LogisticRegression() 中的特征名称

数据挖掘 Python scikit-学习 逻辑回归
2022-01-26 23:57:34

我想知道 LogisticRegression() 模型使用的特征名称以及它们在 scikit-learn 中的相应权重。我可以使用 访问权重coef_,但我不知道如何将它们与相应的权重配对。

2个回答

如果您使用的是 sklearn 的 LogisticRegression,那么它的顺序与列名出现在训练数据中的顺序相同。见下面的代码。

#Train with Logistic regression
from sklearn.linear_model import LogisticRegression
from sklearn import metrics

model = LogisticRegression()
model.fit(X_train,Y_train)
#Print model parameters - the names and coefficients are in same order
print(model.coef_)
print(X_train.columns)

您还可以使用以下其他库进行验证

import statsmodels.api as sm
logit_model=sm.Logit(Y_train,X_train)
result=logit_model.fit()
print(result.summary2())

我做了一个场景:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model.logistic import LogisticRegression
from sklearn.metrics import accuracy_score

max_features = 100
tfidf = TfidfVectorizer(max_features=max_features)#stop_words='english',)# norm = None)#)

#Simple
texts_train = ['positive sample', 'again positive', 'negative sample', 'again negative']
target_train = [1,1,0,0]
texts_test = ['negative', 'positive']
target_test = [0,1]
texts_train1 = tfidf.fit_transform(texts_train)
texts_test1 = tfidf.transform(texts_test)
classifier = LogisticRegression()
classifier.fit(texts_train1, target_train)
predictions = classifier.predict(texts_test1)

print('accuracy (simple):', accuracy_score(target_test, predictions))
tfidf.get_feature_names()

['再次','负','正','样本']

classifier.coef_

数组([[ 0. , -0.56718183, 0.56718183, 0. ]]) 有道理!