mel*_*mel 10 python feature-selection scikit-learn
我很确定之前有人问过,但我找不到答案
在python上使用sklearn运行Logistic回归,我可以使用Transform方法将我的数据集转换为最重要的特征
classf = linear_model.LogisticRegression()
func = classf.fit(Xtrain, ytrain)
reduced_train = func.transform(Xtrain)
Run Code Online (Sandbox Code Playgroud)
如何判断哪些功能最重要?更一般地说,如何计算数据集中每个要素的p值?
如上述评论所建议,您可以(并且应该)在拟合之前对数据进行缩放,从而使系数具有可比性。下面是一些代码,显示了它如何工作。我按照这种格式进行比较。
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
import pandas as pd
import matplotlib.pyplot as plt
x1 = np.random.randn(100)
x2 = np.random.randn(100)
x3 = np.random.randn(100)
#Make difference in feature dependance
y = (3 + x1 + 2*x2 + 5*x3 + 0.2*np.random.randn()) > 0
X = pd.DataFrame({'x1':x1,'x2':x2,'x3':x3})
#Scale your data
scaler = StandardScaler()
scaler.fit(X)
X_scaled = pd.DataFrame(scaler.transform(X),columns = X.columns)
clf = LogisticRegression(random_state = 0)
clf.fit(X_scaled, y)
feature_importance = abs(clf.coef_[0])
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + .5
featfig = plt.figure()
featax = featfig.add_subplot(1, 1, 1)
featax.barh(pos, feature_importance[sorted_idx], align='center')
featax.set_yticks(pos)
featax.set_yticklabels(np.array(X.columns)[sorted_idx], fontsize=8)
featax.set_xlabel('Relative Feature Importance')
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
coef_您可以查看拟合模型属性中的系数,以了解哪些特征最重要。(对于 LogisticRegression,transform所做的就是查看哪些系数的绝对值最高。)
大多数 scikit-learn 模型不提供计算 p 值的方法。从广义上讲,这些模型旨在用于实际预测输出,而不是用于检查以收集对如何完成预测的理解。如果您对 p 值感兴趣,您可以看看statsmodels,尽管它比 sklearn 不太成熟。