Please enable JavaScript to use CodeHS

AI Engineer

Build a model from data

Industry ML work is mostly data work. This tutorial walks through a complete tabular workflow with pandas and scikit-learn.

AI ~15 min Programmer
Vocabulary

Key terms for this tutorial

Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.

accuracy
The fraction of predictions that are correct. It can be misleading when classes are imbalanced.
inference
Using a trained model to make predictions on new inputs.
model
A function with learnable parameters that maps inputs to outputs.
ColumnTransformer
A scikit-learn tool that applies different preprocessing to different columns of a DataFrame.
cross-validation
Training and evaluating on multiple splits of the data to get a more reliable performance estimate.
DataFrame
A pandas table with rows and named columns, similar to a spreadsheet or SQL table.
OneHotEncoder
A scikit-learn transformer that turns a categorical column into many binary columns.
pipeline
A scikit-learn object that chains preprocessing steps and a model so the same transformations are applied during training and inference.

Pipeline

A repeatable preprocessing and training pipeline

Real datasets are messy. A pipeline chains preprocessing and a model so the same transformations are applied during training and inference. This avoids the common bug of fitting preprocessors on the test set.

ml_pipeline.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score

# Synthetic customer churn data
df = pd.DataFrame({
    'tenure': [12, 24, 5, 48, 6],
    'contract': ['month', 'year', 'month', 'two_year', 'month'],
    'churn': [0, 0, 1, 0, 1]
})
X = df.drop('churn', axis=1)
y = df['churn']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

preprocess = ColumnTransformer([
    ('num', StandardScaler(), ['tenure']),
    ('cat', OneHotEncoder(), ['contract'])
])
clf = Pipeline([
    ('preprocess', preprocess),
    ('model', RandomForestClassifier(n_estimators=10, random_state=42))
])
clf.fit(X_train, y_train)
preds = clf.predict(X_test)
print('accuracy:', accuracy_score(y_test, preds))
Output
accuracy: 1.0

Line-by-line: ml_pipeline.py

Read this slowly. Each line does one small, concrete thing.

  1. import pandas as pd — Import the pandas library so we can use its built-in tools.
  2. from sklearn.model_selection import train_test_split — Import tools from the sklearn.model_selection package.
  3. from sklearn.compose import ColumnTransformer — Import tools from the sklearn.compose package.
  4. df = pd.DataFrame({ — Create a pandas DataFrame, a table that makes it easy to manipulate and inspect tabular data.
  5. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) — Split the data into training and testing sets so we can measure performance honestly.
  6. preprocess = ColumnTransformer([ — Build a ColumnTransformer that applies different preprocessing to numeric and categorical columns.
  7. ('num', StandardScaler(), ['tenure']), — Scale numeric features so columns with large numbers do not dominate those with small numbers.
  8. ('cat', OneHotEncoder(), ['contract']) — Turn categorical text values into a set of 0/1 columns that the model can multiply.
  9. clf = Pipeline([ — Wrap preprocessing and the model in a single Pipeline so the same steps run at training and inference time.
  10. ('model', RandomForestClassifier(n_estimators=10, random_state=42)) — Create a random-forest classifier, an ensemble of decision trees that votes on the answer.
  11. clf.fit(X_train, y_train) — Train the model on the training data; this is where the parameters are learned.
  12. preds = clf.predict(X_test) — Use the trained model to make predictions on new data.
  13. print('accuracy:', accuracy_score(y_test, preds)) — Compute accuracy: the fraction of test examples the model labeled correctly.

Pop-in: Why a pipeline matters

A pipeline guarantees the exact same preprocessing happens during training and testing. Without it, you might accidentally scale or encode the test set using its own statistics, which leaks information.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: End-to-End ML Workflow'. Explain the section 'A repeatable preprocessing and training pipeline' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Cross-validation

Cross-validation and metrics

A single train/test split can be lucky or unlucky. K-fold cross-validation trains K models on different folds and reports the average score. Accuracy is easy but misleading with imbalanced classes; precision, recall, and F1 are usually more useful.

cv.py
from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, X, y, cv=3, scoring='accuracy')
print('CV scores:', scores)
print('mean:', scores.mean())
Output
CV scores: [1. 1. 1.]
mean: 1.0

Line-by-line: cv.py

Read this slowly. Each line does one small, concrete thing.

  1. from sklearn.model_selection import cross_val_score — Import tools from the sklearn.model_selection package.
  2. scores = cross_val_score(clf, X, y, cv=3, scoring='accuracy') — Run cross-validation to get a more stable estimate of how the model performs.
  3. print('CV scores:', scores) — Print a result so we can see what the model learned.
  4. print('mean:', scores.mean()) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: End-to-End ML Workflow'. Explain the section 'Cross-validation and metrics' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Check yourself

Check yourself

?

Why use a pipeline?

What bug does a scikit-learn pipeline prevent?

It prevents data leakage by fitting preprocessing only on the training fold and applying the same transformations at inference time.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: End-to-End ML Workflow'. The practice question 'Why use a pipeline?' asks: What bug does a scikit-learn pipeline prevent? The answer is: It prevents data leakage by fitting preprocessing only on the training fold and applying the same transformations at inference time.. Explain the concept behind this in simple terms.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: End-to-End ML Workflow'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Quick quiz

Three questions

1. What is data leakage?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: End-to-End ML Workflow'. The quiz asks: What is data leakage? The correct answer is: Using test-set information during training or preprocessing. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. Why cross-validate?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: End-to-End ML Workflow'. The quiz asks: Why cross-validate? The correct answer is: To get a more robust estimate of performance. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. When is accuracy misleading?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: End-to-End ML Workflow'. The quiz asks: When is accuracy misleading? The correct answer is: When classes are imbalanced or false positives/negatives have different costs. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Next: scale up to PyTorch datasets, dataloaders, and production training loops.

Part of the CodeHS tutorial library.