来自 sklearn 管道的特征名称:未安装错误

feature names from sklearn pipeline: not fitted error

我正在使用 scikit learn 进行文本分类实验。现在我想获得性能最佳的选定功能的名称。我尝试了一些类似问题的答案,但没有任何效果。最后几行代码是我尝试过的示例。例如,当我打印 feature_names 时,出现此错误:sklearn.exceptions.NotFittedError: This SelectKBest instance is not fitted yet. Call 'fit' with appropriate arguments before using this method. 有什么解决办法吗?

scaler = StandardScaler(with_mean=False) 

enc = LabelEncoder()
y = enc.fit_transform(labels)

feat_sel = SelectKBest(mutual_info_classif, k=200)  
clf = linear_model.LogisticRegression()

pipe = Pipeline([('vectorizer', DictVectorizer()),
                 ('scaler', StandardScaler(with_mean=False)),
                 ('mutual_info', feat_sel),
                 ('logistregress', clf)])

feature_names = pipe.named_steps['mutual_info']
X.columns[features.transform(np.arange(len(X.columns)))]

您首先必须安装管道,然后调用feature_names:

解决方案

scaler = StandardScaler(with_mean=False) 

enc = LabelEncoder()
y = enc.fit_transform(labels)

feat_sel = SelectKBest(mutual_info_classif, k=200)  
clf = linear_model.LogisticRegression()

pipe = Pipeline([('vectorizer', DictVectorizer()),
                 ('scaler', StandardScaler(with_mean=False)),
                 ('mutual_info', feat_sel),
                 ('logistregress', clf)])

# Now fit the pipeline using your data
pipe.fit(X, y)

#now can the pipe.named_steps
feature_names = pipe.named_steps['mutual_info']
X.columns[features.transform(np.arange(len(X.columns)))]

一般信息

从文档 example here 您可以看到

anova_svm.set_params(anova__k=10, svc__C=.1).fit(X, y)

这会设置一些初始参数(anova 的 k 参数和 svc 的 C 参数)

然后调用 fit(X,y) 来适应管道。

编辑:

对于新错误,由于您的 X 是字典列表,我看到了一种调用所需列方法的方法。这可以使用 pandas.

来完成
X= [{'age': 10, 'name': 'Tom'}, {'age': 5, 'name': 'Mark'}]

df = DataFrame(X) 
len(df.columns)

结果:

2

希望对您有所帮助