python - 使用 Sklearn 库的 StandardScaler 缩放目标变量在 Python 中出错

标签 python scikit-learn

通过使用 StandardScaler 类的正常过程缩放目标变量会出错。但是,通过添加一行 y = y.reshape(-1,1) 解决了错误。之后在目标变量上应用 fit_transform 方法给出标准化值。我无法弄清楚添加 y.reshape(-1,1) 是如何让它起作用的?

X 是具有一项特征的自变量,y 是数值目标变量“薪水”。我试图将支持向量回归应用于需要显式特征缩放的问题。我尝试了以下代码:

from sklearn.preprocessing import StandardScaler

sc_X = StandardScaler()
sc_y = StandardScaler()

X = sc_X.fit_transform(X)
y = sc_y.fit_transform(y)

它给了我这样的错误:

ValueError: Expected 2D array, got 1D array instead Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

在我做了以下更改之后:

X = sc_X.fit_transform(X)
y = y.reshape(-1,1)
y = sc_y.fit_transform(y)

标准化工作得很好。我需要了解添加此 y = y.reshape(-1,1) 如何帮助实现它。 谢谢。

最佳答案

简而言之,是的,您需要对其进行转换。这是因为根据 sklearn documentation , fit_transform 期望 X 或预测变量由 n_samplesn_features 组成,这对它有意义用于。仅提供一维数组,此函数会将其读取为 n_feature 的 1 个样本。也许附上下面的代码会使这一点更清楚:

In [1]: x_arr                                                                                                                                                                                                     
Out[1]: array([1, 2, 3, 4, 5]) # will be considered as 1 sample of 5 feature

In [2]: x_arr.reshape(-1,1)                                                                                                                                                                                       
Out[2]: 
array([[1], # 1st sample
       [2], # 2nd sample
       [3], # 3rd sample
       [4], # 4th sample
       [5]])# 5th sample

无论如何,关于如何使用 StandardScaler(与上面回答的关于为什么代码产生错误的问题无关),您想要做的是使用相同的 StandardScaler 整个数据。一般来说,缩放目标变量不是必需的,因为它是您要预测的变量,而不是预测变量(假设代码中的 y 是目标变量)。

首先,您想要存储训练数据的均值和标准差,以便稍后用于缩放测试数据。

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()

# Here the scaler will learn the mean and std of train data
x_train_scaled = scaler.fit_transform(x_train, y_train)

# Use here to transform test data
# This ensures both the train and test data are in the same scale
x_test_scaled = scaler.transform(x_test)

希望这对您有所帮助!

关于python - 使用 Sklearn 库的 StandardScaler 缩放目标变量在 Python 中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57848731/

相关文章:

python - 从 python 脚本启动 Node 应用程序

python - 尝试写入 BigQuery 时 Apache Beam 中没有属性 'TableReference'

cluster-analysis - 使用自定义距离度量对纬度/经度对进行聚类

python - 使用 ScikitLearn 的多元线性回归,不同的方法给出不同的答案

python - 使用 sklearn 预处理 Label Binarizer 的一种热编码

python - 如何将向量拆分为列 - 使用 PySpark

python - 为什么这一行会产生错误?

python - 如何查看已完成或剩余的map_async作业数量?

python - 在 scikit-learn 中实现 R 随机森林特征重要性评分

python - svc.predict 可以返回结果以及其他类的概率吗?