python - python 中的机器学习 scikit learn 问题

标签 python python-3.x machine-learning scikit-learn

我正在尝试重现看到的教程 here .

在我将 .fit 方法添加到我的训练集之前,一切都很完美。

这是我的代码示例:

# TRAINING PART

train_dir = 'pdf/learning_set'
dictionary = make_dic(train_dir)

train_labels = np.zeros(20)
train_labels[17:20] = 1
train_matrix = extract_features(train_dir)
model1 = MultinomialNB()
model1.fit(train_matrix, train_labels)


# TESTING PART

test_dir = 'pdf/testing_set'
test_matrix = extract_features(test_dir)
test_labels = np.zeros(8)
test_labels[4:7] = 1
result1 = model1.predict(test_matrix)
print(confusion_matrix(test_labels, result1))

这是我的回溯:

Traceback (most recent call last):
File "ML.py", line 65, in <module>
model1.fit(train_matrix, train_labels)
File "/usr/local/lib/python3.6/site-packages/sklearn/naive_bayes.py", 
line 579, in fit
X, y = check_X_y(X, y, 'csr')
File "/usr/local/lib/python3.6/site-
packages/sklearn/utils/validation.py", line 552, in check_X_y
check_consistent_length(X, y)
File "/usr/local/lib/python3.6/site-
packages/sklearn/utils/validation.py", line 173, in 
check_consistent_length
" samples: %r" % [int(l) for l in lengths])
ValueError: Found input variables with inconsistent numbers of 
samples: [23, 20]

我想知道如何解决这个问题? 我正在使用 Ubuntu 16.04 和 python 3.6。

最佳答案

ValueError:发现输入变量的数量不一致 样本:[23, 20]

这意味着您有 23 个训练向量(train_matrix 有 23 行) 但只有 20 个训练标签(train_labels 是一个包含 20 个值的数组)

更改train_labels = np.zeros(20)train_labels = np.zeros(23) 它应该可以工作。

关于python - python 中的机器学习 scikit learn 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46786036/

相关文章:

python - 长行自动展开 Canvas

python - 从字符串中解析格式奇怪的时间表达式

python - 求解线性方程组。使用 numpy 的三个变量

android - 无法在 Kivy 中为动画选择 id

python - 卡方分析 - 预期频率在 (0,) 处有一个零元素。错误

python - Gunicorn/flask API 暴露 sklearn 模型不工作

python - 以编程方式启用或禁用@auth_basic()

python - 如何使用 keras 在 CNN 中将高级功能与低级功能连接起来?

python - 最近质心的决策边界

python - Python 2.7 中的旧式和新式类