我正在try 使用scaler、onhotcoder、多项式特征以及最终的线性回归模型制作管道

from sklearn.pipeline import Pipeline
pipeline = Pipeline([
                    ('scaler', StandardScaler(), num_cols),
                    ('polynom', PolynomialFeatures(3), num_cols), 
                    ('encoder', OneHotEncoder(), cat_cols),
                   ('linear_regression', LinearRegression() )
])

但当我安装管道时,我有一个ValueError:太多的值无法解包(预期为2个)

pipeline.fit(x_train,y_train)
pipeline.score(x_test, y_test)

推荐答案

如果我理解正确,您希望将管道的一些步骤应用于特定列.您必须使用ColumnTransformer,而不是在管道阶段的末尾添加列名(这是不正确的,并且会导致错误).Here你可以找到另一个类似的例子.

在你的情况下,你可以这样做:

import pandas as pd

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LinearRegression
from sklearn.compose import ColumnTransformer

# Fake data.
train_data = pd.DataFrame({'n1': range(10), 'n2': range(10)})
train_data['c1'] = 0
train_data['c1'][5:] = 1
y_train = [0]*10
y_train[5:] = [1]*5

# Here I assumed you are using a DataFrame. If not, use integer indices instead of column names.
num_cols = ['n1', 'n2']
cat_cols = ['c1']


# Pipeline to transform the numerical features.
numerical_transformer = Pipeline([('scaler', StandardScaler()),
                                  ('polynom', PolynomialFeatures(3))
    
])

# Apply the numerical transformer only on the numerical columns.
# Spearately, apply the OneHotEncoder.
ct = ColumnTransformer([('num_transformer', numerical_transformer, num_cols),
                        ('encoder', OneHotEncoder(), cat_cols)])

# Main pipeline for fitting.
pipeline = Pipeline([
                   ('column_transformer', ct),
                   ('linear_regression', LinearRegression() )
])

pipeline.fit(train_data, y_train)

从示意图上看,管道的布局如下所示:

enter image description here

Python相关问答推荐

已删除的构造函数调用另一个构造函数

Python中的负前瞻性regex遇到麻烦

在Python和matlab中显示不同 colored颜色 的图像

将numpy数组存储在原始二进制文件中

通过优化空间在Python中的饼图中添加标签

Pytest两个具有无限循环和await命令的Deliverc函数

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

如何在solve()之后获得症状上的等式的值

avxspan与pandas period_range

如何设置视频语言时上传到YouTube与Python API客户端

driver. find_element无法通过class_name找到元素'""

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

如何使用SentenceTransformers创建矢量嵌入?

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

使用特定值作为引用替换数据框行上的值

为什么我的sundaram筛这么低效

在二维NumPy数组中,如何 Select 内部数组的第一个和第二个元素?这可以通过索引来实现吗?

使用tqdm的进度条

Js的查询结果可以在PC Chrome上显示,但不能在Android Chrome、OPERA和EDGE上显示,而两者都可以在Firefox上运行