我需要在 C++ 构建目标系统中部署 SVM。因此,我想使用带有 python/numpy 的 dlib 训练 SVM,将其序列化并在目标系统中进行评估。
dlib 的 python 文档对我来说相当晦涩,所以任何人都可以帮我解决这个最小的例子吗?
import dlib
# My data in numpy
feature_column_1 = np.array([-1, -2, -3, 1, 2, 3])
feature_column_2 = np.array([1, 2, 3, -1, -2, -3])
labels = np.array([True, True, True, False, False, False])
# Features
feature_vectors = dlib.vectors()
for feature_column in [feature_column_1, feature_column_2]:
feature_vectors.append(dlib.vector(feature_column.tolist()))
# Labels
labels_array = dlib.array(labels.tolist())
# Train
svm = dlib.svm_c_trainer_linear()
svm.train(feature_vectors, labels_array)
# Test
y_probibilities = svm.predict(labels_array_new)
我在训练中遇到以下错误:
---> 18 svm.train(vectors, array)
ValueError: Invalid inputs
最佳答案
我刚刚为 dlib 添加了一个官方示例。我很惊讶地发现它不包括在内。可在此处获得:https://github.com/davisking/dlib/blob/master/python_examples/svm_binary_classifier.py .以下是相关详细信息:
import dlib
import pickle
x = dlib.vectors()
y = dlib.array()
# Make a training dataset. Here we have just two training examples. Normally
# you would use a much larger training dataset, but for the purpose of example
# this is plenty. For binary classification, the y labels should all be either +1 or -1.
x.append(dlib.vector([1, 2, 3, -1, -2, -3]))
y.append(+1)
x.append(dlib.vector([-1, -2, -3, 1, 2, 3]))
y.append(-1)
# Now make a training object. This object is responsible for turning a
# training dataset into a prediction model. This one here is a SVM trainer
# that uses a linear kernel. If you wanted to use a RBF kernel or histogram
# intersection kernel you could change it to one of these lines:
# svm = dlib.svm_c_trainer_histogram_intersection()
# svm = dlib.svm_c_trainer_radial_basis()
svm = dlib.svm_c_trainer_linear()
svm.be_verbose()
svm.set_c(10)
# Now train the model. The return value is the trained model capable of making predictions.
classifier = svm.train(x, y)
# Now run the model on our data and look at the results.
print("prediction for first sample: {}".format(classifier(x[0])))
print("prediction for second sample: {}".format(classifier(x[1])))
# classifier models can also be pickled in the same was as any other python object.
with open('saved_model.pickle', 'wb') as handle:
pickle.dump(classifier, handle)
但是,如果您想使用 C++,您应该只使用 C++。 Dlib 主要是一个 C++ 库而不是 python 库。 dlib 的全部意义在于为想要进行机器学习的人提供一个很好的 C++ API。所以你最好只使用 C++ 进行训练。 dlib 和完整的 C++ API 文档附带了 99 个完整的 C++ 示例。例如,这是一个相关的例子 http://dlib.net/svm_c_ex.cpp.html .
我真的应该强调 dlib 的 C++ API 比 python API 灵活得多。真的,dlib 的目的是让机器学习在 C++ 中变得容易,dlib 的 python API 是事后才想到的。事实上,dlib 有很多特性是使用诸如 C++ 模板之类的东西表达的,这些特性在 Python 中可能没有关联(例如,因为 python 没有像 C++ 模板那样的东西),所以这些特性不会暴露给 python。所以说真的,如果你想使用 C++,那就使用 C++。 如果您知道如何编写 C++,就没有理由使用 Python API。
关于python - 使用 Python/Numpy 的 dlib SVM 的最小示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46807403/