PART 1 • FOUNDATIONS • LEVEL 01

AI & Machine Learning Foundations

Build the mental model that makes every later algorithm easier: what intelligence means in software, how machines learn from data, how a model moves from examples to decisions, and how to frame a real problem correctly.

⏱️ 90–120 min🎯 Beginner🧪 2 Interactive Labs💼 Placement Ready
ARTIFICIAL INTELLIGENCE
MACHINE LEARNING
DEEP
LEARNING

Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence

By the End of This Level, You Can

01Explain AI, ML, deep learning and data science without mixing them up.
02Identify features, labels, models, parameters and predictions in a problem.
03Select the correct learning paradigm for a practical situation.
04Describe training, evaluation, inference and the complete ML lifecycle.
05Recognize leakage, underfitting, overfitting and unfair evaluation.
06Trace a small regression program and defend its logic in an interview.

Five Ideas to Recall Before AI & ML

No advanced mathematics is required here. Start with these familiar programming ideas.

INPUTData enters a system

Numbers, text, images, audio or sensor readings can become model inputs.

PROCESSRules transform input

A program applies instructions; an ML model applies a learned mathematical function.

OUTPUTA result is produced

The output may be a class, number, recommendation, generated text or action.

VARIABLEValues can change

Model parameters are adjustable values learned during training.

FUNCTIONInputs map to outputs

A model is a parameterized function that approximates a useful relationship.

AI, Machine Learning, Deep Learning & Data Science

These terms overlap, but they answer different questions.

AI

Artificial Intelligence

The broad field of building systems that perform tasks requiring perception, reasoning, language, planning or decision-making.

Examples: search, expert systems, robotics, game playing, ML.
ML

Machine Learning

A way to build behaviour by learning patterns from data instead of writing every decision rule manually.

Examples: price prediction, spam detection, recommendations.
DL

Deep Learning

A branch of ML using multilayer neural networks that learn useful representations from large or complex data.

Examples: vision, speech, language models.
DS

Data Science

The broader practice of turning data into reliable insight using statistics, computing, domain knowledge and communication.

Examples: analysis, experimentation, dashboards, predictive modelling.
Remember: Not every AI system uses ML, not every ML model is deep learning, and data science is not limited to model training.
DETAILED EXPLANATION

Artificial intelligence is the broad goal of building systems that perform tasks requiring human-like reasoning. Machine learning is one way to achieve that goal by learning patterns from examples. Deep learning is a machine-learning family built from many-layer neural networks, while data science combines data collection, analysis, modelling and communication to support decisions.

WORKED INTUITION

A hospital dashboard that summarizes patient trends is data science. A model that predicts readmission risk is machine learning. A system that combines predictions with rules and clinician review is an AI application.

AI / PLACEMENT CONNECTION

Interviewers often test whether you can distinguish a complete AI system from the statistical model inside it.

COMMON MISCONCEPTION

Do not use AI, ML, deep learning and data science as interchangeable words. Their scopes overlap, but they are not identical.

Programmed Rules vs Learned Patterns

The central shift is where the decision logic comes from.

TRADITIONAL PROGRAMMING
Data+Human-written rulesAnswers

Best when rules are stable, explicit and manageable.

if temperature > 38:
    alert = "High"
MACHINE LEARNING — TRAINING
Data+Known answersModel

Best when useful patterns exist but rules are difficult to write completely.

model.fit(examples, labels)
MACHINE LEARNING — INFERENCE
New data+Trained modelPrediction

The trained model applies what it learned to unseen input.

prediction = model.predict(new_data)
DETAILED EXPLANATION

A rule-based program follows conditions written directly by a developer. A learned system receives examples containing inputs and outcomes, adjusts parameters to reduce error, and then applies the discovered relationship to new inputs. Learning is useful when rules are too numerous, uncertain or constantly changing.

WORKED INTUITION

A fixed tax calculation is clearer as rules. Spam detection is better suited to learning because useful signals include thousands of changing word, sender and behaviour patterns.

AI / PLACEMENT CONNECTION

Problem framing includes deciding whether machine learning is necessary at all. A simpler deterministic solution is often safer and easier to maintain.

COMMON MISCONCEPTION

Learning from historical decisions can reproduce their mistakes or bias. More data does not automatically produce better rules.

The Vocabulary of Learning from Data

Use these words precisely; interviewers notice when a candidate does.

DATASETA collection of examples

A table, image folder, document set or stream used for learning or evaluation.

SAMPLEOne observation

One row, image, message or event in the dataset.

FEATUREAn input signal

A measurable property supplied to the model, often written as x.

LABEL / TARGETThe desired answer

The value to predict, often written as y.

MODELA learned mapping

A mathematical function that maps input features to an output.

PARAMETERLearned internal value

A weight or bias updated by the training process.

HYPERPARAMETERA chosen setting

A learning rate, depth or neighbour count selected outside training.

LOSSTraining error signal

A number the learning process tries to minimize.

METRICEvaluation measure

A business-relevant measure such as accuracy, F1 or mean absolute error.

INFERENCEUsing a trained model

Generating a prediction for new, previously unseen input.

DETAILED EXPLANATION

A dataset contains samples. Each sample is described by features and, in supervised learning, a target or label. A model contains learned parameters. Training changes those parameters; inference uses the fixed parameters to create a prediction. Hyperparameters control the learning process or model structure and are selected using validation evidence.

WORKED INTUITION

For house-price prediction, one house is a sample, area and location are features, sale price is the target, regression coefficients are parameters, and regularization strength is a hyperparameter.

AI / PLACEMENT CONNECTION

Clear vocabulary makes data shapes, training code and interview explanations much easier to reason about.

COMMON MISCONCEPTION

A feature available after the real prediction time is leakage, even if it appears in the historical table.

Four Learning Paradigms

The available feedback determines the learning setup.

01

Supervised Learning

Learn from inputs paired with known labels.

Regression predicts numbers.
Classification predicts categories.
House price • disease class • spam
02

Unsupervised Learning

Discover useful structure when labels are absent.

Clustering groups similar items.
Reduction compresses representation.
Customer segments • anomaly discovery
03

Self / Semi-Supervised

Exploit abundant unlabelled data with generated or limited supervision.

Self-supervised creates a learning signal from data.
Semi-supervised mixes labelled and unlabelled samples.
Language pretraining • image representation
04

Reinforcement Learning

An agent learns actions through rewards and consequences.

State → Action → Reward
The goal is long-term cumulative reward.
Games • control • sequential decisions
DETAILED EXPLANATION

Supervised learning uses labelled examples to predict a target. Unsupervised learning searches for structure without a supplied answer. Semi-supervised learning combines a small labelled set with a larger unlabelled set. Reinforcement learning improves a policy through actions, rewards and delayed consequences.

WORKED INTUITION

Price prediction is supervised regression; customer grouping is unsupervised clustering; image learning with 500 labels and 50,000 unlabelled images is semi-supervised; game-playing from rewards is reinforcement learning.

AI / PLACEMENT CONNECTION

The correct paradigm follows from the feedback available to the system, not from the algorithm name alone.

COMMON MISCONCEPTION

Clustering does not discover objectively correct groups. It produces structure according to the features, distance measure and assumptions chosen.

Frame the Problem Before Choosing the Algorithm

A strong ML solution begins with a measurable decision—not with a favourite model.

  1. 1
    DecisionWhat decision or action will the prediction support?
  2. 2
    InputWhat information is available at prediction time?
  3. 3
    TargetWhat exactly should the model predict?
  4. 4
    MetricHow will usefulness and failure be measured?
  5. 5
    ConstraintsWhat limits exist for latency, cost, privacy, fairness and explanation?
  6. 6
    BaselineWhat simple rule or model must the solution beat?
EXAMPLE • STUDENT SUPPORT

Weak framing: “Use AI to help students.”

Useful framing: “Each week, predict which enrolled students are at high risk of missing the next assessment, using only activity available before that week, so mentors can intervene. Optimize recall while controlling false alerts.”

DETAILED EXPLANATION

Good machine learning begins with a decision that must improve. Define the prediction unit, target, prediction time, allowed inputs, success metric, acceptable latency and cost of each error. Only then should you choose an algorithm. This prevents technically impressive models that solve the wrong business problem.

WORKED INTUITION

Instead of saying ‘predict student success,’ define: ‘At week four, estimate whether each active student will need support, using only attendance and assessments available by that date.’

AI / PLACEMENT CONNECTION

Placement interviews reward candidates who translate a vague request into a measurable and leakage-safe formulation.

COMMON MISCONCEPTION

Do not optimize a convenient metric that ignores real consequences. A false negative and false positive may have very different costs.

The End-to-End Machine Learning Lifecycle

A model is only one component of a reliable AI system.

01Define

Decision, target, success metric and constraints.

02Collect

Relevant, lawful and representative data.

03Prepare

Clean, explore and transform without leakage.

04Split

Separate train, validation and test evidence.

05Train

Learn parameters from training data.

06Evaluate

Compare baselines, metrics and failure slices.

07Deploy

Serve predictions in a usable system.

08Monitor

Track quality, drift, safety and retraining needs.

DETAILED EXPLANATION

The ML lifecycle is iterative: frame the problem, collect and understand data, split evaluation evidence, clean and transform, build a baseline, train candidates, validate, test once, deploy and monitor. Feedback from production may require new data or a reformulated objective rather than only model tuning.

WORKED INTUITION

A churn model may perform well initially, then weaken after a pricing change. Monitoring detects the shift, analysis identifies the changed behaviour, and retraining or reframing follows.

AI / PLACEMENT CONNECTION

Real ML work includes data contracts, experiment records, deployment checks and monitoring—not only calling fit and predict.

COMMON MISCONCEPTION

Treating deployment as the final step hides drift, broken features and changing user behaviour.

Training, Validation and Test Data

Each split has a different job. Reusing the test set for decisions makes the final score untrustworthy.

TRAIN • 70%Learn parameters
VALIDATION • 15%Choose settings
TEST • 15%Final unbiased check
Training set

The model learns weights or patterns from these examples.

Validation set

You compare models and tune hyperparameters without touching the test set.

Test set

You use it after decisions are finalized to estimate performance on unseen data.

DETAILED EXPLANATION

Training data estimates parameters. Validation data supports model, feature, threshold and hyperparameter decisions. Test data provides one final unbiased estimate after those choices are complete. The split must respect time, people, devices or groups whenever related samples could otherwise appear in multiple partitions.

WORKED INTUITION

For repeated medical visits, split by patient rather than by row. Otherwise the same patient’s patterns can appear in both training and test data.

AI / PLACEMENT CONNECTION

A valid evaluation design is more important than a sophisticated algorithm because every later conclusion depends on it.

COMMON MISCONCEPTION

Repeatedly checking test performance turns the test set into another validation set and makes the reported score optimistic.

Generalization: The Real Goal

A useful model succeeds on unseen cases, not only on examples it memorized.

UNDERFITTING

Too Simple

High training error and high validation error. The model misses important structure.

GOOD GENERALIZATION

Useful Pattern

Low enough training error and similar validation performance on unseen examples.

OVERFITTING

Memorizes Noise

Very low training error but worse validation error. The model learns accidental details.

Data leakage warning: If information from the validation/test future reaches training or preprocessing, the score can look excellent while real-world performance fails.
DETAILED EXPLANATION

Generalization is the ability to perform well on relevant unseen cases. Underfitting occurs when a model cannot capture important structure. Overfitting occurs when it learns training-specific noise. The goal is neither minimum training error nor maximum complexity, but reliable performance under realistic future conditions.

WORKED INTUITION

A very deep tree may memorize every training customer yet fail on new customers. Pruning, regularization and better validation can expose and reduce the problem.

AI / PLACEMENT CONNECTION

Learning curves, cross-validation and subgroup analysis help separate limited data, excessive complexity and distribution shift.

COMMON MISCONCEPTION

A small train–test gap is not sufficient if both scores are poor or if the test distribution is unrealistic.

Accuracy Alone Is Not Enough

⚖️Fairness

Check whether errors harm groups differently.

🔒Privacy

Collect only necessary data and protect it.

🔍Transparency

Document data, assumptions, limits and intended use.

🛡️Safety

Design fallbacks, human review and monitoring for failures.

👤Accountability

People remain responsible for system decisions and impact.

INTERACTIVE LEARNING • CODEBHAVYA PREMIUM VISUALIZER

🎬 How a Machine Learns — Visual Flow

Move from raw examples to a tested prediction. Every step shows what changes and why.

LIVE
STEP 1 OF 7

Collect representative examples

Begin with examples that represent the conditions where the model will be used.

Step 1 of 7
PROGRAM TRACING • LINE BY LINE

Trace Your First Learning Algorithm

Follow simple linear regression from examples to a prediction. Observe every variable and calculation.

Simple Linear Regression from Scratch

The model learns a line prediction = weight × input + bias.

hours = [1, 2, 3, 4, 5]
scores = [20, 35, 50, 65, 80]
mean_x = sum(hours) / len(hours)
mean_y = sum(scores) / len(scores)
numerator = sum((x - mean_x) * (y - mean_y)
                for x, y in zip(hours, scores))
denominator = sum((x - mean_x) ** 2 for x in hours)
weight = numerator / denominator
bias = mean_y - weight * mean_x
new_hours = 6
prediction = weight * new_hours + bias
print(round(prediction, 2))
LEARNED MODEL
score = 15 × hours + 5
  • Weight = 15: estimated score increase per extra study hour.
  • Bias = 5: the line’s predicted value when hours is zero.
  • For 6 hours: 15 × 6 + 5 = 95.
  • Limitation: extrapolation beyond observed data may be unreliable.

Build the Foundation with Code

Read the task, attempt it independently, use the hint only when needed, then compare with the model program.

0 / 5Solved independently0 / 500Best score

Test Understanding, Not Memorization

Select one answer for every question. Results will show your choice, the correct answer and an explanation.

Not checked yet

How Interviewers Test These Foundations

Strong candidates connect terminology to evaluation and business consequences.

ROUND 01

Definition with Contrast

“Explain AI vs ML vs deep learning with one example each.”

ROUND 02

Problem Framing

“Design the target, features and metric for churn prediction.”

ROUND 03

Failure Diagnosis

“Training accuracy is high but test accuracy is low. What happened?”

ROUND 04

Production Thinking

“Why can a model’s quality decline after deployment?”

CodeBhavya interview pattern:Define → Contrast → Give an example → State a trade-off → Connect to production.

🎤 AI & ML Foundations — Interview Questions

Answer aloud before opening each explanation.

The Foundation in One View

1Frame

Start with a decision and measurable success.

2Learn

Use representative data to fit parameters.

3Generalize

Evaluate honestly on unseen evidence.

4Operate

Deploy responsibly and monitor continuously.

Machine learning is not “data in, magic out.” It is a disciplined process of defining, learning, testing and improving a measurable system.

Habits That Prevent Beginner Mistakes

01

Always write the target and prediction-time features before selecting a model.

02

Build a simple baseline first; complexity must earn its place.

03

Keep the test set untouched until model and hyperparameter choices are complete.

04

Inspect examples and labels manually before trusting summary statistics.

05

Choose metrics from the cost of errors, not from habit.

06

Record assumptions, dataset limits and known failure cases as part of the model.

Strengthen Your AI & ML Thinking

Attempt these without opening notes. Explain every answer with a reason.

  1. 01

    For an email spam detector, identify one sample, three possible features and the label.

  2. 02

    Decide whether house-price prediction is regression or classification, and explain why.

  3. 03

    Give one problem better solved with explicit rules than with machine learning.

  4. 04

    Explain why a model scoring 100% on its training data may still be useless.

  5. 05

    Design a train/validation/test split for time-ordered sales data without future leakage.

  6. 06

    For fraud detection, explain why accuracy alone can be misleading.

  7. 07

    Give one parameter and one hyperparameter for a model you know.

  8. 08

    Classify customer segmentation by learning paradigm and justify your choice.

  9. 09

    Name two reasons production data may differ from training data.

  10. 10

    Write a useful baseline for predicting whether a student submits an assignment.

  11. 11

    Turn “build an AI hiring tool” into a measurable problem statement with safeguards.

  12. 12

    Draw the complete ML lifecycle and mark where human review should occur.