Posted on
Artificial Intelligence

Artificial Intelligence Interview Questions

Author
  • User
    linuxbash
    Posts by this author
    Posts by this author

Artificial Intelligence Interview Questions — A Linux Bash-Friendly Study Guide

If you’re prepping for an AI/ML interview and you live in the terminal, you have a superpower most candidates overlook. Interviews test not only your understanding of ML theory but also your ability to get work done reproducibly and quickly. This post gives you a command-line-first way to study core AI interview questions and back them up with small, runnable examples you can practice right in Bash.

What you’ll get:

  • Why these questions matter and how they’re framed

  • 3–5 actionable, hands-on exercises you can run in minutes

  • A compact Q&A you can rehearse

  • Clear, distro-specific install commands (apt, dnf, zypper)

Why this topic is worth your time

  • Interviews probe practical fluency: Can you reason about bias–variance, select the right metric for imbalanced data, avoid leakage, and ship something reproducible? Doing this in Bash demonstrates you can execute under constraints.

  • Terminal muscle memory is speed: Spinning up an environment, training a quick model, and verifying metrics on the fly is exactly what many on-site tasks demand.

  • Reproducibility wins offers: Employers want candidates who can turn theory into artifacts (scripts, models, metrics) that others can run.

Prerequisites: Install the tools

Use your package manager to install Python, compilers (often needed for Python wheels), Git, curl, and jq (for JSON).

  • Debian/Ubuntu (apt):

    sudo apt update
    sudo apt install -y python3 python3-venv python3-pip build-essential git curl jq
    
  • Fedora/RHEL/CentOS (dnf):

    sudo dnf install -y python3 python3-pip gcc gcc-c++ make git curl jq
    
  • openSUSE (zypper):

    sudo zypper refresh
    sudo zypper install -y python3 python3-pip gcc gcc-c++ make git curl jq
    

Create and activate a virtual environment:

python3 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip

Then install the Python stack we’ll use:

pip install numpy pandas scikit-learn joblib matplotlib

The 5 interview themes (and what you’re expected to show)

  • Fundamentals

    • Typical question: “Explain bias–variance trade-off.” Show you know over/underfitting and how regularization, more data, and model complexity affect it.
    • Be ready to talk cross-validation, scaling, leakage prevention.
  • Deep learning basics

    • Typical question: “When do you prefer ReLU vs. tanh? What is vanishing gradient?”
    • Know high-level architectures (CNN, RNN, Transformers) and where they shine.
  • Metrics and evaluation

    • Typical question: “Accuracy is 99%—is that good?” For imbalance, talk precision/recall, PR AUC, cost of errors, calibration, and confusion matrices.
  • Data handling

    • Typical question: “How do you handle leakage?” Show splitting before transforms, using Pipelines, and disciplined feature engineering.
  • MLOps and systems

    • Typical question: “Batch vs. online inference trade-offs?” Discuss latency, throughput, autoscaling, idempotency, and monitoring drift.

Actionable practice you can run now

1) Make a reproducible ML environment

  • Why: Interviewers love candidates who can set up, pin, and share environments quickly.

  • Do this:

    # already inside venv
    pip freeze > requirements.txt
    sha256sum requirements.txt > requirements.txt.sha256
    git init && git add requirements.txt requirements.txt.sha256 && git commit -m "Reproducible env"
    

2) Train and evaluate a tiny model in under a minute

  • Why: Show end-to-end competency—data prep, training, metrics, artifacts.

  • Create a training script:

    cat > train.py <<'PY'
    import os, json, random
    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import StandardScaler
    from sklearn.linear_model import LogisticRegression
    from sklearn.pipeline import Pipeline
    from sklearn.metrics import accuracy_score, precision_recall_fscore_support, confusion_matrix
    import joblib
    
    # Reproducibility
    random.seed(42); np.random.seed(42)
    
    data = load_iris(as_frame=True)
    df = data.frame.copy()
    df.columns = ['sepal_length','sepal_width','petal_length','petal_width']
    df['target'] = data.target
    
    X = df[['sepal_length','sepal_width','petal_length','petal_width']]
    y = df['target']
    
    X_train, X_test, y_train, y_test = train_test_split(
      X, y, test_size=0.2, random_state=42, stratify=y)
    
    pipe = Pipeline([
      ('scaler', StandardScaler()),
      ('clf', LogisticRegression(max_iter=200))
    ])
    pipe.fit(X_train, y_train)
    y_pred = pipe.predict(X_test)
    
    acc = accuracy_score(y_test, y_pred)
    prec, rec, f1, _ = precision_recall_fscore_support(
      y_test, y_pred, average='macro', zero_division=0)
    cm = confusion_matrix(y_test, y_pred).tolist()
    
    metrics = {
      'accuracy': acc,
      'precision_macro': prec,
      'recall_macro': rec,
      'f1_macro': f1,
      'confusion_matrix': cm
    }
    print(json.dumps(metrics, indent=2))
    with open('metrics.json','w') as f: json.dump(metrics, f, indent=2)
    
    joblib.dump(pipe, 'model.joblib')
    with open('labels.json','w') as f: json.dump(data.target_names.tolist(), f)
    
    df.to_csv('iris.csv', index=False)
    print("Artifacts: model.joblib, metrics.json, iris.csv, labels.json")
    PY
    
    python train.py
    jq . metrics.json
    

3) Explore data from the shell (just like on-site)

  • Why: Rapid data triage is a common whiteboard/terminal drill.

  • Create a CSV and inspect it:

    # iris.csv already created by train.py with clean headers
    wc -l iris.csv
    head -5 iris.csv
    # Class distribution
    cut -d, -f5 iris.csv | tail -n +2 | sort | uniq -c
    # Quick mean of sepal_length (column 1), skipping header
    awk -F, 'NR>1{sum+=$1; n++} END{print "mean(sepal_length)=",sum/n}' iris.csv
    
  • Read metrics without writing extra Python:

    jq '.accuracy, .f1_macro' metrics.json
    

4) Ship a minimal CLI predictor

  • Why: Prove you can turn a model into a tool. Many interviews include “wire up inference” tasks.

  • Create a simple predictor that reads JSON from stdin:

    cat > predict.py <<'PY'
    #!/usr/bin/env python3
    import sys, json, joblib, numpy as np
    
    model = joblib.load('model.joblib')
    labels = json.load(open('labels.json'))
    
    payload = json.load(sys.stdin)
    feats = [payload['sepal_length'], payload['sepal_width'],
           payload['petal_length'], payload['petal_width']]
    probs = model.predict_proba([feats])[0]
    idx = int(np.argmax(probs))
    out = {
      "predicted_index": idx,
      "predicted_label": labels[idx],
      "probabilities": {labels[i]: float(p) for i,p in enumerate(probs)}
    }
    print(json.dumps(out, indent=2))
    PY
    chmod +x predict.py
    
    echo '{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.2}' | ./predict.py
    

5) Lock down reproducibility talking points

  • Why: It’s a frequent interview dimension (and an easy win).

  • Show artifacts and provenance:

    pip freeze > requirements.txt
    python - <<'PY'
    import json, platform, sys
    print(json.dumps({
    "python": sys.version,
    "platform": platform.platform()
    }, indent=2))
    PY
    sha256sum model.joblib iris.csv > checksums.txt
    git add metrics.json model.joblib iris.csv labels.json predict.py train.py requirements.txt checksums.txt
    git commit -m "Add minimal model, metrics, and inference CLI"
    

Common pitfalls interviewers probe (and how to answer)

  • Data leakage

    • Pitfall: Scale on full data, then split. Fix: split first, or use Pipelines so transforms fit only on training folds. Mention Pipeline and cross_val_score.
  • Wrong metric choice

    • Pitfall: Using accuracy on imbalanced data. Fix: use precision/recall, PR AUC, class weights, cost-sensitive thresholds. Justify with business costs.
  • Overfitting and generalization

    • Pitfall: Optimizing on test set. Fix: nested CV or a truly held-out set; use regularization and early stopping; monitor learning curves.
  • Reproducibility gaps

    • Pitfall: “It works on my machine.” Fix: pin deps, set seeds, capture hardware/software metadata, checksum data/models, optional containers.
  • Inference system design

    • Pitfall: Ignoring latency/throughput trade-offs. Fix: discuss batching, warm starts, vectorized featurization, autoscaling, caching, and observability.

Quick-fire interview Q&A to rehearse

  • Q: Bias vs. variance?

    • A: Bias is error from simplifying assumptions; variance is sensitivity to data fluctuations. Regularization and more data reduce variance; more expressive models reduce bias.
  • Q: Why scale features?

    • A: Many models (logistic regression, SVM, KNN) and optimizers converge faster and behave better when features are on similar scales.
  • Q: L1 vs. L2 regularization?

    • A: L1 encourages sparsity (feature selection); L2 shrinks weights uniformly to reduce variance. Elastic Net mixes both.
  • Q: Class imbalance strategy?

    • A: Adjust threshold, use class weights or resampling, monitor PR AUC/recall, and align to misclassification costs.
  • Q: Cross-validation: when and why?

    • A: For robust generalization estimates, hyperparameter tuning, and avoiding optimistic bias from a single split.
  • Q: Preventing leakage?

    • A: Split before transforms; use Pipelines; treat time-series with forward-chaining; keep target-dependent features out.
  • Q: Over/underfitting signs?

    • A: High train/low test performance = overfit; both low = underfit. Adjust model capacity, regularization, or data.
  • Q: ROC AUC vs. PR AUC?

    • A: PR AUC is more informative with heavy class imbalance; ROC can look good even with poor positive class performance.
  • Q: Batch vs. online inference?

    • A: Batch optimizes throughput/cost for non-urgent tasks; online optimizes latency for user-facing needs; consider autoscaling, caching, and warm models.
  • Q: Monitoring in production?

    • A: Track latency, errors, drift (feature/label), data quality, calibration, and business KPIs; alert on deviations.

Conclusion and next steps (CTA)

You now have a terminal-first playbook: set up a reproducible environment, train and evaluate a tiny model, inspect data and metrics from Bash, and ship a minimal CLI predictor—all while rehearsing the “why” behind your choices.

Your next steps:

  • Time-box yourself: rebuild this repo from scratch in 15 minutes.

  • Extend predict.py into a FastAPI service, add logging, and containerize it.

  • Add a Makefile target for train/test/infer to showcase automation in interviews.

If this helped, turn it into your personal interview template—swap in a different dataset, add a confusion matrix plot, and practice explaining each design choice as you type the commands.