python - Scikit-learn 随机森林拟合方法中的值误差

标签 python machine-learning scikit-learn random-forest

我正在尝试使用 python 和 scikit-learn 训练(拟合)随机森林分类器,以存储作为特征向量的一组数据。我可以读取数据,但由于值错误而无法运行分类器的训练。我使用的源代码如下:

from sklearn.ensemble import RandomForestClassifier
from numpy import genfromtxt

 my_training_data = genfromtxt('csv-data.txt', delimiter=',')

 X_train = my_training_data[:,0]
 Y_train = my_training_data[:,1:my_training_data.shape[1]]

 clf = RandomForestClassifier(n_estimators=50)
 clf = clf.fit(X_train.tolist(), Y_train.tolist())

返回给我的错误如下:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/sklearn/ensemble/forest.py",  line 260, in fit
n_samples, self.n_features_ = X.shape
ValueError: need more than 1 value to unpack

csv-data.txt 是一个逗号分隔值文件,包含 3996 个用于训练分类器的向量。我用的是f 标记向量的第一个维度,其余为浮点值。这些是分类器中使用的特征向量的维度。

我是否错过了一些转换?

最佳答案

训练示例按行存储在“csv-data.txt”中,每行的第一个数字包含类标签。因此你应该:

X_train = my_training_data[:,1:]
Y_train = my_training_data[:,0]

请注意,在X_train中的第二个索引中,您可以省略结束索引,索引将自动运行到末尾(当然,为了清楚起见,您可以明确表示,但这只是仅供引用。

此外,在调用 fit() 时无需调用 tolist(),因为这些已经是 numpy ndarray,如果参数是列表,则 fit() 函数会将它们转换回 numpy ndarray

clf.fit(X_train.tolist(), Y_train.tolist())

关于python - Scikit-learn 随机森林拟合方法中的值误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263685/

相关文章:

python-2.7 - 使用 scikit-learn 用户定义的 SVM 内核

python - 在 TensorFlow 中关闭服务器

python - 决策树——Python最有影响力的参数

python - GridSearchCV 评分和 grid_scores_

python - 在 python 3 中使用带逗号的打印

python - 如果在 xpath (lxml) 中找不到节点/标签,如何返回字符串或匹配空

python - Flask 路由模板

python - Matlab Engine Python - OSx Anaconda Segfault 或 iPython 的 DYLD_LIBRARY_PATH 错误

machine-learning - multilayer_perceptron : ConvergenceWarning: Stochastic Optimizer: Maximum iterations reached and the optimization hasn't converged yet. 警告?

python - 将 CountVectorizer 中的稀疏矩阵添加到数据框中,并提供分类器的免费信息 - 保持稀疏格式