RandomForestClassifier Error: Number of features must match input

RandomForestClassifier Error: Number of features must match input

我对 sklearn 比较陌生,一直在尝试使用以下代码:

from sklearn.ensemble import RandomForestClassifier
from numpy import genfromtxt, savetxt

def main():
    #create the training & test sets, skipping the header row with [1:]
    dataset = genfromtxt(open('mypath\data1.csv','r'), delimiter=',', dtype='f8')[1:]    
    target = [x[0] for x in dataset]
    train = [x[1:] for x in dataset]
    test = genfromtxt(open('mypath\data1.csv','r'), delimiter=',', dtype='f8')[1:]

    #create and train the random forest
    #multi-core CPUs can use: rf = RandomForestClassifier(n_estimators=100, n_jobs=2)
    rf = RandomForestClassifier(n_estimators=100)
    rf.fit(train, target)

    savetxt(myoutput\data1_output.csv', rf.predict(test), delimiter=',', fmt='%f')

if __name__=="__main__":
    main()

此代码 运行 是包含三列的 .csv 文件上的随机森林分类器,第一列包含标签,而另外两列包含特征。当 运行 运行此程序时,出现以下错误:

ValueError: Number of features of the model must  match the input. Model n_features is 2 and  input n_features is 3

我最初的假设是有一个名为 n_features 的组件需要根据我的用例进行调整。然而,它似乎比这更复杂。谁能解释我是否以及如何使用此代码成功获得上述类型的 .csv 运行?

我确实看到了 this post,这表明问题在于代码将我的标签作为一项功能包含在内。但是,我真的不明白针对该问题的解决方案是如何解决这个问题的,因此非常感谢您提供额外的解释。

您的 csv 文件的形状是 (n_examples, 3)。您在调用时将此数组拆分为两个列表,其中包含响应变量和输入变量:

target = [x[0] for x in dataset]
train = [x[1:] for x in dataset]

因此,target 是形状 (n_examples, 1)train 是形状 (n_examples, 2)。接下来,您读取同一个 csv 文件进行测试(我不知道您为什么要使用训练数据进行测试,或者为什么此时需要再次读取该文件)。无论如何,这意味着 test 是形状 (n_examples, 3).

predict 获取输入并使用通过调用 fit 学习的模型参数生成响应。因此 predict 期望收到形状为 (2,) 的输入变量列表或形状为 (n_examples, 2) 的数组。您现在应该看到不匹配发生在哪里。

要修复,请致电 rf.predict(test[1:, 1:])。这个切片从第 1 行开始,从第 1 列开始,跳过第一行,假设它包含 header 信息(你应该检查 header 确实被读入)并跳过第一列每行跳过每个示例的响应变量。

当然,由于测试是从与训练数据相同的文件中读取的,因此这相当于 rf.predict(train)