分类变量随机森林分类器的训练/测试格式

2024-09-30 22:14:26 发布

您现在位置:Python中文网/ 问答频道 /正文

更新:如何为scikit randomforestclassifier为多个类别设置训练/测试df?我怎么预测?在

我的训练数据集有一个包含4个类的分类结果列,我想预测这四个类中哪一个最适合我的测试数据。对于其他问题,我尝试使用pandas get_dummies将四个新列编码到原始df中,而不是原始的结果列,但是不确定如何向分类器表明这四个列是类别,所以我使用y = df_raw['Outcomes'].values。在

然后,我将训练集拆分为80/20并调用fit(),其中x\u train,x\u valid和y\u train,y\u valid:

def split_vals(a,n): return a[:n].copy(), a[n:].copy() 
n_valid = 10000 
n_trn = len(df_raw_dumtrain)-n_valid
raw_train, raw_valid = split_vals(df_raw_dumtrain, n_trn)
X_train, X_valid = split_vals(df_raw_dumtrain, n_trn)
y_train, y_valid = split_vals(df_raw_dumtrain, n_trn)

random_forest = RandomForestClassifier(n_estimators=10)
random_forest.fit(X_train, y_train)
Y_prediction = random_forest.predict(X_train)

我尝试运行fit()作为:

^{pr2}$

但我得到一个错误:

ValueError: Number of features of the model must match the input. Model n_features is 27 and input n_features is 28

我应该如何配置我的测试集?在


Tags: ofdfrawtrainrandom类别fitsplit
1条回答
网友
1楼 · 发布于 2024-09-30 22:14:26

您必须从测试数据中删除目标变量,然后将dataframe的剩余列作为预测函数的输入。你就能解决功能不匹配的问题。在

试试这个!在

random_forest.predict(df_test.drop('Outcomes',axis=1))

注意:您不必为使用随机林或任何基于决策树的模型而创建目标变量的虚拟变量。在

相关问题 更多 >