【发布时间】:2020-12-19 03:32:50
【问题描述】:
我正在尝试弄清楚如何在使用管道时对数据进行缩放(可能使用 inverse_transform)以进行预测。下面的数据只是一个例子。我的实际数据更大更复杂,但我希望使用 RobustScaler(因为我的数据有异常值)和 Lasso(因为我的数据有几十个无用的特征)。一般来说,我对管道很陌生。
基本上,如果我尝试使用此模型来预测任何事情,我希望以未缩放的术语进行预测。这可以通过管道实现吗?如何使用 inverse_transform 做到这一点?
import pandas as pd
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler
data = [[100, 1, 50],[500 , 3, 25],[1000 , 10, 100]]
df = pd.DataFrame(data,columns=['Cost','People', 'Supplies'])
X = df[['People', 'Supplies']]
y = df[['Cost']]
#Split
X_train,X_test,y_train,y_test = train_test_split(X,y)
#Pipeline
pipeline = Pipeline([('scale', RobustScaler()),
('alg', Lasso())])
clf = pipeline.fit(X_train,y_train)
train_score = clf.score(X_train,y_train)
test_score = clf.score(X_test,y_test)
print ("training score:", train_score)
print ("test score:", test_score)
#Predict example
example = [[10,100]]
clf.predict(example)
【问题讨论】:
-
您的数据是否按输出缩放?我没有在代码中看到您在输入上调用
.transform()以使用robustscaler,无论是用于您的训练还是测试 -
也许那是我的问题之一。同样,对管道来说非常新。我应该在管道中的某处调用 fit_transform() 吗?
-
典型的工作流是
pipeline.fit(train),pipeline.transform(train),pipeline.transform(test),那么你应该可以使用内置的inverse_transform在预测后反转转换 -
所以当我尝试做 pipeline.transform(X_train,y_train) 时,我得到一个错误:AttributeError: 'Lasso' object has no attribute 'transform'。
-
看起来像管道无法转换的问题,除非转换器是最后一步。解决方法在this question 中讨论
标签: python python-3.x machine-learning pipeline lasso-regression