Python scikit svm"ValueError:X每个样本有62个特征;期望337"

Lor*_*ole 4 python machine-learning svm scikit-learn

使用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)
Run Code Online (Sandbox Code Playgroud)

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'}
Run Code Online (Sandbox Code Playgroud)

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

提供的testing_labels表示为:

[1,2,3,3,1,2,3, ... ]
Run Code Online (Sandbox Code Playgroud)

当我尝试使用LinearSVC来预测我被告知时:

ValueError: X has 27 features per sample; expecting 46
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?显然,这是我适应和转换数据的方式.

Far*_*eer 7

问题是你DictVectorizer为火车和测试创造和装配不同.

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