AI from scratch · Toolkit 2 · Stage 4: the engineer's toolkit

pandas and scikit-learn

Stage 3 used pandas and scikit-learn a line at a time. This lesson is the working kit: how a real table gets loaded, looked at, cleaned, grouped, joined and turned into features, and how scikit-learn's few rules let you swap any model into the same pipeline and tune it honestly. The table is real: every NYC subway elevator and escalator outage this site's archive saw in five weeks of fall 2026, 667 of them.

Data: MTA elevator and escalator outage feed, archived by ihor.sh, September 9 to October 15, 2026 (times in New York time). last_seen is the last time the feed listed the outage; for finished ones, that's when it ended, give or take the archive's polling interval.

1. Load it, then look before doing anything

pd.read_csv reads the file; parse_dates turns the time columns into real dates instead of text. Then four looks that catch most surprises: the first rows, the types and missing values, the numbers summarized, and how often each category appears.

The oldest outage started in September 2024, two years before the archive did. What's the most likely story?

Look at those rows: "Capital Replacement", estimated back in service at the end of October 2026. Real tables have stories like this, and a model trained on "how long outages last" needs to decide whether they belong. Here they're unfinished, so they drop out anyway.

Before any model: shape, types, missing values, ranges and category counts; the surprises live there.

2. Select, filter and add columns

You wantpandas
Some columnsdf[["station", "reason"]]
Rows where something is truedf[df["kind"] == "EL"], combined with & and | (each condition in brackets)
Rows and columns by labeldf.loc[df["ada"] == 1, "station"]
By positiondf.iloc[:5, :3]
A new columndf["hours"] = ... (a whole column at once, like NumPy)
Text and date partsdf["lines"].str.count("/"), df["start"].dt.hour

Half the outages are over in under 2 hours, a quarter last more than 4, and two planned jobs took a month. The MTA's estimate is longer than the real outage 98% of the time: it plans for the worst.

Which line keeps elevator outages at ADA-accessible stations that lasted over 4 hours?

Each comparison makes a column of True/False; & combines them row by row. Brackets are needed because & is evaluated before ==.

Columns are whole arrays: filter with a True/False column, combine conditions with & and |, and build new columns in one line.

3. Group, then combine

groupby is three steps under one name: split the rows by a key, apply a summary to each group, combine the answers into a table. Step through it on six outages:

1. the rows

2. split by reason

3. apply, combine

Why pass validate="many_to_one" to merge?

A merge pairs every left row with every matching right row. If the right table had a station twice, each of its outages would appear twice, and every count and mean after that would be wrong with no warning.

groupby is split, apply, combine; merge pairs every row with every match, so say what shape of match you expect.

Where it breaks: three silent pandas bugs

4. scikit-learn's one contract

Every piece of scikit-learn follows the same few rules, which is why any model drops into any pipeline:

MethodWhat it doesWho has it
fit(X, y)Learns from training data and stores what it learned (attributes ending in _, like coef_ or mean_)everything
transform(X)Applies what was learned to new rowsscalers, encoders, imputers
predict(X), predict_proba(X)Answers for new rowsmodels
get_params(), set_params()The settings you chose (hyperparameters), separate from what it learnedeverything

A pipeline chains them, and is itself one estimator: fit fits every step on the training rows in order, predict runs new rows through all of them. The question here: will an outage last more than 4 hours (27% of them do)? An app could warn riders to plan another route.

Logistic regression edges out the trees here (about 0.89 against 0.88, and steadier from fold to fold): with 600 rows and a few strong categories, the simpler model has less to overfit. That's chapter 13's table in practice: start simple, and let the validation numbers decide.

Every scikit-learn piece learns in fit and applies in transform or predict, so a pipeline of them is one model you can swap, score and tune.

Why fit and transform are separate methods
  1. A scaler needs two numbers per column, a mean and a spread, and they have to come from somewhere.
  2. fit is where it learns them, from the rows it's given, and stores them (mean_, scale_).
  3. transform only applies the stored numbers. It never looks at the new rows' own mean.
  4. So "learn from training rows, apply to everything" isn't a rule you have to remember: it's built into which method does what. Cross-validation calls fit on each fold's training rows and transform on its test rows, and no test row can shape the scaling.
  5. fit_transform is just both on the same rows: right for training data, a leak if you call it on test data.

5. Tuning: grid search with the right split

Hyperparameters are the settings you choose before fitting: the penalty strength C, the depth of trees, the learning rate. GridSearchCV tries each combination with cross-validation and keeps the best. In a pipeline, a step's setting is named step__setting (two underscores).

Search on a log scale (0.01, 0.1, 1, 10): the effect of a penalty depends on its order of magnitude, not on its exact value. When the grid gets big, RandomizedSearchCV tries a fixed number of random combinations instead, and usually finds as good a setting in far fewer tries.

Grid search reports a best CV AUC of about 0.9. What is that number?

Choosing the best of several on the same folds rewards a little luck. Keep the last week or two of outages untouched, and score the chosen model on them once.

Hyperparameters are chosen by cross-validation over a log-scale grid, and the winner's score is optimistic until it's checked on data nobody chose with.

6. What to carry forward

All lessons: AI from scratch. Kaggle Learn's free Pandas and Intermediate ML courses are good companions.

Last updated