问题描述
我正在使用scikit Learner在Roder上对我拥有的3个不同数据帧(aa,bb,cc)运行随机森林模型。 为了做到这一点,我使用for循环并为每个模型生成混淆矩阵。 问题是我想保存每个模型的预测,以便以后将其用于ROC分析。
这是循环的原始脚本:
todrop=['name','code','date','nitrogen','Hour','growth_day']
col='test'
dfs=[aa,bb,cc]
for h in dfs:
h.drop(todrop,axis=1,inplace=True)
y=h[col]
X=h.drop(col,axis=1)
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,stratify=y,random_state=42)
rfc = RandomForestClassifier()
rfc.fit(X_train,y_train)
predictions = rfc.predict(X_test)
conf_mat = confusion_matrix(y_test,predictions)
df_conf_norm = conf_mat / conf_mat.sum(axis=0)
index = ['healthy','sick']
columns = ['healthy','sick']
cm_df = pd.DataFrame(df_conf_norm,columns,index)
seaborn.heatmap(cm_df,annot=True,annot_kws={"size": 15},linewidths=.5,cmap='YlOrRd')
plt.title('Random Forest',fontsize = 20) # title with fontsize 20
plt.xlabel('True Labels',fontsize = 17) # x-axis label with fontsize 15
plt.ylabel('Prediction',fontsize = 17) # y-axis label with fontsize 15
plt.show()
print('Accuracy'+'{}'.format(accuracy_score(y_test,predictions)))
我已尝试通过以下方式保存模型:
predictions[h] = rfc.predict(X_test)
但是我得到了错误:
IndexError:仅整数,切片(
:
),省略号(...
), numpy.newaxis(None
)和整数或布尔数组是有效索引
我也尝试过使用zip,然后将其另存为名称:
names=['aa','bb','cc']
for h,n in (zip(dfs,names)):
...
predictions[n] = rfc.predict(X_test)
但出现相同的错误。
我在这里的最终目标是保存(每个模型的)那些预测,以便在最终的ROC图中创建。
解决方法
在循环的每次迭代中,您都将创建一个名为predictions
的np.array变量:
predictions = rfc.predict(X_test)
因此,如果要将每个模型保存在诸如dict之类的变量中,则需要在循环外使用不同的名称声明它:
all_predictions = dict()
然后修改第二个示例中的代码应该可以:
names=['aa','bb','cc']
for h,n in (zip(dfs,names)):
...
all_predictions[n] = rfc.predict(X_test)