Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 1: AI and Machine Learning Fundamentals

Week 01 / Lesson 2

Preparing data and testing a prediction fairly

Separate prediction inputs from answers and choose a split that represents the intended use.

Section 2.1 1 of 8

Overview

Focus

Separate prediction inputs from answers and choose a split that represents the intended use.

Your route through the lesson

  • 2.2 Artificial intelligence, machine learning, and deep learning
  • 2.3 From raw records to usable features and targets
  • 2.4 Training, validation, and test partitions
  • 2.5 Leakage, preprocessing, and a first classifier
  • 2.6 Put it into practice
  • 2.7 Guided comparison
  • 2.8 Purchase-time fraud features

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 8

Artificial intelligence, machine learning, and deep learning

Focus

Distinguish a fixed rule, a learned mapping, and a layered neural network.

Artificial intelligence describes systems designed to perform tasks associated with intelligent behavior, such as recognizing a message or planning a route. Machine learning is one way to build those systems: fit a mapping using examples or other experience. Deep learning is machine learning built from neural networks with multiple learned layers. These are nested categories, not three competing products.

Consider three email systems. A rule written by a programmer blocks every message with more than ten links. Its rule does not change from examples. A fitted classifier changes its weights after comparing historical predictions with supplied spam labels. A deep neural classifier learns several layers of numerical transformations from such examples. Both fitted classifiers are machine learning; the layered one is also deep learning. Supervised learning describes their feedback, while deep learning describes a model family. A model can therefore be both supervised and deep.

When classifying a system, ask two separate questions: what changes through experience, and what supplies feedback? Calling an application an assistant does not answer either question.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A developer writes “block messages with more than ten links” and never fits it from examples. What makes this a rule-based system?
2. An email classifier fits several neural layers to labeled messages. Which descriptions can both apply?
3. A price model changes coefficients using historical sale prices. What establishes machine learning?

Section 2.3 3 of 8

From raw records to usable features and targets

Focus

Read records and separate information available for prediction from the target answer.

A record is one item represented by named fields. A table arranges records in rows and fields in columns. For a house, a record might be area=1500, bedrooms=3, and sold_price=300000. Area and bedrooms are available before selling; sold_price is the historical answer used during training. At prediction time the new house has features but its sale price is unknown.

Python stores a small ordered collection in a list, written with square brackets. A dictionary uses braces and maps field names to values. NumPy, a numerical library, stores a rectangular collection of numbers in an array. A typical feature array called X has one row per example and one column per feature; y stores one target per row. The names X and y are conventions, not special syntax.

Missing data needs an explicit policy. Suppose training areas are 1000, 2000, and missing. A simple policy fills the missing area with the observed training mean, 1500. Save that value and use it for future records. Recomputing a different mean from each new customer changes the mapping. Customer identifiers can be retained to split records without being used as predictive numbers.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Three house records each contain area and bedrooms. What shape has their numerical feature array?
2. A historical house record contains area, bedrooms, and final sale price. Which field is the target for predicting sale price?
3. Observed training areas are 1000 and 2000; another area is missing. Under a training-mean fill policy, what fills it?

Section 2.4 4 of 8

Training, validation, and test partitions

Focus

Assign fitting, model selection, and final evaluation to separate data partitions.

Training data fits learned parameters. Validation data compares choices such as learning rate or model size. Test data estimates behavior after those choices are frozen. If you repeatedly choose the best model using the test score, that score has become selection feedback rather than an independent final check.

The split must resemble deployment. If the task is predicting records from unseen customers, put every record from one customer on only one side. For customers A, B, and C with two records each, training on A, validating on B, and testing on C prevents customer overlap. A random row split could place A on both sides and measure familiarity with A instead of performance on new customers. Predicting future transactions instead needs a chronological split: fit on earlier observations and evaluate later ones.

A random row split is useful for independently generated rows when that matches the intended use. Preserve a fixed random seed to reproduce a comparison, and report how you split. A seed is an initial value for a repeatable random sequence; it does not make an inappropriate split valid.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A team selects a learning rate using validation records. What should its untouched test set be used for?
2. Two records from each of three customers must be evaluated on unseen customers. Which split fits the goal?
3. A transaction model will predict next month from earlier months. Which evaluation follows that use?

Section 2.5 5 of 8

Leakage, preprocessing, and a first classifier

Focus

Fit preparation and a classifier on training records and interpret a simple baseline.

A preprocessing step converts raw inputs into a form suitable for a model. Standardization subtracts a feature's training mean and divides by its training standard deviation. With training values 10 and 20, the mean is 15; a future value is transformed using that saved mean, not a mean recomputed from test data. This avoids leaking evaluation information into preparation.

Scikit-learn calls a fitted algorithm an estimator. Its fit(X,y) method learns from training examples; predict(X_new) returns predictions. A pipeline connects preparation and the estimator so fitting operates on the proper training inputs. Its StandardScaler object learns preparation statistics and LogisticRegression learns a weighted binary classifier. The class name does not make this a numerical-price regression task: logistic regression predicts a category using estimated class probabilities.

Compare with a baseline before admiring a score. If 18 of 20 training messages are legitimate, an always-legitimate baseline is simple. On a test set containing 16 legitimate and 4 spam messages, it achieves 80% accuracy while missing every spam message. A confusion matrix counts true categories against predictions, exposing those misses.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A scaler is used before a classifier. Where should its mean and standard deviation be fitted?
2. An always-legitimate filter sees 16 legitimate and 4 spam test messages. What is its accuracy?
3. A fitted scikit-learn classifier should label new feature rows. Which operation does that?

Section 2.6 6 of 8

Put it into practice

Focus

Prepare Python, run a leakage-safe split, and inspect a small classifier result.

Create an exercise folder in PowerShell. Install a supported Python interpreter if python --version is unavailable. A virtual environment keeps exercise packages separate from other projects. The -m option runs a module using the selected interpreter; pip installs packages for that interpreter.

python -m venv .venv
./.venv/Scripts/python.exe -m pip install numpy scikit-learn
./.venv/Scripts/python.exe -c "import numpy; print(numpy.array([2, 4]).mean())"

The final command imports NumPy, makes an array, and calls its mean method. It should print 3.0. A message saying ModuleNotFoundError means the interpreter cannot find that package; rerun installation with the same .venv interpreter rather than changing unrelated application files.

Download week01.py into the exercise folder. Run ./.venv/Scripts/python.exe week01.py --lesson 2. The script constructs six customer records and asserts that training, validation, and test customer sets do not intersect. Python's assert stops execution if its condition is false; a traceback identifies the failed line. It then fits a small generated-data classifier with a train-only pipeline and prints its confusion matrix and majority baseline. Inspect the actual output; a classifier is not required to achieve a promised accuracy.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. PowerShell created a .venv environment. Which command installs NumPy into that environment?
2. A split has customer A in both training and test, but row numbers differ. Which assertion should fail?
3. A Python assert rejects overlapping customer sets. What does the traceback mean?

Section 2.7 7 of 8

Guided comparison

Focus

Explain the split and prediction checks rather than treating script completion as model quality.

The six customer records form three pairs: A has two records, B has two, and C has two. Assigning A to training, B to validation, and C to test makes each pair stay together. The training/customer intersection with the test/customer set is empty. That is an exact property to assert. Merely having different row positions does not prove it.

For a numerical transformation, training values 10 and 20 give mean 15 and population standard deviation 5. Transforming a future value 30 gives (30−15)/5=3. Fitting on 10,20,30 instead would give mean 20, allowing the future record to influence preparation. A pipeline prevents that when only training rows are passed to fit.

For a classifier result, read the confusion matrix according to its explicit class order. With labels [0,1], rows are true classes and columns predicted classes. Matrix [[8,2],[1,9]] means eight true negatives, two false positives, one false negative, and nine true positives. Seventeen of twenty are correct, so accuracy is 85%. The assertions about split and shape can pass even when predictive accuracy is poor; they check engineering conditions, not universal quality.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Training values 10 and 20 have mean 15 and standard deviation 5. How is a future value 30 standardized?
2. With true-class rows and predicted-class columns ordered [0,1], what does matrix [[8,2],[1,9]] contain?
3. A script confirms disjoint customer groups and correct array shapes. What has been established?

Section 2.8 8 of 8

Purchase-time fraud features

Focus

Exclude information that was unavailable when a fraud decision had to be made.

Suppose a payment system decides whether to flag a transaction at purchase time. Its historical table includes amount, card age, purchase timestamp, and whether a refund was later issued. A refund may correlate strongly with fraud, making an evaluation look excellent. But the refund event happens after the decision. Supplying it during training creates a shortcut the deployed predictor cannot reproduce.

Make prediction time explicit for every feature. Amount and the card's age are available when the purchase arrives. The final fraud determination is a target; the later refund is excluded from inputs. An older confirmed-fraud count might be a valid feature only if computed from events already known before the current purchase. Computing it from the customer's complete future history would leak again.

There are two distinct checks: are evaluation customers or dates properly separated, and was every input knowable at prediction time? A disjoint group split does not repair a future-only feature. A valid feature list does not repair customer overlap. Repair each failure independently and compare the revised model using an untouched test set.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A fraud decision occurs at purchase. Which recorded field is unavailable then?
2. A model uses next-week refunds but has disjoint train and test customers. Is leakage fixed?
3. A fraud count is computed for a purchase at noon. Which events may contribute to a prediction-time feature?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: How a model learns from error →