在此步骤中,我们将使用已拟合的 scaler 来转换我们的数据。transform() 方法将缩放转换应用于数据,使用在 fit() 步骤中计算的均值和标准差。这将使我们的数据中心化,均值为 0,标准差为 1。
我们将把转换后的数据存储在一个名为 X_scaled 的新变量中,以保持原始数据不变。
理解代码:
X_scaled = scaler.transform(X):将学习到的转换应用于我们的数据
np.set_printoptions(precision=2, suppress=True):格式化输出以提高可读性
precision=2:显示 2 位小数
suppress=True:对非常小/大的数字使用科学计数法
np.mean(X, axis=0):沿轴 0(列)计算均值
axis=0:计算所有样本中每个特征(列)的均值
- 结果:每个特征一个均值
在你的 preprocess.py 文件中,在 ## --- Step 4: Transform the data --- 注释下添加以下代码。我们将打印原始数据和缩放后数据的均值,以观察转换的效果。
## --- Step 4: Transform the data ---
X_scaled = scaler.transform(X)
## Use numpy to set precision for cleaner output
np.set_printoptions(precision=2, suppress=True)
print("Original data mean:", np.mean(X, axis=0))
print("Scaled data mean:", np.mean(X_scaled, axis=0))
print("Scaled data sample:\n", X_scaled[:5])
保存文件并运行它。
python3 preprocess.py
你将看到缩放后数据的均值实际上为零,并且样本数据值已被转换。
Shape of features (X): (150, 4)
Shape of target (y): (150,)
Scaler object created: StandardScaler()
Scaler mean: [5.84333333 3.05733333 3.758 1.19933333]
Original data mean: [5.84 3.06 3.76 1.2 ]
Scaled data mean: [-0. -0. -0. -0.]
Scaled data sample:
[[-0.9 1.02 -1.34 -1.32]
[-1.14 -0.13 -1.34 -1.32]
[-1.39 0.33 -1.4 -1.32]
[-1.51 0.1 -1.28 -1.32]
[-1.02 1.25 -1.34 -1.32]]