【问题标题】:rfecv.fit() in python not accepting my x and y argumentspython中的rfecv.fit()不接受我的x和y参数
【发布时间】:2021-12-25 14:44:26
【问题描述】:

我真的是 Python 新手,所以我不知道很多基础知识,但我有一份必须用 Python 完成的大学报告,我正在努力弄清楚如何解决我的代码中的问题。

首先,我为 X 和 y 创建了训练数据,然后将其转换为 pandas DataFrame,以便我可以从 statsmodels 中调用 ols 作为我的初始模型。现在我想使用 rfe 来减少我的模型,我从 RFECV 开始,这样我就可以确定我希望 RFE 选择多少特征。但每次我运行代码时,我都会遇到 rfecv.fit() 的问题。

这是我的代码:

'''

from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
pipe = make_pipeline(StandardScaler())
pipe.fit(X_train, y_train)

#recombine training dataset in order to call ols
X_train_df = pd.DataFrame(X_train)
y_train_df = pd.DataFrame(y_train)
traindata = pd.concat([X_train_df.reset_index(drop=True), y_train_df.reset_index(drop=True)], axis=1)


#create first linear model
from statsmodels.formula.api import ols
model1 = ols('Tenure ~ Population + Children + Age + Income + Outage_sec_perweek + Email + Contacts + Yearly_equip_failure + MonthlyCharge + Bandwidth_GB_Year + Area_Suburban + Area_Urban + Marital_Married + Marital_Never_Married + Marital_Separated + Marital_Widowed + Gender_Male + Gender_Nonbinary + Churn_Yes + Contract_One_Year + Contract_Two_Year', data=traindata).fit()
print(model1.params)

#RFECV to determine number of variables to include for the optimal model
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import RFECV

svc = SVC(kernel="linear")
rfecv = RFECV(estimator = svc, step = 1, cv = StratifiedKFold, scoring = "accuracy")
rfecv.fit(X_train_df, y_train_df)

'''

输出错误如下所示: TypeError: Singleton array array(None, dtype=object) 不能被认为是一个有效的集合。

任何帮助或资源将不胜感激!谢谢

【问题讨论】:

  • 尝试打印您的 X_train_df 和 y_train_df 并检查它们的外观

标签: python pandas scikit-learn linear-regression rfe


【解决方案1】:

你需要传递cv = StratifiedKFold()而不是cv = StratifiedKFold,所以下面的方法可以工作:

rfecv = RFECV(estimator = svc, step = 1, cv = StratifiedKFold(), scoring = "accuracy")

或者如果你想要 10 折(默认为 5):

rfecv = RFECV(estimator = svc, step = 1, cv = StratifiedKFold(n_splits=10), scoring = "accuracy")

您可以从thisthis 等帖子中查看有/没有括号之间的区别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2020-05-17
    • 2015-02-14
    • 2014-01-25
    • 2019-07-14
    相关资源
    最近更新 更多