我将把这个答案分成两部分。先了解 StandardScaler 的 fit_tansform 函数的输入,再了解输出。
如果您遵循 fit_transform 函数的 StandardScaler 文档,它会说:
参数:X 类形状的数组 (n_samples, n_features) 输入样本。
返回 X_newndarray 形状数组 (n_samples, n_features_new)
理解输入:
在这里,当您执行 X[:,0] 时,您将获得整列,但在一行中。这是一个随机 3x2 数组的示例:
import numpy as np
X = np.random.random_sample((3,2))*10
print(X)
print(X[:,0])
print(X[:,0].shape)
给予
[[3.5782437 6.12481959]
[9.2333248 8.49628361]
[8.56447626 5.24588392]]
[3.5782437 9.2333248 8.56447626]
(3,)
这是我们的第一个问题。 StandardScaler 需要一个二维数组,其中行是每个样本,列是特征,在本例中是 1 个特征。因此,我们需要一个 (3x1) 二维数组,但我们有一个 (3,) 一维数组。这会导致您在没有重塑的情况下得到错误。要将我们的一维数组转换为函数期望的形状,我们使用reshape。该函数需要一个 shape 参数。我们想要一个 (3x1) 形状,因此,使用 reshape(-1,1) (-1 表示 numpy 将推断我们想要所有元素)。
要确认这一点:
print(X[:,0].reshape(-1,1))
给予
[[9.31648164]
[6.74048286]
[7.57667118]]
现在,我们准备将其输入到 StandardScaler 的 fit_transform 中。
二、fit_transform的输出:
让我们看看它的输出的形状:
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
print(sc.fit_transform(X[:,0].reshape(-1,1)))
print(sc.fit_transform(X[:,0].reshape(-1,1)).shape)
给予
[[ 1.34073239]
[-1.06001668]
[-0.28071571]]
(3, 1)
当 X[:,0] 实际上是一个 (3,) 一维数组时,我们得到一个 3x1 二维数组。我们想将此数组展平为一维数组。有多种方法可以做到这一点。我们可以再次使用 reshape,给一个值表示一维数组,-1 表示所有值:
temp = sc.fit_transform(X[:,0].reshape(-1,1)).reshape(-1)
print(temp)
print(temp.shape)
给予
[ 1.34073239 -1.06001668 -0.28071571]
(3,)
这意味着X[:,0] = sc.fit_transform(X[:,0].reshape(-1,1)).reshape(-1) 可以工作。
使用ravel 或flatten 也可以。