尝试使用 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/