使用递归特征消除时出现TypeError:__init__()参数数量不符
问题描述
运行代码时出现错误:
TypeError: __init__() takes 2 positional arguments but 3 were given.
完整报错信息:
runfile('C:/Users/drash/OneDrive/Desktop/Howto Health/preprocessing 1.py', wdir='C:/Users/drash/OneDrive/Desktop/Howto Health') Traceback (most recent call last): File "C:\Users\drash\OneDrive\Desktop\Howto Health\preprocessing 1.py", line 60, in <module> rfe = RFE(model, 10) TypeError: __init__() takes 2 positional arguments but 3 were given
相关代码片段:
features = ['EMB_CD3', 'EMB_CD45R0', 'EMB_LFA1', 'EMB_Perforin', 'EMB_Mac', 'EMB_HLA1', 'EMB_CD54', 'EMB_VCAM', 'Virus:1=Cox,4=B19V,6=HHV6,5=EBV,2=ADV(including double infections)', 'Viral_load_B19V-VP1_mRNA', 'Viral_load_DNA_B19V','Virus_EBV', 'Virus_HHV-6', 'B19V-Typ1'] df_new = df[features].copy() #KNN Imputer for missing values imputer = KNNImputer(n_neighbors=3) imputed = imputer.fit_transform(df_new) df_imputed = pd.DataFrame(imputed, columns=df_new.columns) X = df_imputed Y = df['target'].astype(int) #%% feature extraction using Recursive Feature Elimination model = LogisticRegression(solver='lbfgs') rfe = RFE(model, 10) fit = rfe.fit(X, Y) print("Num Features: %s" % (fit.n_features_)) print("Selected Features: %s" % (fit.support_)) print("Feature Ranking: %s" % (fit.ranking_))
问题解决
这个错误是因为新版本scikit-learn中,RFE的构造函数不再支持通过位置参数传递特征数量。旧版写法RFE(model, 10)在新版中不再适用,n_features_to_select必须用关键字参数指定。
修正后的RFE初始化代码:
rfe = RFE(model, n_features_to_select=10)
完整修正后的特征提取部分代码:
#%% feature extraction using Recursive Feature Elimination model = LogisticRegression(solver='lbfgs') rfe = RFE(model, n_features_to_select=10) fit = rfe.fit(X, Y) print("Num Features: %s" % (fit.n_features_)) print("Selected Features: %s" % (fit.support_)) print("Feature Ranking: %s" % (fit.ranking_))
原理说明:scikit-learn 1.0+版本中,RFE的__init__方法签名变更,除第一个必选参数estimator外,其余参数都需要显式指定关键字,不能再用位置参数传递,否则会被识别为多余参数,触发TypeError。
内容的提问来源于stack exchange,提问作者drashti bhatt
相关产品推荐
相关产品推荐

