我急需一个在 python 中使用 LibSVM 的分类任务示例。我不知道输入应该是什么样子,哪个函数负责训练,哪个函数负责测试 谢谢
8 回答
此处列出的代码示例不适用于 LibSVM 3.1,因此我或多或少地通过 mossplix 移植了该示例:
from svmutil import *
svm_model.predict = lambda self, x: svm_predict([0], [x], self)[0][0]
prob = svm_problem([1,-1], [[1,0,1], [-1,0,-1]])
param = svm_parameter()
param.kernel_type = LINEAR
param.C = 10
m=svm_train(prob, param)
m.predict([1,1,1])
这个例子演示了一类SVM 分类器;它尽可能简单,同时仍然显示完整的 LIBSVM 工作流程。
第 1 步:导入 NumPy 和 LIBSVM
import numpy as NP
from svm import *
步骤 2:生成合成数据:对于这个例子,给定边界内的 500 个点(注意:LIBSVM网站上提供了相当多的真实数据集)
Data = NP.random.randint(-5, 5, 1000).reshape(500, 2)
第 3 步:现在,为一类分类器选择一些非线性决策边界:
rx = [ (x**2 + y**2) < 9 and 1 or 0 for (x, y) in Data ]
第 4 步:接下来,根据此决策边界任意划分数据:
I类:位于任意圆上或之内的那些
第二类:决策边界外的所有点
SVM 模型构建从这里开始;在此之前的所有步骤都只是准备一些合成数据。
步骤 5:通过调用svm_problem构造问题描述,传入决策边界函数和数据,然后将此结果绑定到变量。
px = svm_problem(rx, Data)
第 6 步:为非线性映射选择核函数
对于这个例子,我选择RBF(径向基函数)作为我的核函数
pm = svm_parameter(kernel_type=RBF)
第 7 步:通过调用svm_model训练分类器,传入问题描述(px) 和内核(pm)
v = svm_model(px, pm)
第 8 步:最后,通过在训练好的模型对象 ('v') 上调用predict来测试训练好的分类器
v.predict([3, 1])
# returns the class label (either '1' or '0')
对于上面的示例,我使用了LIBSVM 3.0版(发布此答案时的当前稳定版本)。
最后,w/r/t 关于内核函数选择的部分问题,支持向量机并不特定于特定的内核函数——例如,我可以选择不同的内核(高斯、多项式等)。
LIBSVM 包含所有最常用的内核函数——这是一个很大的帮助,因为您可以看到所有合理的替代方案并选择一个用于您的模型,只需调用svm_parameter并传入kernel_type的值(a所选内核的三字母缩写)。
最后,您选择用于训练的核函数必须与用于测试数据的核函数相匹配。
LIBSVM 从包含两个列表的元组中读取数据。第一个列表包含类,第二个列表包含输入数据。创建具有两个可能的类的简单数据集,您还需要通过创建 svm_parameter 来指定要使用的内核。
>> from libsvm import *
>> prob = svm_problem([1,-1],[[1,0,1],[-1,0,-1]])
>> param = svm_parameter(kernel_type = LINEAR, C = 10)
## training the model
>> m = svm_model(prob, param)
#testing the model
>> m.predict([1, 1, 1])
添加到@shinNoNoir :
param.kernel_type 表示要使用的核函数类型,0:线性 1:多项式 2:RBF 3:Sigmoid
还要记住,svm_problem(y,x):这里 y 是类标签,x 是类实例,x 和 y 只能是列表、元组和字典。(没有 numpy 数组)
这是我混搭的一个虚拟示例:
import numpy
import matplotlib.pyplot as plt
from random import seed
from random import randrange
import svmutil as svm
seed(1)
# Creating Data (Dense)
train = list([randrange(-10, 11), randrange(-10, 11)] for i in range(10))
labels = [-1, -1, -1, 1, 1, -1, 1, 1, 1, 1]
options = '-t 0' # linear model
# Training Model
model = svm.svm_train(labels, train, options)
# Line Parameters
w = numpy.matmul(numpy.array(train)[numpy.array(model.get_sv_indices()) - 1].T, model.get_sv_coef())
b = -model.rho.contents.value
if model.get_labels()[1] == -1: # No idea here but it should be done :|
w = -w
b = -b
print(w)
print(b)
# Plotting
plt.figure(figsize=(6, 6))
for i in model.get_sv_indices():
plt.scatter(train[i - 1][0], train[i - 1][1], color='red', s=80)
train = numpy.array(train).T
plt.scatter(train[0], train[1], c=labels)
plt.plot([-5, 5], [-(-5 * w[0] + b) / w[1], -(5 * w[0] + b) / w[1]])
plt.xlim([-13, 13])
plt.ylim([-13, 13])
plt.show()
param = svm_parameter('-s 0 -t 2 -d 3 -c '+str(C)+' -g '+str(G)+' -p '+str(self.epsilon)+' -n '+str(self.nu))
我不知道早期版本,但在LibSVM 3.xx中,该方法svm_parameter('options')
只需要一个参数。
在我的情况下C
,G
和p
是nu
动态值。您根据您的代码进行更改。
选项:
-s svm_type : set type of SVM (default 0)
0 -- C-SVC (multi-class classification)
1 -- nu-SVC (multi-class classification)
2 -- one-class SVM
3 -- epsilon-SVR (regression)
4 -- nu-SVR (regression)
-t kernel_type : set type of kernel function (default 2)
0 -- linear: u'*v
1 -- polynomial: (gamma*u'*v + coef0)^degree
2 -- radial basis function: exp(-gamma*|u-v|^2)
3 -- sigmoid: tanh(gamma*u'*v + coef0)
4 -- precomputed kernel (kernel values in training_set_file)
-d degree : set degree in kernel function (default 3)
-g gamma : set gamma in kernel function (default 1/num_features)
-r coef0 : set coef0 in kernel function (default 0)
-c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
-n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)
-m cachesize : set cache memory size in MB (default 100)
-e epsilon : set tolerance of termination criterion (default 0.001)
-h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)
-b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)
-wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1)
-v n: n-fold cross validation mode
-q : quiet mode (no outputs)
通过 SciKit-learn 的 SVM:
from sklearn.svm import SVC
X = [[0, 0], [1, 1]]
y = [0, 1]
model = SVC().fit(X, y)
tests = [[0.,0.], [0.49,0.49], [0.5,0.5], [2., 2.]]
print(model.predict(tests))
# prints [0 0 1 1]
在此处了解更多详细信息:http: //scikit-learn.org/stable/modules/svm.html#svm