Lab 2 of 8about 45 minutes
Tune a penguin model on folds
It uses what you learned in Logistic regression, Overfitting and regularization and Cross-validation and tuning.
Start here
Run itThe penguins from Python for AI. The piles below are dealt with the videos' random_state, so the numbers are theirs.
1A penguin's chance
Your turnFrom Logistic regression
The Adelies and the Chinstraps, by the bill's length, as ml-logistic-regression dealt them. Fill in two lines. predict_proba gives a column of chances for each kind, in the order of model.classes_, so keep the Chinstrap's. Then the bill where that chance is one half: the line's score, w times the bill plus b, is zero there.
Hint
[:, 1] keeps the second column. For the boundary, solve w * bill + b = 0 for the bill.
One way to do it
two = penguins[penguins["species"] != "Gentoo"].dropna(subset=["bill_length_mm"])
X, y = two[["bill_length_mm"]], two["species"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0)
model = LogisticRegression()
model.fit(X_train, y_train)
new = pd.DataFrame({"bill_length_mm": [40, 43, 45, 48]})
chance = model.predict_proba(new)[:, 1]
w, b = model.coef_[0, 0], model.intercept_[0]
boundary = -b / w
print(model.classes_, chance.round(3), round(boundary, 2), model.score(X_test, y_test))2Twenty penguins, a line and a curve
Your turnFrom Overfitting and regularization
Now ml-overfitting's deal: the mass in grams from the flipper in centimetres measured from 20, 86 sealed as the test set, 20 to learn from and the other 236 to validate. Write errors: a fitted model's RMSE on the 20 it learned from, then on the validation set.
Hint
Two RMSEs, each with the real masses first: one on X_train and y_train, one on X_val and y_val.
One way to do it
known = penguins.dropna(subset=["flipper_length_mm", "body_mass_g"])
X, y = known[["flipper_length_mm"]] / 10 - 20, known["body_mass_g"]
X_rest, X_test, y_rest, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(X_rest, y_rest, train_size=20, random_state=0)
def errors(model):
return (root_mean_squared_error(y_train, model.predict(X_train)),
root_mean_squared_error(y_val, model.predict(X_val)))
for degree in (1, 9):
model = make_pipeline(PolynomialFeatures(degree), StandardScaler(), LinearRegression())
model.fit(X_train, y_train)
print(degree, np.round(errors(model)))3A penalty
Your turnFrom Overfitting and regularization
Ridge is a linear regression with a penalty on big weights, and alpha is its strength. Make the curve of degree 9 with Ridge in place of the plain regression, at each of the video's four strengths, and keep each one's validation error in by_strength.
Hint
Step 2's pipeline, with Ridge(alpha=alpha) as its last part.
One way to do it
by_strength = {}
for alpha in [0.0001, 0.01, 1, 1000]:
curve = make_pipeline(PolynomialFeatures(9), StandardScaler(), Ridge(alpha=alpha))
curve.fit(X_train, y_train)
by_strength[alpha] = round(errors(curve)[1])
print(by_strength)4No scale
Run itFrom Overfitting and regularization
Run the cell. It makes step 3's curves with the flipper in millimetres and no StandardScaler. The ninth power of a 230 mm flipper is about 1.8 followed by 21 zeros, beside a column of 1s. With numbers that far apart, the answer hangs on rounding: on another computer the four misses come out different, and they no longer fall and then rise with the strength, as in step 3.
5The strength, on five folds
Your turnFrom Cross-validation and tuning and Overfitting and regularization
With only 20 penguins, one validation set is a lot to give up. Choose the strength on five folds of the 20 instead, then open the test set once. GridSearchCV keeps the highest score, so a miss is scored as a negative number: -347 means 347 g. A pipeline's step is named by its class in small letters, so Ridge's strength is ridge__alpha.
Hint
The folds are cut from the 20 the curve learns from. The test set is scored once, after the search.
One way to do it
grid = {"ridge__alpha": [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]}
curve = make_pipeline(PolynomialFeatures(9), StandardScaler(), Ridge())
search = GridSearchCV(curve, grid, cv=5, scoring="neg_root_mean_squared_error")
search.fit(X_train, y_train)
test_miss = -search.score(X_test, y_test)
print(search.best_params_, round(-search.best_score_), round(test_miss))6Choosing on the test set
Run itFrom Cross-validation and tuning
Why not skip the folds, and pick the strength that does best on the test set? Run the cell. Here the test set picks the same strength, at 429 g.
The same 429 g, and it means less. It is the best of eight looks, so it was picked for being low, and no penguin is left that took no part in the choice. The folds' 429 g was a first look.
7The C of a logistic regression
On your ownFrom Cross-validation and tuning and Logistic regression
On your own now. In logistic regression the penalty's setting is C, and a smaller C means a stronger penalty. Deal step 1's Adelies and Chinstraps again, choose C from 0.01, 0.1, 1, 10 and 100 on five folds of the training set, and keep the search in c_search and its score on the test set, opened once, in c_test.
Hint
Step 5 again, with LogisticRegression() in place of the curve and {"C": [...]} as the grid. Its score is the share right, so no minus sign. The folds tie 0.01 and 0.1 to the third decimal, and a tie is read as a tie.
One way to do it
X, y = two[["bill_length_mm"]], two["species"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0)
c_search = GridSearchCV(LogisticRegression(), {"C": [0.01, 0.1, 1, 10, 100]}, cv=5)
c_search.fit(X_train, y_train)
c_test = c_search.score(X_test, y_test)
print(c_search.best_params_, round(c_search.best_score_, 3), round(c_test, 3))Run on Pyodide 314, Python 3.14, pandas 3.0 and scikit-learn 1.8. Checked on .
