如何在scikit中标准化目标数据学习回归

时间:2014-10-27 09:59:22

标签: python machine-learning scikit-learn svm predict

我试图以csv格式预测铜矿企业数据数据集中的未来利润数据。

我读了数据:

data = pd.read_csv('data.csv')

我拆分了数据:

data_target = data[target].astype(float)
data_used = data.drop(['Periodo', 'utilidad_operativa_dolar'], axis=1)
x_train, x_test, y_train, y_test = train_test_split(data_used, data_target, test_size=0.4,random_state=33)

创建一个svr预测器:

clf_svr= svm.SVR(kernel='rbf')

标准化数据:

from sklearn.preprocessing import StandardScaler
scalerX = StandardScaler().fit(x_train)
scalery = StandardScaler().fit(y_train)

x_train = scalerX.transform(x_train)
y_train = scalery.transform(y_train)
x_test = scalerX.transform(x_test)
y_test = scalery.transform(y_test)

print np.max(x_train), np.min(x_train), np.mean(x_train), np.max(y_train), np.min(y_train), np.mean(y_train)

然后预测:

y_pred=clf.predict(x_test)

预测数据也是标准化的。我希望预测数据采用原始格式,我该怎么做?

3 个答案:

答案 0 :(得分:6)

您可能希望使用y-scaler的inverse_transform方法。请注意,您可以使用管道更简洁地完成所有这些操作,如下所示

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR

pipeline = Pipeline([('scaler', StandardScaler()), ('estimator', SVR(kernel="rbf"))])

y_scaler = StandardScaler()
y_train = y_scaler.fit_transform(y_train)
pipeline.fit(x_train, y_train)
y_pred = y_scaler.inverse_transform(pipeline.predict(x_test))

许多人只会在全球范围内扩展目标并在没有太多过度拟合的情况下逃脱。但你并没有因此而堕落。如代码中所示,使用单独的y数据缩放器的AFAIK是唯一的方法。

答案 1 :(得分:3)

我知道这个问题很旧,当时的答案是正确的,但是现在有一种scikit-learn方法可以做到这一点。

http://scikit-learn.org/dev/modules/compose.html#transforming-target-in-regression

答案 2 :(得分:0)

正如其他人已经提到的那样,您应该使用inverse_transform()方法从之前应用的相应转换中检索原始数据。 需要考虑的另一点是,如果我们要预测实际目标“ y”值,为什么需要转换目标y_test, y_train?在预测过程中,我们可能还处于其原始状态。

此外(在Python 3.7.3中,sklearn 0.20.3),当您像上面所做的那样标准化y_test, y_train之类的单列行时,无意中将输出作为numpy数组接收,这对Dataframe操作无济于事;

例如:

enter image description here

当您确实指定输出应类似于单个列的Dataframe时,可能会遇到更多问题;

例如:

enter image description here enter image description here

解决方案:您将必须使用适当的子集选择运算符(.loc / .iloc)在列表中明确声明目标列名称/索引。

例如:

enter image description here

注意::在实时ML项目中,当您的模型准备在生产阶段进行调整时,测试数据会在将来到达或实时收集。

X_train, X_test这样的标准化训练测试功能集有助于轻松比较均值的特征变化,并且对正则化主成分分析技术很有用要求对特征变量进行标准化。