首页 > 解决方案 > 如何计算哪个自变量对因变量的影响最大?

问题描述

我有一个包含 5 个自变量和 1 个因变量的数据框。我所有的变量都是连续的,包括因变量。有没有一种方法可以计算我的哪些自变量在 python 中对我的因变量影响最大?有没有我可以运行的算法来为我做这件事?

我尝试了信息增益方法,但这是一种分类方法,因此必须使用标签编码器来转换我的因变量。在将数据集拆分为训练集和测试集后,我使用了以下代码

#encoding the dependant variable
lab_enc = preprocessing.LabelEncoder()
training_scores_encoded = lab_enc.fit_transform(y_train)

#SelectFromModel will select those features which importance is greater than the mean importance of all the features by default, but we can alter this threshold if we want.
#Firstly, I specify the random forest instance, indicating the number of trees.
#Then I use selectFromModel object from sklearn to automatically select the features.
sel = SelectFromModel(RandomForestClassifier(n_estimators = 100))
sel.fit(X_train, training_scores_encoded)

#We can now make a list and count the selected features.    
selected_feat= X_train.columns[(sel.get_support())]
len(selected_feat)

#viewing the importances 
import matplotlib.pyplot as plt
importances = sel.estimator_.feature_importances_
indices = np.argsort(importances)[::-1]
# X is the train data used to fit the model 
plt.figure()
plt.title("Feature importances")
plt.bar(range(X_train.shape[1]), importances[indices],
       color="r", align="center")
plt.xticks(range(X_train.shape[1]), indices)
plt.xlim([-1, X_train.shape[1]])

虽然我得到了结果,但我不确定这一点,因为我必须对我的(连续)因变量进行编码。这是正确的方法吗?如果不是,我该怎么办?

预先感谢您的帮助

标签: pythonpandasdataframe

解决方案


您可以使用模块中的SelectKBestscikit-learn

在此处查看原始文档。

这种技术称为特征选择。


推荐阅读