【发布时间】:2019-07-21 12:30:11
【问题描述】:
我从我的火车数据集中的图像中提取了一些特征,然后我应用了这些特征并将数据拆分为火车并使用train_test_split 进行测试:
Train data : (60, 772)
Test data : (20, 772)
Train labels: (60,)
Test labels : (20,)
接下来我要做的是将 SVM 分类器应用于测试数据集中的图像并查看结果。
# create the model - SVM
#clf = svm.SVC(kernel='linear', C=40)
clf = svm.SVC(kernel='rbf', C=10000.0, gamma=0.0001)
# fit the training data to the model
clf.fit(trainDataGlobal, trainLabelsGlobal)
# path to test data
test_path = "dataset/test"
# loop through the test images
for index,file in enumerate(glob.glob(test_path + "/*.jpg")):
# read the image
image = cv2.imread(file)
# resize the image
image = cv2.resize(image, fixed_size)
# predict label of test image
prediction = clf.predict(testDataGlobal)
prediction = prediction[index]
#print("Accuracy: {}%".format(clf.score(testDataGlobal, testLabelsGlobal) * 100 ))
# show predicted label on image
cv2.putText(image, train_labels[prediction], (20,30), cv2.FONT_HERSHEY_TRIPLEX, .7 , (0,255,255), 2)
# display the output image
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.show()
我没有得到很好的准确度,尽管我可以看到它说准确率为 60%。然而,大多数图像都被错误地标记了。我在prediction 中传递了错误的参数吗?
我可以做些什么来改善这一点?
编辑:我用下面的代码尝试了你所说的,但我收到一个错误,说我应该重塑我的feature_vector。所以我这样做了,然后我得到以下错误。
(作为参考:feature_extraction_method(image).shape 是 (772,)。)
for filename in test_images:
# read the image and resize it to a fixed-size
img = cv2.imread(filename)
img = cv2.resize(img, fixed_size)
feature_vector = feature_extraction_method(img)
prediction = clf.predict(feature_vector.reshape(-1, 1))
cv2.putText(img, prediction, (20, 30), cv2.FONT_HERSHEY_TRIPLEX, .7 , (0, 255, 255), 2)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-71-2b8ff4146d8e> in <module>()
19
20 feature_vector = feature_extraction_method(img)
---> 21 prediction = clf.predict(feature_vector.reshape(-1, 1))
22 cv2.putText(img, prediction, (20, 30), cv2.FONT_HERSHEY_TRIPLEX, .7 , (0, 255, 255), 2)
23 plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
/anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py in predict(self, X)
546 Class labels for samples in X.
547 """
--> 548 y = super(BaseSVC, self).predict(X)
549 return self.classes_.take(np.asarray(y, dtype=np.intp))
550
/anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py in predict(self, X)
306 y_pred : array, shape (n_samples,)
307 """
--> 308 X = self._validate_for_predict(X)
309 predict = self._sparse_predict if self._sparse else self._dense_predict
310 return predict(X)
/anaconda3/lib/python3.6/site-packages/sklearn/svm/base.py in _validate_for_predict(self, X)
457 raise ValueError("X.shape[1] = %d should be equal to %d, "
458 "the number of features at training time" %
--> 459 (n_features, self.shape_fit_[1]))
460 return X
461
ValueError: X.shape[1] = 1 should be equal to 772, the number of features at training time
【问题讨论】:
标签: python image-processing scikit-learn svm