【问题标题】:Not able to train a Linear SVM machine无法训练线性 SVM 机器
【发布时间】:2015-08-27 22:25:25
【问题描述】:

我正在为我的图像处理项目构建一个 SVM 线性机器,在该项目中我提取正样本和负样本的特征并将其保存到目录中。然后我正在使用这些功能训练 SVM,但我遇到了一个我无法调试的错误。 下面是我的 train-classifier.py 文件来训练分类器 -

from skimage.feature import local_binary_pattern
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.externals import joblib
import argparse as ap
import glob
import os
from config import *

if __name__ == "__main__":
    # Parse the command line arguments
    parser = ap.ArgumentParser()
    parser.add_argument('-p', "--posfeat", help="Path to the positive features directory", required=True)
    parser.add_argument('-n', "--negfeat", help="Path to the negative features directory", required=True)
    parser.add_argument('-c', "--classifier", help="Classifier to be used", default="LIN_SVM")
    args = vars(parser.parse_args())

    pos_feat_path =  args["posfeat"]
    neg_feat_path = args["negfeat"]

    # Classifiers supported
    clf_type = args['classifier']

    fds = []
    labels = []
    # Load the positive features
    for feat_path in glob.glob(os.path.join(pos_feat_path,"*.feat")):
        fd = joblib.load(feat_path)
        fds.append(fd)
        labels.append(1)

    # Load the negative features
    for feat_path in glob.glob(os.path.join(neg_feat_path,"*.feat")):
        fd = joblib.load(feat_path)
        fds.append(fd)
        labels.append(0)

    if clf_type is "LIN_SVM":
        clf = LinearSVC()
        print "Training a Linear SVM Classifier"
        clf.fit(fds, labels)
        # If feature directories don't exist, create them
        if not os.path.isdir(os.path.split(model_path)[0]):
            os.makedirs(os.path.split(model_path)[0])
        joblib.dump(clf, model_path)
        print "Classifier saved to {}".format(model_path)

我在 clf.fit(fds, labels) 行中遇到错误,下面是它所说的 -

Calculating the descriptors for the positive samples and saving them
Positive features saved in ../data/features/pos
Calculating the descriptors for the negative samples and saving them
Negative features saved in ../data/features/neg
Completed calculating features from training images
Training a Linear SVM Classifier
Traceback (most recent call last):
  File "../object-detector/train-classifier.py", line 42, in <module>
    clf.fit(fds, labels)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/svm/classes.py", line 200, in fit
    dtype=np.float64, order="C")
  File "/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py", line 444, in check_X_y
    ensure_min_features)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py", line 344, in check_array
    array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: setting an array element with a sequence.
Traceback (most recent call last):
  File "../object-detector/test-classifier.py", line 68, in <module>
    fd = hog(im_window, orientations, pixels_per_cell, cells_per_block, visualize, normalize)
  File "/usr/lib/python2.7/dist-packages/skimage/feature/_hog.py", line 63, in hog
    raise ValueError("Currently only supports grey-level images")
ValueError: Currently only supports grey-level images

【问题讨论】:

    标签: python opencv image-processing machine-learning


    【解决方案1】:

    我认为代码来自https://github.com/bikz05/object-detector。您需要确保训练样本(pos 和 neg)具有相同的大小(widthxheight)并且是灰色图像。您的测试图像也应该是灰色的。

    我为此使用了 imagemagick 的转换命令:

    转换 sample.png -resize 100x40 -colorspace gray sample.png

    更新(使用python转为灰度图并调整大小):

    import cv2
    
    img = cv2.imread('color_image.jpg',0)
    im = cv2.resize(img, (100,40), interpolation=cv2.INTER_CUBIC)
    cv2.imwrite("gray_image.jpg", im)
    

    【讨论】:

    • 如何在 Python 中转换为灰度?
    • 你可以使用:img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    【解决方案2】:

    您可以使用 OpenCV 的 SVM 类来代替 scikit 的。它易于使用。

    import cv2
    
    # prepare your test and train datasets
    
    svm = cv2.SVM()
    svm.train(some_train_data, responses, params)
    
    exp = svm.predict(some_test_data) 
    

    更多信息,请查看OpenCV docs

    【讨论】:

      猜你喜欢
      • 2014-12-15
      • 2013-04-14
      • 2013-05-11
      • 2012-11-03
      • 2021-05-17
      • 2015-05-04
      • 2015-07-25
      • 2017-03-14
      • 2015-04-18
      相关资源
      最近更新 更多