我正在尝试获得泰坦尼克号数据集上的最终管道(示例取自“手- on ML”一书)。
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelBinarizer
num_pipeline = Pipeline([
('selector', DataFrameSelector(list(df_num))),
('imputer',SimpleImputer(strategy='median', fill_value='num',missing_values=np.nan)),
('std_scaler',StandardScaler())
])
cat_pipeline = Pipeline([
('selector', DataFrameSelector(list(df_cat))),
('imputer',SimpleImputer(strategy='most_frequent', fill_value='categorical',missing_values=np.nan)),
('cat_encoder', OneHotEncoder(sparse=False)),
])from sklearn.pipeline import FeatureUnion
full_pipeline = FeatureUnion(transformer_list=[
("num_pipeline", num_pipeline),
("cat_pipeline", cat_pipeline),
])
df_prepared = full_pipeline.fit_transform(df)
df_prepared.shape
df_total = pd.DataFrame(df_prepared, columns=df.columns)
df_total哪里
df_num = ['Pclass', 'Age', 'SibSp', 'Parch', 'Fare']
df_cat = ['Sex', 'Embarked']问题是我得到了ValueError:
ValueError: Shape of passed values is (668, 10), indices imply (668, 7)我尝试将'Embarked'从df_cat中删除,它以某种方式创建了DF (但它是不准确的)。我认为它不起作用,因为'Embarked'有3个类别(10-3=7-这就是我想要的列数)。
如果删除'Sex'类别,则得到ValueError: Shape of passed values is (668, 8), indices imply (668, 7) (10-2=8)。
如何使用Pipeline()对这两个类别进行编码,以及我做了哪些错误的步骤?
发布于 2020-07-14 14:48:10
df.columns是不正确的,因为在一次热编码之后,有更多的列具有不同的名称。在您的示例中,而不是Sex,实际值有两列,而不是Embarked,只有三列。
管道的全部目的是创建这些额外的列,那么为什么要删除它们呢?我不知道您在哪里定义df.columns,但在我看来,在这一行中发生了错误:
df_total = pd.DataFrame(df_prepared, columns=df.columns)https://datascience.stackexchange.com/questions/77703
复制相似问题