1What is Artificial Intelligence?

Artificial Intelligence (AI) is the simulation of human intelligence processes by computer systems. The term was coined in 1956 by John McCarthy at the Dartmouth Conference, but the ideas behind it stretch back to Alan Turing's foundational 1950 paper "Computing Machinery and Intelligence," where he asked the famous question: "Can machines think?"

At its core, AI refers to machines that can perform tasks that would normally require human intelligence — things like understanding natural language, recognising faces, playing chess, diagnosing diseases, or driving a car. The key insight is that "intelligence" is not magic — it is pattern recognition, reasoning, and decision-making under uncertainty — all of which can be approximated computationally.

Types of AI by Capability

🐣 Narrow AI (ANI)

Designed for one specific task. All current commercial AI falls here — ChatGPT, Google Search, Siri, Alexa, recommendation engines.

Where we are today

🧠 General AI (AGI)

Hypothetical AI with human-level reasoning across all domains — can learn any intellectual task a human can. Debated among researchers.

Theoretical / future

🚀 Superintelligent AI (ASI)

AI that surpasses human intelligence in every domain. Subject of both excitement and existential concern in AI safety research.

Speculative / not yet real

Types of AI by Functionality

TypeDescriptionExampleLearns?
Reactive Machines No memory, reacts only to current input Deep Blue (Chess) No
Limited Memory Uses past data for decisions Self-driving cars, ChatGPT Yes
Theory of Mind Understands emotions, beliefs of others Research stage only Partially
Self-Aware AI Has consciousness, self-understanding Does not exist yet Unknown

AI vs ML vs Deep Learning — The Real Difference

These three terms are often used interchangeably but they are not the same thing. Think of them as nested circles:

💡 Key Mental Model AI ⊃ Machine Learning ⊃ Deep Learning. Every deep learning system is a machine learning system, and every machine learning system is an AI system — but not the other way around. Traditional AI (like rule-based expert systems) does not use machine learning at all.

Real-World Applications of AI in 2026

2History and Evolution of AI

Understanding where AI came from gives you critical context for why it works the way it does today, and why certain techniques exist. The field did not progress in a straight line — it had two major "winters" where funding dried up due to overpromising and underdelivering.

EraKey MilestoneWhy It Matters
1950Turing Test proposed by Alan TuringFirst formal definition of machine intelligence
1956Dartmouth Conference — AI named as a fieldMcCarthy, Minsky, Shannon gathered to define AI
1958Perceptron invented by RosenblattFirst artificial neural network — foundation of DL
1966–74First AI WinterNLP machines failed; funding cut; optimism crashed
1980sExpert Systems riseRule-based AI for medical/business diagnosis
1987–93Second AI WinterExpert systems too rigid; LISP machines failed
1997Deep Blue beats Kasparov at chessProved AI can beat world champions in bounded domains
2006Hinton's Deep Belief Networks paperDeep learning became viable again
2012AlexNet wins ImageNet by huge marginDeep learning's public breakthrough — CNN revolution begins
2016AlphaGo beats Lee Sedol at GoReinforcement learning milestone; Go has more positions than atoms in universe
2017Transformer architecture published (Attention Is All You Need)Foundation of GPT, BERT, all modern LLMs
2022-26ChatGPT, Gemini, Claude, GPT-4o, SoraGenerative AI enters mainstream; multimodal systems become common

3Machine Learning — Core Concepts

Machine Learning is a method of data analysis that automates analytical model building. It is based on the idea that systems can learn from data, identify patterns, and make decisions with minimal human intervention. Unlike traditional programming where you give the computer explicit rules, in ML you give the computer data and let it find the rules itself.

📐 Formal Definition Tom Mitchell (1997): "A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E."

The Three Learning Paradigms

TypeInput DataGoalExamples
Supervised Learning Labelled (X, y pairs) Learn a mapping from X → y Spam detection, house price prediction, image classification
Unsupervised Learning Unlabelled (X only) Find hidden structure in data Customer segmentation, anomaly detection, topic modelling
Reinforcement Learning States, Actions, Rewards Maximise cumulative reward over time Game playing (AlphaGo), robot control, recommendation tuning
Semi-Supervised Small labelled + large unlabelled Combine both to improve learning Image classification with few labelled examples
Self-Supervised Data creates its own labels Pre-train representations GPT (predict next word), BERT (mask language modelling)

Key ML Terminology — Know These Cold for Interviews

⚠️ Common Mistake Never use your test set for model selection or hyperparameter tuning. If you do, your model's test accuracy is no longer a reliable estimate of real-world performance — you've indirectly trained on the test set.

How a Model Learns — Gradient Descent Explained Simply

Most ML algorithms learn by minimising a loss function — a measure of how wrong the model's predictions are. Gradient descent is the algorithm that performs this minimisation:

  1. Initialise: Start with random model weights (parameters)
  2. Forward pass: Make predictions using current weights
  3. Calculate loss: Measure how wrong the predictions are (e.g., Mean Squared Error)
  4. Backpropagation: Calculate the gradient (direction of steepest increase) of the loss
  5. Update weights: Move weights in the opposite direction of the gradient, scaled by the learning rate
  6. Repeat: Continue until the loss stops decreasing (convergence)
📐 Gradient Descent Update Rule w = w - α × ∂L/∂w
Where: w = weights, α = learning rate, ∂L/∂w = gradient of loss with respect to weights

4Supervised Learning — Algorithms with Python Code

Supervised learning is the most widely used paradigm in practical ML. You have a labelled dataset and you want to learn a function that maps inputs to outputs. There are two main tasks: regression (predict a continuous value) and classification (predict a discrete category).

4.1 Linear Regression

Linear regression assumes the relationship between input X and output y is a straight line. It finds the best-fit line through your data by minimising the sum of squared errors. Despite its simplicity, it is extremely powerful when the assumption holds and is the foundation of many advanced models.

📐 Linear Regression Formula y = β₀ + β₁x₁ + β₂x₂ + ... + βₙxₙ + ε
Where: β₀ = intercept, β₁...βₙ = coefficients (learnt from data), ε = error term
🐍 Python — Linear Regression with scikit-learn
# Linear Regression: Predict house price from size
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt

# ─── 1. Create sample dataset ───
np.random.seed(42)
house_size = np.random.randint(500, 3500, 100)           # sq ft
price = house_size * 150 + np.random.normal(0, 20000, 100)  # in Rs

X = house_size.reshape(-1, 1)  # Reshape for sklearn (n_samples, n_features)
y = price

# ─── 2. Split data 80/20 ───
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
print(f"Training samples: {len(X_train)}, Test samples: {len(X_test)}")

# ─── 3. Train the model ───
model = LinearRegression()
model.fit(X_train, y_train)

# ─── 4. View learnt parameters ───
print(f"Intercept (β₀): {model.intercept_:.2f}")
print(f"Coefficient (β₁): {model.coef_[0]:.2f}")
# Output: Intercept ≈ 1200, Coefficient ≈ 150 (close to our true values!)

# ─── 5. Make predictions ───
y_pred = model.predict(X_test)

# ─── 6. Evaluate ───
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)

print(f"RMSE: {rmse:.2f}")      # Root Mean Squared Error (in same units as y)
print(f"R² Score: {r2:.4f}")   # 1.0 = perfect, 0 = as good as mean baseline

# ─── 7. Predict for a new house ───
new_house = np.array([[1800]])  # 1800 sq ft
predicted_price = model.predict(new_house)[0]
print(f"Predicted price for 1800 sq ft: ₹{predicted_price:,.0f}")

Evaluation Metrics for Regression

MetricFormulaInterpretationRange
MAEmean(|y - ŷ|)Average absolute error; easy to interpret0 to ∞, lower is better
MSEmean((y - ŷ)²)Penalises large errors more; differentiable0 to ∞, lower is better
RMSE√MSESame units as y; most commonly reported0 to ∞, lower is better
R² Score1 - SS_res/SS_totProportion of variance explained by model-∞ to 1, higher is better

4.2 Logistic Regression (Classification)

Despite the name, Logistic Regression is a classification algorithm, not regression. It models the probability that an input belongs to a particular class, using the sigmoid function to squish any input to the range (0, 1).

🐍 Python — Logistic Regression for Spam Detection
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import StandardScaler

# Simulate email spam dataset (binary classification)
X, y = make_classification(
    n_samples=1000, n_features=20,
    n_informative=10, random_state=42
)
# y = 0 (not spam) or 1 (spam)

# Split and scale (IMPORTANT: scale features for logistic regression)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)  # fit on train only!
X_test  = scaler.transform(X_test)       # transform test with same scaler

# Train
clf = LogisticRegression(max_iter=200, random_state=42)
clf.fit(X_train, y_train)

# Evaluate
y_pred = clf.predict(X_test)
print(classification_report(y_test, y_pred, target_names=['Not Spam', 'Spam']))
print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))

# Get probability (not just class) for a single email
email_features = X_test[0].reshape(1, -1)
prob = clf.predict_proba(email_features)[0]
print(f"P(Not Spam) = {prob[0]:.3f}, P(Spam) = {prob[1]:.3f}")

4.3 Decision Trees and Random Forests

Decision Trees split data based on feature thresholds, forming a tree of if-else rules. They are highly interpretable. Random Forests combine hundreds of decision trees, each trained on a random subset of data and features, then vote on the final prediction — this is called ensemble learning.

🐍 Python — Random Forest Classifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris

# Classic iris flower classification dataset
iris = load_iris()
X, y = iris.data, iris.target
# Features: sepal length, sepal width, petal length, petal width
# Classes: 0=setosa, 1=versicolor, 2=virginica

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

rf = RandomForestClassifier(
    n_estimators=100,   # 100 trees
    max_depth=5,        # limit depth to avoid overfitting
    random_state=42
)
rf.fit(X_train, y_train)
print(f"Accuracy: {rf.score(X_test, y_test):.4f}")

# Feature importance — which features matter most?
importances = rf.feature_importances_
for name, imp in zip(iris.feature_names, importances):
    print(f"  {name}: {imp:.4f}")
# Petal length and petal width will be most important (~0.85 combined)

Classification Metrics — Know the Difference

MetricFormulaWhen to Use
Accuracy(TP+TN) / TotalBalanced classes; avoid with imbalanced data
PrecisionTP / (TP+FP)When false positives are costly (spam filter — don't block real email)
RecallTP / (TP+FN)When false negatives are costly (cancer detection — don't miss sick patients)
F1 Score2 × (P×R)/(P+R)Balance of precision and recall; good for imbalanced classes
ROC-AUCArea under ROC curveOverall discriminative power across all thresholds

5Unsupervised Learning — Patterns Without Labels

Unsupervised learning works on data without labels. The goal is to discover hidden structure — groupings, patterns, or compressed representations — entirely from the data itself. It is used when labelling data is expensive, impossible, or when you do not know what to look for in advance.

5.1 K-Means Clustering

K-Means is the most popular clustering algorithm. It partitions data into K clusters where each data point belongs to the cluster with the nearest centroid (mean). The algorithm alternates between assigning points to clusters and updating centroids until convergence.

📐 K-Means Objective Function Minimise: Σᵢ Σₓ∈Cᵢ ||x - μᵢ||² (sum of squared distances to cluster centroid)
🐍 Python — K-Means Clustering
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
import numpy as np

# Generate synthetic customer data (age vs spending score)
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.8, random_state=42)

# ─── Elbow Method: Find optimal K ───
inertias = []
k_range = range(1, 11)
for k in k_range:
    km = KMeans(n_clusters=k, random_state=42, n_init=10)
    km.fit(X)
    inertias.append(km.inertia_)
# Plot inertia vs K — look for the "elbow" where it stops dropping sharply

# ─── Train with K=4 (the elbow) ───
kmeans = KMeans(n_clusters=4, random_state=42, n_init=10)
labels = kmeans.fit_predict(X)

# Evaluate clustering quality
sil_score = silhouette_score(X, labels)
print(f"Silhouette Score: {sil_score:.4f}")
# Range: -1 (bad) to 1 (perfect). Above 0.5 is generally good.

# Cluster centers
print("Cluster Centers:")
print(kmeans.cluster_centers_)

# Assign new customer to a cluster
new_customer = np.array([[3.5, 2.1]])
cluster = kmeans.predict(new_customer)[0]
print(f"New customer belongs to cluster: {cluster}")

5.2 Principal Component Analysis (PCA)

PCA is a dimensionality reduction technique that finds the directions of maximum variance in high-dimensional data and projects data onto these directions (called principal components). It reduces the number of features while retaining most of the information, making models faster and visualisation possible.

🐍 Python — PCA for Dimensionality Reduction
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_breast_cancer

# Breast cancer dataset: 30 features → reduce to 2 for visualisation
data = load_breast_cancer()
X, y = data.data, data.target
print(f"Original shape: {X.shape}")  # (569, 30)

# Always scale before PCA (PCA is sensitive to scale)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Reduce to 2 components for 2D plot
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
print(f"Reduced shape: {X_pca.shape}")  # (569, 2)

# How much variance do the 2 components explain?
print(f"Variance explained: {pca.explained_variance_ratio_.sum():.2%}")
# Typically ~63% for this dataset — 63% of info in just 2 dimensions!

# Find how many components needed for 95% variance
pca_full = PCA(n_components=0.95)  # keep 95% variance
X_full_pca = pca_full.fit_transform(X_scaled)
print(f"Components for 95% variance: {pca_full.n_components_}")  # ~10

6Deep Learning & Neural Networks

Deep Learning is a subset of Machine Learning that uses artificial neural networks with many layers (hence "deep") to learn representations of data at progressively higher levels of abstraction. It powers almost every AI breakthrough in the last 10 years — image recognition, language models, text-to-speech, generative AI, and more.

How a Neural Network Works

A neural network consists of layers of interconnected nodes (neurons). Each connection has a weight. Data flows forward through the network (forward pass), and errors are propagated backward (backpropagation) to update weights. This cycle repeats for thousands or millions of iterations.

Key Activation Functions

FunctionFormulaRangeBest UsedWeakness
Sigmoid1/(1+e⁻ˣ)(0, 1)Binary output layerVanishing gradient
Tanh(eˣ-e⁻ˣ)/(eˣ+e⁻ˣ)(-1, 1)Hidden layers (older)Vanishing gradient
ReLUmax(0, x)[0, ∞)Hidden layers (default choice)Dying ReLU
Leaky ReLUmax(0.01x, x)(-∞, ∞)Fixes dying ReLUNot adaptive
Softmaxeˣⁱ / Σeˣʲ(0,1) sums to 1Multi-class outputComputationally heavy
🐍 Python — Neural Network with TensorFlow/Keras
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np

# Load MNIST digit recognition (28x28 greyscale images, digits 0-9)
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()

# Preprocess: normalize to [0,1] and flatten 28x28 → 784
X_train = X_train.reshape(-1, 784) / 255.0
X_test  = X_test.reshape(-1, 784) / 255.0

# ─── Build the model ───
model = keras.Sequential([
    layers.Dense(256, activation='relu', input_shape=(784,)),
    layers.Dropout(0.3),          # Randomly drop 30% of neurons to prevent overfitting
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.2),
    layers.Dense(10, activation='softmax')  # 10 output classes (digits 0-9)
])

# ─── Compile ───
model.compile(
    optimizer='adam',                      # Adaptive learning rate optimiser
    loss='sparse_categorical_crossentropy',  # Multi-class classification loss
    metrics=['accuracy']
)
model.summary()  # ~235,146 trainable parameters

# ─── Train ───
history = model.fit(
    X_train, y_train,
    epochs=10,
    batch_size=128,
    validation_split=0.1,
    verbose=1
)

# ─── Evaluate on test set ───
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {test_acc:.4f}")  # Typically ~97.5-98%

# ─── Predict a single image ───
img = X_test[0].reshape(1, 784)
probabilities = model.predict(img)[0]
predicted_digit = np.argmax(probabilities)
print(f"Predicted digit: {predicted_digit} (confidence: {probabilities[predicted_digit]:.2%})")

CNN, RNN, Transformer — When to Use Which

ArchitectureBest ForKey FeatureFamous Examples
CNN
(Convolutional Neural Network)
Images, videos, spatial data Shared convolutional filters detect local patterns regardless of position ResNet, VGG, EfficientNet, YOLO
RNN/LSTM
(Recurrent Neural Network)
Sequential data, time series, older NLP Maintains hidden state across sequence; remembers past context LSTM for speech recognition, seq2seq translation
Transformer NLP, multimodal, everything modern Self-attention: each token attends to every other token simultaneously BERT, GPT-4, Claude, Gemini, Sora
GAN
(Generative Adversarial Network)
Image generation, data augmentation Two networks (generator vs discriminator) compete, improving each other StyleGAN, BigGAN, image-to-image translation

7Data Science & the Complete ML Pipeline

Data science is the discipline of extracting actionable insight from raw data. In practice, it is 80% data cleaning and preparation, and 20% actual modelling. Every ML project follows a pipeline — skipping any step leads to poor-quality models, no matter how sophisticated the algorithm.

The 7-Step ML Pipeline

Step 1 — Problem Definition

Is this regression or classification? What does success look like? What metric matters? Define this before touching data.

Step 2 — Data Collection

Web scraping, APIs, surveys, sensors, databases. Data quality > data quantity. Garbage in = garbage out.

Step 3 — Exploratory Data Analysis (EDA)

Understand distributions, correlations, outliers, class imbalance. df.describe(), df.info(), heatmaps, boxplots.

Step 4 — Data Preprocessing

Handle missing values, encode categories, scale features, remove outliers, engineer new features.

Step 5 — Model Training & Selection

Try multiple models, use cross-validation, tune hyperparameters with GridSearchCV or Optuna.

Step 6 — Model Evaluation

Evaluate on held-out test set using the right metrics. Check for data leakage. Examine error cases.

Step 7 — Deployment & Monitoring

Serve model via REST API (FastAPI/Flask), monitor for drift, retrain periodically as data changes.

Data Preprocessing — The Most Important Step

🐍 Python — Complete Preprocessing Pipeline
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

# Sample messy dataset
df = pd.DataFrame({
    'age':    [25, np.nan, 35, 28, 45],
    'salary': [50000, 60000, np.nan, 75000, 90000],
    'city':   ['Mumbai', 'Delhi', 'Mumbai', None, 'Bangalore'],
    'hired':  [1, 0, 1, 1, 0]
})

# Define which columns are numeric vs categorical
numeric_cols = ['age', 'salary']
cat_cols = ['city']

# Numeric pipeline: impute missing with median, then scale
num_pipeline = Pipeline([
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler())
])

# Categorical pipeline: impute missing with mode, then one-hot encode
cat_pipeline = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
])

# Combine into one preprocessor
preprocessor = ColumnTransformer([
    ('num', num_pipeline, numeric_cols),
    ('cat', cat_pipeline, cat_cols)
])

# Prepare features and target
X = df.drop('hired', axis=1)
y = df['hired']

# Fit and transform
X_processed = preprocessor.fit_transform(X)
print(f"Processed shape: {X_processed.shape}")
# Original: (5, 3) → Processed: (5, 5) [2 scaled numerics + 3 one-hot cities]

8Algorithm Complexity Analysis

Understanding the time and space complexity of ML algorithms is critical for interviews and for choosing the right algorithm in production. A model that takes hours to train or gigabytes of memory is not practical even if its accuracy is high.

Common ML Algorithm Complexities

AlgorithmTraining TimePrediction TimeSpaceScalability
Linear/Logistic Regression O(n·d) O(d) O(d) Excellent
Decision Tree O(n·d·log n) O(depth) O(nodes) Good
Random Forest (k trees) O(k·n·d·log n) O(k·depth) O(k·nodes) Moderate
SVM (kernel) O(n²·d) to O(n³) O(n_sv·d) O(n²) Poor (large n)
KNN (k-nearest) O(1) [lazy] O(n·d) O(n·d) Poor (large n)
K-Means O(n·K·d·i) O(K·d) O(n+K) Good
Neural Network (Dense) O(e·n·layers·units²) O(layers·units²) O(layers·units²) Good with GPU

n = samples, d = features, k = trees/clusters, i = iterations, e = epochs, n_sv = support vectors

Bias-Variance Tradeoff — The Central Problem in ML

📐 Error Decomposition Total Error = Bias² + Variance + Irreducible Noise

Bias = How wrong on average is the model's assumption about the data structure?
Variance = How much does model change if trained on different data samples?
ScenarioBiasVarianceSymptomFix
UnderfittingHighLowBad on both train and testMore complex model, more features, less regularisation
OverfittingLowHighGreat train, poor testMore data, dropout, regularisation (L1/L2), simpler model
IdealLowLowGood on bothRight model complexity + sufficient data

9Python Libraries Cheat Sheet

These are the essential libraries you must know for any AI/ML/Data Science role in India. Every data science interview will test your knowledge of at least NumPy, Pandas, and scikit-learn.

NumPy — Arrays
import numpy as np
a = np.array([1,2,3])
np.zeros((3,3))
np.dot(A, B)
np.reshape(a, (-1,1))
np.mean(a); np.std(a)
a[a > 2] # boolean mask
Pandas — DataFrames
import pandas as pd
df = pd.read_csv('data.csv')
df.head(); df.describe()
df['col'].value_counts()
df.dropna(); df.fillna(0)
df.groupby('city').mean()
df.merge(df2, on='id')
Scikit-Learn — ML
from sklearn.* import ...
model.fit(X_train, y_train)
model.predict(X_test)
model.score(X_test, y_test)
cross_val_score(model, X, y)
GridSearchCV(model, params)
Pipeline([steps...])
TensorFlow / Keras
import tensorflow as tf
model = keras.Sequential([...])
model.compile(loss=..., opt=...)
model.fit(X, y, epochs=10)
model.evaluate(X_test, y_test)
model.save('model.h5')
tf.keras.models.load_model(...)
Matplotlib — Plots
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.scatter(x, y, c=labels)
plt.hist(data, bins=30)
plt.xlabel('X'); plt.ylabel('Y')
plt.title('My Plot')
plt.savefig('plot.png')
Seaborn — Stats Viz
import seaborn as sns
sns.heatmap(df.corr())
sns.boxplot(x='col', data=df)
sns.pairplot(df)
sns.histplot(df['col'])
sns.countplot(x='target', data=df)

🎯 Practice Problems

Click any problem to reveal a hint. Solve these before your next interview — they cover the most asked AI/ML problem types.

1. Implement Linear Regression from Scratch (No Libraries) Easy
Write a Python class LinearRegressionScratch with fit(X, y) and predict(X) methods using only NumPy. Use the normal equation or gradient descent.
💡 Hint: Normal Equation: β = (XᵀX)⁻¹Xᵀy. Use np.linalg.inv() for matrix inversion. Add a column of 1s to X for the intercept term.
2. Handle Class Imbalance in a Fraud Detection Dataset Medium
You have a dataset where 99% of transactions are legitimate and 1% are fraud. A model that predicts "not fraud" for everything gets 99% accuracy but is useless. Fix this.
💡 Hint: Try SMOTE (Synthetic Minority Oversampling), class_weight='balanced' in sklearn, or use F1/AUC instead of accuracy as your metric. Consider undersampling the majority class.
3. Build a Text Classifier Without Pretrained Models Medium
Given a dataset of movie reviews labelled as positive/negative, build a sentiment classifier using TF-IDF features and a simple classifier (Naive Bayes or Logistic Regression).
💡 Hint: Use sklearn's TfidfVectorizer to convert text to numerical features. Pipeline: TfidfVectorizer → LogisticRegression. Use fetch_20newsgroups or IMDB dataset from sklearn.
4. Detect Overfitting Using Learning Curves Easy
Train a decision tree on a dataset. Plot training accuracy and validation accuracy vs. number of training samples (learning curve). Identify if your model is overfitting or underfitting.
💡 Hint: Use sklearn.model_selection.learning_curve(). If training score is high but validation score is low, it is overfitting. If both are low, it is underfitting.
5. Implement K-Means from Scratch Medium
Write KMeans(k) class with fit(X) and predict(X) using only NumPy. Implement random centroid initialisation, assignment step, and update step. Run for 100 iterations.
💡 Hint: Assignment step: labels = argmin distance from each point to each centroid. Update step: centroids = mean of all points in each cluster. Use np.linalg.norm for distance.
6. Explain a Black-Box Model's Prediction Using SHAP Hard
Train a Random Forest on the Titanic dataset. Use SHAP (SHapley Additive exPlanations) to explain which features most influenced a specific passenger's survival prediction.
💡 Hint: pip install shap. Use shap.TreeExplainer(model), then shap_values = explainer(X_test). shap.waterfall_plot() shows per-prediction feature contributions. This is called Explainable AI (XAI).
7. Build a CNN for Image Classification Hard
Using CIFAR-10 (10 classes of 32x32 images), build a CNN with at least 3 convolutional layers. Achieve above 70% test accuracy. Use data augmentation to improve performance.
💡 Hint: Architecture: Conv2D → MaxPool → Conv2D → MaxPool → Flatten → Dense. Use ImageDataGenerator for augmentation (flip, rotate, zoom). Add BatchNormalization to stabilise training.
8. Perform Hyperparameter Tuning with Cross-Validation Medium
Use GridSearchCV or RandomizedSearchCV to find the best hyperparameters for a Random Forest on the breast cancer dataset. Report the best parameters and their cross-validated accuracy.
💡 Hint: Parameters to tune: n_estimators (50-300), max_depth (3-15), min_samples_split (2-10). Use cv=5 for 5-fold cross-validation. RandomizedSearchCV is faster than GridSearchCV for large spaces.

🧠 Interactive Quiz — Test Yourself

10 questions covering AI, ML, and Data Science concepts. Click an option to see if you're right. Track your score at the end.

Q1. Which type of machine learning does NOT require labelled training data?

A) Supervised Learning
B) Unsupervised Learning
C) Transfer Learning
D) Reinforcement Learning (uses reward signals)
✅ Correct! Unsupervised learning works only on unlabelled data — finding hidden patterns like clusters or dimensions without any predefined categories.

Q2. Your model has 99% training accuracy but 60% test accuracy. What is happening?

A) Underfitting — model is too simple
B) Overfitting — model memorised training data
C) Data leakage from test set
D) Wrong evaluation metric chosen
✅ Correct! A large gap between training accuracy and test accuracy is the classic sign of overfitting. The model has memorised training examples rather than learning generalizable patterns.

Q3. Which activation function is most commonly used in hidden layers of modern deep neural networks?

A) Sigmoid
B) Tanh
C) ReLU (Rectified Linear Unit)
D) Softmax
✅ Correct! ReLU (max(0, x)) is the default choice for hidden layers because it is computationally simple, does not suffer from vanishing gradients for positive inputs, and typically trains faster than Sigmoid/Tanh.

Q4. In the K-Means algorithm, what does the "elbow method" help you determine?

A) Whether the data is linearly separable
B) The optimal number of clusters (K)
C) The learning rate for gradient descent
D) Whether the data needs normalisation
✅ Correct! The elbow method plots inertia (within-cluster sum of squares) vs. K. You pick K at the "elbow" — where adding more clusters stops giving significant benefit.

Q5. Which metric should you prioritise for a cancer diagnosis model where missing a sick patient is very costly?

A) Precision
B) Recall
C) Accuracy
D) Specificity
✅ Correct! Recall = TP/(TP+FN) measures how many actual positives your model catches. When false negatives are very costly (missing cancer), maximise recall, even at the cost of some false positives.

Q6. What is the purpose of Dropout in a neural network?

A) To speed up the forward pass
B) To reduce the learning rate automatically
C) To prevent overfitting by randomly disabling neurons during training
D) To normalise activations across the batch
✅ Correct! Dropout randomly sets a fraction of neurons to zero during each training step. This prevents neurons from co-adapting and forces the network to learn more robust, distributed representations.

Q7. What is the Transformer architecture's key innovation over RNNs?

A) It processes sequences faster by using convolutions
B) Self-attention allows each token to attend to all others simultaneously (parallel processing)
C) It has no trainable parameters
D) It uses reinforcement learning instead of backpropagation
✅ Correct! Transformers process entire sequences in parallel using self-attention, unlike RNNs which process tokens sequentially. This enables much faster training and capture of long-range dependencies — the reason GPT and BERT are so powerful.

Q8. Which of the following is NOT a valid technique to handle class imbalance?

A) SMOTE (Synthetic Minority Oversampling)
B) Undersampling the majority class
C) Using class weights in the loss function
D) Increasing the learning rate
✅ Correct! Increasing the learning rate is not a solution for class imbalance — it affects convergence speed, not class representation. The other three are all standard, valid techniques for handling imbalanced datasets.

Q9. What does R² (R-squared) score of 0.0 mean in regression?

A) The model has 0% accuracy
B) The model is no better than predicting the mean of y for every input
C) All predictions are zero
D) The model has perfect predictions
✅ Correct! R² = 0 means the model explains none of the variance — it performs exactly as well as a trivial baseline that always predicts the mean of y. R² = 1 is perfect; R² < 0 means your model is worse than predicting the mean.

Q10. You should NEVER use your test set for which of the following?

A) Final model evaluation after all decisions are made
B) Hyperparameter tuning and model selection
C) Reporting final accuracy in your paper/project
D) Checking model performance once at the end
✅ Correct! Using the test set for model selection or hyperparameter tuning is data leakage. You've indirectly trained on the test set, making your reported accuracy an optimistic overestimate. Use validation set or cross-validation for all tuning decisions.

💼 Interview Questions & Answers

Most asked AI/ML questions at TCS, Infosys, Wipro, Accenture, Amazon, Flipkart, and startups. Click to expand.

What is the difference between a parameter and a hyperparameter?
A parameter is internal to the model and is learnt from the training data — for example, the weights and biases in a neural network, or the coefficients in linear regression. You do not set these manually; the optimiser updates them.

A hyperparameter is set by the user before training begins and controls the learning process itself — for example, the learning rate, number of layers, number of trees, regularisation strength (C in SVM), or batch size. Hyperparameters are tuned using techniques like GridSearchCV, RandomizedSearchCV, or Bayesian optimisation on the validation set.
Explain gradient descent and its variants (SGD, Mini-batch, Adam)
Gradient Descent (Batch GD): Computes gradient using the entire dataset before updating weights. Slow for large datasets but stable convergence.

Stochastic Gradient Descent (SGD): Updates weights after every single sample. Fast and noisy — the noise can actually help escape local minima but makes convergence erratic.

Mini-batch GD: Updates after a batch of samples (e.g., 32, 64, 128). Best of both worlds — faster than batch GD, smoother than SGD. This is what Keras/PyTorch use by default.

Adam: Adaptive Moment Estimation. Combines momentum (remembers past gradients) with adaptive learning rates per parameter. Currently the most popular optimiser. Works well with default settings (lr=0.001, β1=0.9, β2=0.999).
What is regularisation? Explain L1 and L2.
Regularisation adds a penalty term to the loss function to discourage large weights, preventing overfitting by keeping the model simpler.

L2 Regularisation (Ridge): Adds λΣwᵢ² to the loss. Penalises large weights heavily, pushing them towards zero but never exactly to zero. Creates smaller, distributed weights. Better when all features are relevant.

L1 Regularisation (Lasso): Adds λΣ|wᵢ| to the loss. Can push some weights exactly to zero, effectively performing feature selection. Better when you suspect many features are irrelevant.

Elastic Net: Combines both L1 and L2. λ controls total regularisation, and a ratio α controls the L1/L2 mix. Often outperforms either alone when both effects are desired.
How does a Random Forest reduce variance compared to a single Decision Tree?
A single decision tree has high variance — small changes in the training data can lead to very different trees. Random Forest reduces this variance through two key techniques:

1. Bootstrap Aggregating (Bagging): Each tree is trained on a different random sample (with replacement) of the training data. Each tree sees a different version of the data, so the trees are decorrelated.

2. Feature Randomness: At each split, only a random subset of features is considered (typically √d for classification). This ensures trees don't all rely on the same dominant features.

The final prediction is the majority vote (classification) or average (regression) across all trees. Averaging uncorrelated predictions reduces variance while keeping bias similar to a single tree.
What is the Vanishing Gradient problem and how is it solved?
During backpropagation in deep networks, gradients are computed by repeatedly multiplying by the derivative of activation functions. Sigmoid and Tanh derivatives are always < 1 (maximum 0.25 for sigmoid). Multiplying many values < 1 across many layers makes the gradient exponentially small, so early layers learn extremely slowly or not at all — this is the vanishing gradient problem.

Solutions:
1. ReLU activation: Derivative is 1 for positive inputs, so gradients don't shrink through ReLU layers.
2. Batch Normalisation: Normalises layer outputs, keeping gradients in a healthy range.
3. Residual connections (ResNets): Skip connections allow gradients to flow directly through the network, bypassing problematic layers.
4. Careful weight initialisation: Xavier/He initialisation sets initial weights appropriately for the activation function used.
What is data leakage and why is it dangerous?
Data leakage occurs when information from outside the training set is used to create the model, giving it an unfair advantage that will not exist in production. The model appears to perform extremely well in evaluation but fails badly when deployed on real data.

Common forms:
1. Using test set data to tune hyperparameters or select features
2. Fitting a scaler (StandardScaler) on the entire dataset including test data before splitting
3. Including features in the training data that are derived from the target variable (e.g., "customer_churned_next_month" as a feature for churn prediction)
4. Time-series data: using future data to predict past events

Prevention: Always split your data first, then fit all preprocessing (scalers, imputers, encoders) only on the training set. Use sklearn Pipelines to ensure this is done correctly automatically.
What is transfer learning and when should you use it?
Transfer learning is the practice of taking a model pre-trained on a large dataset and adapting it to a new, typically smaller, related task. Instead of training from scratch, you start from a model that already knows good representations.

When to use:
- You have a small labelled dataset (hundreds to thousands of examples) for a task similar to a task with large public datasets
- Training from scratch would be computationally prohibitive
- Similar domain: images → images, text → text

Approaches:
1. Feature extraction: Freeze all pretrained layers, only train a new classification head
2. Fine-tuning: Unfreeze some or all layers and continue training with a very small learning rate

Examples: Using ResNet50 (trained on ImageNet) for medical imaging; using BERT (trained on Wikipedia) for sentiment analysis; using GPT-3 for code generation with a few examples.
Explain Precision, Recall, and F1 — when does each matter?
Precision = TP / (TP + FP) — of all the cases you predicted as positive, how many were actually positive? Use when false positives are costly. Example: Email spam filter — you don't want to mark important emails as spam (false positives are bad).

Recall = TP / (TP + FN) — of all the actual positives, how many did you catch? Use when false negatives are costly. Example: Cancer diagnosis — you don't want to miss actual cancer cases (false negatives are deadly).

F1 Score = 2 × (Precision × Recall) / (Precision + Recall) — harmonic mean of both. Use when you want a single metric that balances both, especially with imbalanced classes where accuracy is misleading.

ROC-AUC: Measures overall ranking quality across all classification thresholds. A score of 0.5 is random; 1.0 is perfect. Useful for comparing models independent of the decision threshold you set.

13AI/ML Learning Roadmap — Zero to Job-Ready

Follow this sequence. Don't jump to deep learning before you're solid on the fundamentals — every shortcut here comes back to haunt you in interviews.

Month 1 — Python & Math Foundations

Python basics (loops, functions, OOP), NumPy arrays, Pandas DataFrames. Linear algebra (matrices, vectors, dot products). Probability basics (Bayes' theorem, distributions). Statistics (mean, variance, correlation, hypothesis testing).

Month 2 — Core Machine Learning

Linear/Logistic Regression from scratch and with sklearn. Decision Trees, Random Forest, SVM, KNN. Model evaluation: cross-validation, confusion matrix, ROC-AUC. Feature engineering, preprocessing pipelines.

Month 3 — Data Science Skills

EDA with Pandas and Seaborn. Data cleaning and preprocessing. Kaggle competitions (start with Titanic, House Prices). Build 2-3 end-to-end ML projects. Learn Matplotlib for visualisation.

Month 4 — Advanced ML & Ensembles

Gradient Boosting (XGBoost, LightGBM, CatBoost). Hyperparameter tuning (GridSearchCV, Optuna). Advanced feature engineering. Handling imbalanced datasets. Time series forecasting basics.

Month 5 — Deep Learning Basics

Neural networks with TensorFlow/Keras. CNNs for image classification. RNNs/LSTMs for sequence data. Transfer learning. GPU training fundamentals (Google Colab is free).

Month 6 — NLP & Transformers

Text preprocessing, TF-IDF, word embeddings. BERT and fine-tuning with HuggingFace. Prompt engineering for LLMs. Build a chatbot or document QA system as a portfolio project.

Month 7-8 — MLOps & Deployment

REST APIs with FastAPI/Flask. Docker basics for model packaging. MLflow for experiment tracking. Basic cloud deployment (Render, HuggingFace Spaces, Google Cloud Run). Model monitoring and drift detection.

Month 9-12 — Portfolio & Job Prep

3-5 strong GitHub projects with documentation. Kaggle Expert rank. Practice ML system design questions. Revise all interview Q&A. Apply to data analyst → data scientist → ML engineer roles progressively.

14Free Resources — Curated for Indian Students

All resources below are completely free. No paid courses needed to become job-ready in AI/ML.

Courses

Practice Platforms

Books (Free PDFs available legally)