Python scikit svm "ValueError: X has 62 features per sample; expecting 337"

标签 python machine-learning scikit-learn svm

尝试使用 Python 的 scikit SVM 线性支持向量分类,我在尝试进行预测时遇到错误:

ten_percent = len(raw_routes_data) / 10

# Training
training_label = all_labels[ten_percent:]
training_raw_data = raw_routes_data[ten_percent:]
training_data = DictVectorizer().fit_transform(training_raw_data).toarray()


learner = svm.LinearSVC()
learner.fit(training_data, training_label)

# Predicting
testing_label = all_labels[:ten_percent]
testing_raw_data = raw_routes_data[:ten_percent]
testing_data = DictVectorizer().fit_transform(testing_raw_data).toarray()

testing_predictions = learner.predict(testing_data)


m = metrics.classification_report(testing_label, testing_predictions)

raw_data 表示为 Python 字典,其中包含各种旅行选项的到达时间类别和天气数据类别:

{'72_bus': '6.0 to 11.0', 'uber_eta': '2.0 to 3.5', 'tweet_delay': '0', 'c_train': '1.0 to 4.0', 'weather': 'Overcast', '52_bus': '16.0 to 21.0', 'uber_surging': '1.0 to 1.15', 'd_train': '17.6666666667 to 21.8333333333', 'feels_like': '27.6666666667 to 32.5'}

当我训练和拟合训练数据时,我对 90% 的数据使用 Dictionary Vectorizer 并将其转换为数组。

提供的 testing_labels 表示为:

[1,2,3,3,1,2,3, ... ]

当我尝试使用 LinearSVC 预测时,我得到通知:

ValueError: X has 27 features per sample; expecting 46

我在这里错过了什么?显然这是我拟合和转换数据的方式。

最佳答案

问题是您为训练和测试创建和安装了不同的 DictVectorizer

您应该只使用训练数据创建和拟合一个DictVectorizer,并在您的测试数据上使用此对象的transform 方法来创建测试数据的特征表示。

关于Python scikit svm "ValueError: X has 62 features per sample; expecting 337",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35233156/

相关文章:

python - 修改生成的查询以运行 LIKE 子句 - 红色查询生成器

python - 在Python中使用for循环读取文件

machine-learning - 在 Tensorflow 中将数据分成批处理进行分类

python - 使用部分拟合的 sklearn 投票合奏

machine-learning - 在实时系统中使用 sklearn DictVectorizer

scikit-learn - 将 sklearn TfidfVectorizer 与已经标记化的输入一起使用?

python - 读取当前正在写入的 gzip 文件

python - 如何使用 python 获取两个日期时间(PDT 格式)之间的秒数差异?

machine-learning - 我的说话人识别神经网络运行不佳

artificial-intelligence - 向用户组推荐项目的最有效算法是什么?