python随机森林 交叉验证_随机森林特征导入的交叉验证数据集折叠

本文介绍了Python中随机森林模型在交叉验证过程中出现的错误,强调了在fit方法中应该使用训练数据及其对应的标签。通过示例代码展示了如何利用K Fold交叉验证选择训练数据集,并且展示如何绘制特征重要性图,以帮助理解模型中各特征的影响。
摘要由CSDN通过智能技术生成

错误的原因之一是此代码rfc.fit(train_data, test_data)。你应该把火车标签作为第二个参数,而不是测试数据。在

至于绘图,你可以尝试做一些类似下面的代码。我假设您知道在这种情况下,k-folds CV只用于选择不同的训练数据集。由于未进行预测,因此忽略测试数据:import numpy as np

import matplotlib.pyplot as plt

from sklearn.ensemble import RandomForestClassifier

from sklearn.model_selection import KFold

from sklearn.datasets import make_classification

# dummy classification dataset

X, y = make_classification(n_features=10)

# dummy feature names

feature_names = ['F{}'.format(i) for i in range(X.shape[1])]

kf = KFold(n_splits=3)

rfc = RandomForestClassifier()

count = 1

# test data is not needed for fitting

for train, _ in kf.split(X, y):

rfc.fit(X[train, :], y[train])

# sort the feature index by importance score in descending order

importances_index_desc = np.argsort(rfc.feature_importances_)[::-1]

feature_labels = [feature_names[i] for i in importances_index_desc]

# plot

plt.figure()

plt.bar(feature_labels, rfc.feature_importances_[importances_index_desc])

plt.xticks(feature_labels, rotation='vertical')

plt.ylabel('Importance')

plt.xlabel('Features')

plt.title('Fold {}'.format(count))

count = count + 1

plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值