【问题标题】:Using numpy.ndarray vs. Pandas Dataframe in sklearn's .fit() method在 sklearn 的 .fit() 方法中使用 numpy.ndarray 与 Pandas Dataframe
【发布时间】:2019-06-15 01:40:13
【问题描述】:

我正在对我的数据使用逻辑回归模型。据我了解(例如,从这里:Pandas vs. Numpy Dataframes),将 numpy.ndarray 与 sklearn 一起使用比使用 Pandas Dataframes 更好。这可以通过使用数据框上的 .values 属性来完成。我已经这样做了,但是得到了 ValueError:仅熊猫 DataFrames 支持使用字符串指定列。 显然,我的代码做错了什么。非常感谢任何见解。

有趣的是,我的代码在我不使用 .values 时有效,并且只使用 X 作为 DataFrame 和 y 作为 Pandas 系列。

# We will train our classifier with the following features:
# Numeric features to be scaled: LIMIT_BAL, AGE, PAY_X, BIL_AMTX, and PAY_AMTX
# Categorical features: SEX, EDUCATION, MARRIAGE

# We create the preprocessing pipelines for both numeric and categorical data
numeric_features = ['LIMIT_BAL', 'AGE', 'PAY_1', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6', 
                 'BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', 'BILL_AMT5', 'BILL_AMT6', 
                 'PAY_AMT1', 'PAY_AMT2', 'PAY_AMT3', 'PAY_AMT4', 'PAY_AMT5', 'PAY_AMT6']

data['PAY_1'] = data.PAY_1.astype('float64')
data['PAY_2'] = data.PAY_2.astype('float64')
data['PAY_3'] = data.PAY_3.astype('float64')
data['PAY_4'] = data.PAY_4.astype('float64')
data['PAY_5'] = data.PAY_5.astype('float64')
data['PAY_6'] = data.PAY_6.astype('float64')
data['AGE'] = data.AGE.astype('float64')


numeric_transformer = Pipeline(steps=[
('scaler', MinMaxScaler())
])

categorical_features = ['SEX', 'EDUCATION', 'MARRIAGE']
categorical_transformer = Pipeline(steps=[
('onehot', OneHotEncoder(categories='auto'))
])

preprocessor = ColumnTransformer(
transformers=[
    ('num', numeric_transformer, numeric_features),
    ('cat', categorical_transformer, categorical_features)
])

y = data['default'].values
X = data.drop('default', axis=1).values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, 
random_state=10, stratify=y)

# Append classifier to preprocessing pipeline.
# Now we have a full prediction pipeline.
lr = Pipeline(steps=[('preprocessor', preprocessor),
                 ('classifier', LogisticRegression(solver='liblinear'))])

param_grid_lr = {
'classifier__C': np.logspace(-5, 8, 15)
}

lr_cv = GridSearchCV(lr, param_grid_lr, cv=10, iid=False)

lr_cv.fit(X_train, y_train)

ValueError: 仅 Pandas DataFrames 支持使用字符串指定列

【问题讨论】:

  • 添加了预处理器的代码

标签: python pandas numpy scikit-learn


【解决方案1】:

您正在使用ColumnTransformer,就好像您有一个数据框,但您没有...

column(s) :字符串或整数,字符串或整数的类数组,切片,布尔掩码数组或可调用的

在第二个轴上索引数据。整数被解释为位置列,而字符串可以通过名称引用 DataFrame 列。如果转换器期望 X 是一维数组(向量),则应使用标量字符串或整数,否则将向转换器传递一个二维数组。一个可调用对象被传递了输入数据 X 并且可以返回上述任何一个。

如果为列传递字符串,则需要传递数据框。如果你想使用一个 numpy 数组,那么首先可能不需要转换,你需要指定整数而不是字符串作为索引。

【讨论】:

  • 谢谢你,马修。在 pandas 数据帧上使用 numpy 数组有什么好处吗?我看不出会有,我只是想知道。
  • 取决于之后的算法,对于某些模型来说,连续数组可能会更好。
猜你喜欢
  • 2021-06-21
  • 2019-11-12
  • 1970-01-01
  • 2016-07-27
  • 2017-04-02
  • 2019-12-22
  • 2019-09-19
  • 2018-02-08
  • 2021-10-14
相关资源
最近更新 更多