【发布时间】:2011-05-12 00:30:35
【问题描述】:
我急需一个在 python 中使用 LibSVM 的分类任务示例。我不知道 Input 应该是什么样子,哪个函数负责训练,哪个函数负责测试 谢谢
【问题讨论】:
标签: python machine-learning svm libsvm
我急需一个在 python 中使用 LibSVM 的分类任务示例。我不知道 Input 应该是什么样子,哪个函数负责训练,哪个函数负责测试 谢谢
【问题讨论】:
标签: python machine-learning svm libsvm
这是我混搭的一个虚拟示例:
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)
【讨论】:
SVM 通过 SciKit-learn:
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]
【讨论】:
这个例子演示了一类SVM分类器;它尽可能简单,同时仍显示完整的 LIBSVM 工作流程。
第 1 步:导入 NumPy 和 LIBSVM
import numpy as NP
from svm import *
第 2 步: 生成合成数据:对于这个例子,给定边界内的 500 个点(注意:不少真实数据集在 LIBSVM 上提供了 website)
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 类:位于或内任意圆圈
II 类:所有点在决策边界(圆)
SVM 模型构建从这里开始;在此之前的所有步骤都只是准备一些合成数据。
第五步:通过调用svm_problem构造问题描述,传入决策边界函数和数据,然后将此结果绑定到一个变量。
px = svm_problem(rx, Data)
第 6 步:为非线性映射选择一个核函数
对于这个例子,我选择 RBF(径向基函数)作为我的核函数
pm = svm_parameter(kernel_type=RBF)
第 7 步: 训练分类器, 通过调用svm_model,传入问题描述 (px) & kernel (pm)
v = svm_model(px, pm)
第 8 步:最后,通过对已训练模型对象 ('v') 调用 predict 来测试已训练分类器
v.predict([3, 1])
# returns the class label (either '1' or '0')
对于上面的例子,我使用了LIBSVM的3.0版本(当时的稳定版本这个答案 em> 已发布)。
最后,关于您选择内核函数的部分问题,支持向量机不是特定于一个特定的核函数——例如,我可以选择不同的核(高斯、多项式等)。
LIBSVM 包含所有最常用的内核函数——这是一个很大的帮助,因为您可以看到所有可能的替代方案并选择一个用于您的模型,只需调用 svm_parameter 并传入 kernel_type 的值(所选内核的三字母缩写)。
最后,您选择用于训练的核函数必须与用于测试数据的核函数相匹配。
【讨论】:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python2.7/svm.py", line 83, in __init__ tmp_xi, tmp_idx = gen_svm_nodearray(xi,isKernel=isKernel) File "/usr/lib/pymodules/python2.7/svm.py", line 51, in gen_svm_nodearray raise TypeError('xi should be a dictionary, list or tuple') TypeError: xi should be a dictionary, list or tuple
TypeError: __init__() got an unexpected keyword argument 'kernel_type'。
添加到@shinNoNoir:
param.kernel_type 代表你要使用的核函数的类型, 0:线性 1:多项式 2:RBF 3:乙状结肠
还要记住,svm_problem(y,x):这里 y 是类标签,x 是类实例,x 和 y 只能是列表、元组和字典。(没有 numpy 数组)
【讨论】:
此处列出的代码示例不适用于 LibSVM 3.1,因此我或多或少地移植了 the example by 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])
【讨论】:
【讨论】:
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])
【讨论】:
from svmutil import * 代替。请参阅下面@ShinNoNoir 的回答。