python - 如何让文本对象与 sklearn 分类器管道一起工作?

标签 python python-3.x pandas machine-learning scikit-learn

目标:当模型输入为 int、float 和对象(根据 pandas 数据框)时,使用 sklearn 预测一组给定类的概率。

我正在使用 UCI 存储库中的以下数据集: Auto Dataset

我创建了一个几乎可以工作的管道:

# create transformers for the different variable types.

from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
import pandas as pd
import numpy as np

data = pd.read_csv(r"C:\Auto Dataset.csv")
target = 'aspiration'
X = data.drop([target], axis = 1)
y = data[target]

integer_transformer = Pipeline(steps = [
   ('imputer', SimpleImputer(strategy = 'most_frequent')),
   ('scaler', StandardScaler())])

continuous_transformer = Pipeline(steps = [
   ('imputer', SimpleImputer(strategy = 'most_frequent')),
   ('scaler', StandardScaler())])

categorical_transformer = Pipeline(steps = [
   ('imputer', SimpleImputer(strategy = 'most_frequent')),
   ('lab_enc', OneHotEncoder(handle_unknown='ignore'))])

# Use the ColumnTransformer to apply the transformations to the correct columns in the dataframe.
integer_features = X.select_dtypes(include=['int64'])
continuous_features = X.select_dtypes(include=['float64'])
categorical_features = X.select_dtypes(include=['object'])

import numpy as np

from sklearn.compose import ColumnTransformer

preprocessor = ColumnTransformer(
   transformers=[
       ('ints', integer_transformer, integer_features),
       ('cont', continuous_transformer, continuous_features),
       ('cat', categorical_transformer, categorical_features)])

# Create a pipeline that combines the preprocessor created above with a classifier.
from sklearn.neighbors import KNeighborsClassifier

base = Pipeline(steps=[('preprocessor', preprocessor),
                     ('classifier', KNeighborsClassifier())])

当然,我想利用 predict_proba(),这最终给我带来了一些麻烦。我尝试了以下方法:

model = base.fit(X,y )
preds = model.predict_proba(X)

但是,我收到一个错误:

ValueError: No valid specification of the columns. Only a scalar, list or slice of all integers or all strings, or boolean mask is allowed

当然,这里是完整的回溯:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-37-a1a29a8b3623> in <module>()
----> 1 base_learner.fit(X)

D:\Anaconda3\lib\site-packages\sklearn\pipeline.py in fit(self, X, y, **fit_params)
    263             This estimator
    264         """
--> 265         Xt, fit_params = self._fit(X, y, **fit_params)
    266         if self._final_estimator is not None:
    267             self._final_estimator.fit(Xt, y, **fit_params)

D:\Anaconda3\lib\site-packages\sklearn\pipeline.py in _fit(self, X, y, **fit_params)
    228                 Xt, fitted_transformer = fit_transform_one_cached(
    229                     cloned_transformer, Xt, y, None,
--> 230                     **fit_params_steps[name])
    231                 # Replace the transformer of the step with the fitted
    232                 # transformer. This is necessary when loading the transformer

D:\Anaconda3\lib\site-packages\sklearn\externals\joblib\memory.py in __call__(self, *args, **kwargs)
    327 
    328     def __call__(self, *args, **kwargs):
--> 329         return self.func(*args, **kwargs)
    330 
    331     def call_and_shelve(self, *args, **kwargs):

D:\Anaconda3\lib\site-packages\sklearn\pipeline.py in _fit_transform_one(transformer, X, y, weight, **fit_params)
    612 def _fit_transform_one(transformer, X, y, weight, **fit_params):
    613     if hasattr(transformer, 'fit_transform'):
--> 614         res = transformer.fit_transform(X, y, **fit_params)
    615     else:
    616         res = transformer.fit(X, y, **fit_params).transform(X)

D:\Anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py in fit_transform(self, X, y)
    445         self._validate_transformers()
    446         self._validate_column_callables(X)
--> 447         self._validate_remainder(X)
    448 
    449         result = self._fit_transform(X, y, _fit_transform_one)

D:\Anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py in _validate_remainder(self, X)
    299         cols = []
    300         for columns in self._columns:
--> 301             cols.extend(_get_column_indices(X, columns))
    302         remaining_idx = sorted(list(set(range(n_columns)) - set(cols))) or None
    303 

D:\Anaconda3\lib\site-packages\sklearn\compose\_column_transformer.py in _get_column_indices(X, key)
    654         return list(np.arange(n_columns)[key])
    655     else:
--> 656         raise ValueError("No valid specification of the columns. Only a "
    657                          "scalar, list or slice of all integers or all "
    658                          "strings, or boolean mask is allowed")

不确定我遗漏了什么,但会感谢任何可能的帮助。

编辑: 我正在使用 sklearn 版本 0.20。

最佳答案

错误消息为您指明了正确的方向。列应按名称或索引指定,但您将数据列作为 DataFrame 传递。

df.select_dtypes() 不输出列索引。它输出具有匹配列的 DataFrame 的子集。你的代码应该是

# Use the ColumnTransformer to apply the transformations to the correct columns in the dataframe.
integer_features = list(X.columns[X.dtypes == 'int64'])
continuous_features = list(X.columns[X.dtypes == 'float64'])
categorical_features = list(X.columns[X.dtypes == 'object'])

因此,例如,整数列作为列表传递 ['curb-weight', 'engine-size', 'city-mpg', 'highway-mpg']

关于python - 如何让文本对象与 sklearn 分类器管道一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54987484/

相关文章:

python-2.7 - 将列设置为索引时 Dtype 发生变化

python - 将带有元素日期标签的年度财政数据元组 Munge 转换为 Python Pandas 中的时间序列

python - Django DateTimeField 很幼稚,但 USE_TZ = True

python - 具有多个条件的元组排序

python - 根据形状对 numpy 数组列表进行分组。 Pandas ?

python - DataFrame.resample 不包括最后一行

python - 如何用py2exe打包Twisted程序?

python - Django - 在 Formset 中禁用对现有表单的编辑,但允许在新表单中进行编辑

python-3.x - 结束 ='' 语法错误 : invalid syntax

python - 删除一行中特定单词的重复