fit_transform和transform有什么区别? 为什么直接转换不起作用?
from sklearn.preprocessing import StandardScaler
X_scaler = StandardScaler()
X_train = X_scaler.fit_transform(X_train)
X_test = X_scaler.transform(X_test)
如果直接转换则会出现以下错误
NotFittedError: This StandardScaler instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
最佳答案
StandardScaler
,如per documentation :
Standardize features by removing the mean and scaling to unit variance
因此它需要首先了解数据的均值和方差。
因此需要 fit()
或 fit_transform()
,以便 StandardScaler
可以遍历所有数据来查找均值和方差。那些可以访问
按属性:
mean_ : The mean value for each feature (column) in the training set.
var_ : The variance for each feature in the training set.
请注意,这些数据将针对数据中的每一列单独计算。
在transform()
中,它只会使用这些均值
和方差
值来缩放数据。
现在您可能会说为什么它不在 transform()
期间计算这些属性。这样做是为了以与训练数据相同的方式缩放测试数据(来自 fit_transform()
)。如果您在每次调用 transform()
时计算数据的均值和方差,那么所有传递的数据将具有不同的比例,这不是您想要的。
这对于所有 scikit 变压器都是如此。
1) fit()
- 只会遍历数据并保存数据的所有需要的属性
2) transform()
- 使用 fit()
保存的属性来更改数据
3) fit_transform()
- fit()
的实用函数,然后 transform()
相同的数据。
通常,您会在训练数据上调用 fit_transform()
,而在测试数据上仅调用 transform()
。
关于python-3.x - sklearn StandardScaler,不允许直接变换,我们需要 fit_transform,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51988030/