【发布时间】: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