Lab 2 of 4about 40 minutes
Scan the penguins before a model
It uses what you learned in Expectation and variance, Samples, averages and the normal distribution and Correlation.
Start here
Run itThe penguins from Python for AI, with mass in kilos as the videos had it. measures holds the four measured columns as one NumPy array, a penguin a row.
1The table
Run itRun the cell. It prints the shape, then the first three penguins.
Four columns a model could learn from, each in its own unit: millimetres from about 13 to 230, kilos from about 3 to 6.
2Each column's centre and spread
Your turnBy hand first. The average is each column added up, divided by the count. The variance is the average squared distance from the average, and the standard deviation is its square root. axis=0 works down each column. Write the variance; the last line prints NumPy's own.
pandas has its own: df.body_mass_kg.std() gives 0.802, not 0.80. It divides by 341, one less than the count. Both are in use; the scaler in the next step divides by 342, as NumPy does.
Hint
Take averages away from measures, square it, add down each column, and divide by n.
One way to do it
n = len(measures)
averages = measures.sum(axis=0) / n
spreads = np.sqrt(((measures - averages) ** 2).sum(axis=0) / n)
print(averages.round(2), spreads.round(2))
print(measures.mean(axis=0).round(2), measures.std(axis=0).round(2))3One scale for every column
Your turnPut every column on one scale: take away its average, then divide by its standard deviation. Then scikit-learn's StandardScaler does the same, and np.allclose holds the two together.
Hint
Two arrays you made in step 2. NumPy does it for every column at once.
One way to do it
scaled = (measures - averages) / spreads
by_scaler = StandardScaler().fit_transform(measures)
print(scaled.mean(axis=0).round(2), scaled.std(axis=0).round(2))
print(np.allclose(scaled, by_scaler))4How far an average of ten moves
Your turnFrom Samples, averages and the normal distribution and Expectation and variance
Pick ten penguins at random and average their masses, 10,000 times. rng.choice(mass, size=(10_000, 10)) gives a row of ten masses for each draw. Then work out the same spread: one penguin's standard deviation, divided by the square root of 10.
Hint
Average across each row. The standard error is a standard deviation over a square root.
One way to do it
rng = np.random.default_rng(0)
mass = measures[:, 3]
draws = rng.choice(mass, size=(10_000, 10))
averages_of_ten = draws.mean(axis=1)
worked = mass.std() / np.sqrt(10)
print(averages_of_ten.std().round(3), worked.round(3))
plt.hist(averages_of_ten, bins=40)5Which columns move with mass
Your turnFrom Correlation and Expectation and variance
Each column's r with mass: multiply each penguin's scaled value by its scaled mass, and average over the penguins. Then np.corrcoef gives every r at once, a row for each column; its last row is each column against mass.
pandas gives the same table with df.corr(), but not as it stands: it stops on the species column, ValueError: could not convert string to float: 'Adelie'. df.corr(numeric_only=True) keeps only the number columns.
Hint
Column i of scaled is scaled[:, i]. Multiply it by mass_scaled, then take the average.
One way to do it
mass_scaled = scaled[:, 3]
r = np.array([(scaled[:, i] * mass_scaled).mean() for i in range(4)])
print(r.round(2))
print(np.corrcoef(measures.T)[3].round(2))6Inside each species
Your turnFrom Correlation
Bill depth's r with mass is below zero over all. Find it over all, then inside each species alone. groupby hands you each species' rows as a table of its own.
Hint
.corr on one column, with the other column in the brackets. Do the same on group in place of df.
One way to do it
over_all = df.bill_depth_mm.corr(df.body_mass_kg)
inside = {}
for name, group in df.groupby("species"):
inside[name] = group.bill_depth_mm.corr(group.body_mass_kg)
plt.scatter(group.bill_depth_mm, group.body_mass_kg, s=8, label=name)
plt.legend()
print(round(over_all, 2), {name: round(value, 2) for name, value in inside.items()})7A table you have not met
On your ownFrom Expectation and variance and Correlation
On your own now: 178 wines of three kinds, bundled with scikit-learn. from sklearn.datasets import load_wine, then load_wine(as_frame=True).frame gives a table, each wine's kind in target. Put its 13 measured columns on one scale in wine_scaled. Keep each column's r with alcohol, alcohol's own left out, in with_alcohol, the column that moves most with alcohol in top, and its r with alcohol inside each kind in top_inside.
Hint
Steps 3, 5 and 6 again, with pandas doing the r: .corr() on the 13 columns gives the whole table. .abs().idxmax() names the biggest r, up or down.
One way to do it
from sklearn.datasets import load_wine
wine = load_wine(as_frame=True).frame
wine_columns = wine.columns.drop("target")
wine_scaled = StandardScaler().fit_transform(wine[wine_columns])
with_alcohol = wine[wine_columns].corr()["alcohol"].drop("alcohol")
top = with_alcohol.abs().idxmax()
top_inside = {kind: group[top].corr(group.alcohol) for kind, group in wine.groupby("target")}
print(with_alcohol.round(2).sort_values().tail(3))
print(top, {kind: round(value, 2) for kind, value in top_inside.items()})Run on Pyodide 314, Python 3.14, NumPy 2.4, pandas 3.0, matplotlib 3.10 and scikit-learn 1.8. Checked on .
