Exercises
Preprocessing
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Scale the features and print the mean and standard deviation of each column afterwards.
Python needs scikit-learn, downloaded on first run
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[25.0, 30000.0], [26.0, 31000.0], [55.0, 30500.0], [56.0, 31500.0]])
# scale, then print the column means and stds, rounded
fit_transform does both steps. axis=0 works down the columns.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[25.0, 30000.0], [26.0, 31000.0], [55.0, 30500.0], [56.0, 31500.0]])
scaled = StandardScaler().fit_transform(X)
print(scaled.mean(axis=0).round(2))
print(scaled.std(axis=0).round(2))Exercise 2Passed
Encode the colours so no false ordering is invented.
Python needs scikit-learn, downloaded on first run
import numpy as np
from sklearn.preprocessing import OrdinalEncoder
colours = np.array([["red"], ["green"], ["blue"]])
print(OrdinalEncoder().fit_transform(colours).shape)Give each colour its own column.
import numpy as np
from sklearn.preprocessing import OneHotEncoder
colours = np.array([["red"], ["green"], ["blue"]])
print(OneHotEncoder(sparse_output=False).fit_transform(colours).shape)Exercise 3Passed
Fit the scaler on the training data only, then transform both. Print the transformed test value.
Python needs scikit-learn, downloaded on first run
import numpy as np
from sklearn.preprocessing import StandardScaler
train = np.array([[10.0], [20.0], [30.0]])
test = np.array([[40.0]])
# fit on train only, print the transformed test value rounded to two places
fit(train), then transform each.
import numpy as np
from sklearn.preprocessing import StandardScaler
train = np.array([[10.0], [20.0], [30.0]])
test = np.array([[40.0]])
scaler = StandardScaler().fit(train)
print(scaler.transform(test).round(2).ravel())