- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个 dataset它遵循单热编码模式,我的因变量也是二进制的。我的代码的第一部分列出了整个数据集的重要变量。我使用了这篇 stackoverflow 帖子“Using scikit to determine contributions of each feature to a specific class prediction”中提到的方法。我不确定我得到什么输出。在我的案例中,特征重要性对整个模型“延迟相关 DMS 与建议”进行了排名。我将其解释为,这个变量在 0 类或 1 类中应该是重要的,但从我得到的输出来看,它在两个类中都不重要。我在上面分享的 stackoverflow 中的代码还表明,当 DV 为二进制时,0 类的输出与 1 类的输出完全相反(在符号 +/- 方面)。在我的例子中,两者的值都不同类。
这是情节的样子:-
特征重要性 - 整体模型
我的代码的第二部分显示了累积的特征重要性,但查看 [plot] 表明没有一个变量是重要的。是我的公式错了还是我的解释错了,或者两者兼而有之?
这是我的代码;
import pandas as pd
import numpy as np
import json
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import scale
from sklearn.ensemble import ExtraTreesClassifier
##get_ipython().run_line_magic('matplotlib', 'inline')
file = r'RCM_Binary.csv'
data = pd.read_csv()
print("data loaded successfully ...")
# Define features and target
X = data.iloc[:,:-1]
y = data.iloc[:,-1]
#split to training and testing
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=41)
# define classifier and fitting data
forest = ExtraTreesClassifier(random_state=1)
forest.fit(X_train, y_train)
# predict and get confusion matrix
y_pred = forest.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
#Applying 10-fold cross validation
accuracies = cross_val_score(estimator=forest, X=X_train, y=y_train, cv=10)
print("accuracy (10-fold): ", np.mean(accuracies))
# Features importances
importances = forest.feature_importances_
std = np.std([tree.feature_importances_ for tree in forest.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
feature_list = [X.columns[indices[f]] for f in range(X.shape[1])] #names of features.
ff = np.array(feature_list)
# Print the feature ranking
print("Feature ranking:")
for f in range(X.shape[1]):
print("%d. feature %d (%f) name: %s" % (f + 1, indices[f], importances[indices[f]], ff[indices[f]]))
# Plot the feature importances of the forest
plt.figure()
plt.rcParams['figure.figsize'] = [16, 6]
plt.title("Feature importances")
plt.bar(range(X.shape[1]), importances[indices],
color="r", yerr=std[indices], align="center")
plt.xticks(range(X.shape[1]), ff[indices], rotation=90)
plt.xlim([-1, X.shape[1]])
plt.show()
## The new additions to get feature importance to classes:
# To get the importance according to each class:
def class_feature_importance(X, Y, feature_importances):
N, M = X.shape
X = scale(X)
out = {}
for c in set(Y):
out[c] = dict(
zip(range(N), np.mean(X[Y==c, :], axis=0)*feature_importances)
)
return out
result = class_feature_importance(X, y, importances)
print (json.dumps(result,indent=4))
# Plot the feature importances of the forest
titles = ["Did not Divert", "Diverted"]
for t, i in zip(titles, range(len(result))):
plt.figure()
plt.rcParams['figure.figsize'] = [16, 6]
plt.title(t)
plt.bar(range(len(result[i])), result[i].values(),
color="r", align="center")
plt.xticks(range(len(result[i])), ff[list(result[i].keys())], rotation=90)
plt.xlim([-1, len(result[i])])
plt.show()
第二部分代码
# List of tuples with variable and importance
feature_importances = [(feature, round(importance, 2)) for feature, importance in zip(feature_list, importances)]
# Sort the feature importances by most important first
feature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)
# Print out the feature and importances
[print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances]
# list of x locations for plotting
x_values = list(range(len(importances)))
# Make a bar chart
plt.bar(x_values, importances, orientation = 'vertical', color = 'r', edgecolor = 'k', linewidth = 1.2)
# Tick labels for x axis
plt.xticks(x_values, feature_list, rotation='vertical')
# Axis labels and title
plt.ylabel('Importance'); plt.xlabel('Variable'); plt.title('Variable Importances');
# List of features sorted from most to least important
sorted_importances = [importance[1] for importance in feature_importances]
sorted_features = [importance[0] for importance in feature_importances]
# Cumulative importances
cumulative_importances = np.cumsum(sorted_importances)
# Make a line graph
plt.plot(x_values, cumulative_importances, 'g-')
# Draw line at 95% of importance retained
plt.hlines(y = 0.95, xmin=0, xmax=len(sorted_importances), color = 'r', linestyles = 'dashed')
# Format x ticks and labels
plt.xticks(x_values, sorted_features, rotation = 'vertical')
# Axis labels and title
plt.xlabel('Variable'); plt.ylabel('Cumulative Importance'); plt.title('Cumulative Importances');
plt.show()
# Find number of features for cumulative importance of 95%
# Add 1 because Python is zero-indexed
print('Number of features for 95% importance:', np.where(cumulative_importances > 0.95)[0][0] + 1)
最佳答案
这个问题可能已经过时了,但以防万一有人感兴趣:
您从源代码中复制的 class_feature_importance
函数使用行作为特征,使用列作为示例,而您则像大多数人一样以相反的方式进行操作。因此,每个类别的特征重要性的计算都会出错。将代码更改为
zip(range(M))
应该可以解决。
关于python - 使用 Scikit-learn 确定 RF 模型中每个类的特征重要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201913/
Unix 中 rm -rf 中的 rf 代表什么? 更一般地说,我很难记住 Unix 命令和选项,因为我不明白它们代表什么。是否有资源可以解释这些简写的含义? 最佳答案 在rm中, -r 代表递归 -
在 Makefile 中,我读到: -rm -rf(而不是 rm -rf)。 Makefile 中行开头的第一个“-”是什么意思? 最佳答案 这意味着make本身将忽略来自rm的任何错误代码。 在 m
rm是删除item,但是参数-rf的作用是什么? 每当我输入 help -rf 时,它都会打印 powershell 中可用命令的完整列表。如果您在 powershell 中输入 rm -rf 会发生
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 这个问题似乎不是关于 a specific programming problem, a software
我尝试搜索 SO,但无法找到以下命令之间的区别。如果我有一个名为 dir 的目录,下面的命令有何不同? rm -rf dir/* rm -rf dir/ rm -rf dir 另外,如果运行命令的 i
我很困惑,为什么没有交叉验证的随机森林分类模型的平均准确度得分为 0.996,而具有 5 折交叉验证的模型的平均准确度得分为 0.687。 有 275,956 个样本。 0级=217891,1级=60
我正在尝试在 DRF3 中制作一个可写的嵌套序列化器。我有一个模型音乐会,其中有一个 m2m 领域“技术人员”到我的用户模型。我已成功在其 View 中添加连接到 Concert 实例的用户列表。现在
rm -rf 只删除文件不删除文件夹 我有一个数据库,我循环遍历 file_path 并检查 file_exist 如果文件不存在。我执行 rm -rf $db_value 但有时 db_value
首先,这是windows系统,不是linux。在我的 makefile 中,我正在做 make clean rm -rf output 但是,第一次运行时,会报错 rm: cannot lstat `
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎不是关于 a specific programming problem, a softwar
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎不是关于 a specific programming problem, a softwar
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎不是关于 a specific programming problem, a softwar
我有一个非常简单的 dockerfile,用“rm -Rf”在安装后删除安装文件,但是我收到了一些错误,例如: Step 4/4 : RUN rm -Rf /INSTALLATION ---> Run
我想使用 TCL 删除目录中的所有文件。 (我在 Win 10 下使用 Xilinx Vivado 的 TCL 控制台。)我在 TCL documentation 中发现了这一点。那个 file de
git中的“-rf”是什么意思? 我用了 git rm -rf directories 但我不知道 -rf 的实际含义 最佳答案 -r - 当给出前导目录名称时允许递归删除。 -f - 覆盖最新检查。
当您将其键入控制台并运行时,此命令将完美运行。 rm -rf !(folder1|file_name|log.txt|*.sh|*.conf) 但是,当我从bash脚本运行它时,出现以下错误; ./t
已关闭。这个问题是 off-topic 。目前不接受答案。 想要改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 已关闭10 年前。 Improve th
我的问题与 here 完全相同和 here . 我还使用 simple2.py 对该程序生成的可执行文件进行沙箱处理 test1.c: #include int main(){ puts
使用随机森林算法进行回归,我在 iternet 中发现,在预测之后,它们对预测结果进行归一化,这意味着我们假设结果是 pred pred = pred = pred*(np.exp(-pred/100
我正在尝试编写一个 BASH 脚本,它将递归删除目录中的所有文件。 当我在控制台 rm -rf/home/dir/dir/* 中写入时,效果很好,但我不能使用变量来完成。 VAR="/home/dir
我是一名优秀的程序员,十分优秀!