SVM既可以用来分类,就是SVC;又可以用来预测,或者成为回归,就是SVR。sklearn中的svm模块中也集成了SVR类。
简单的使用sklean中的SVC(support vectors classification)例子。
from sklearn import svm X = [[0, 0], [1, 1], [1, 0]] # training samples y = [0, 1, 1] # training target clf = svm.SVC() # class clf.fit(X, y) # training the svc model result = clf.predict([2, 2]) # predict the target of testing samples print result # target print clf.support_vectors_ #support vectors print clf.support_ # indeices of support vectors print clf.n_support_ # number of support vectors for each class
算法就是一个类,其中包含fit(), predict()等等许多方法,我们只要输入训练样本和标记,以及模型的一些可能的参数,自然就直接出分类的结果。
SVR使用例子。
X = [[0, 0], [1, 1]] y = [0.5, 1.5] clf = svm.SVR() clf.fit(X, y) result = clf.predict([2, 2]) print result
关于SVC的一些用法,可以参考下面的链接:
http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC
SVC中也可以实现多类分类问题,而且默认使用的是1 vs. 1的投票机制,这种机制的优缺点,需要建立的分类器很多很多。。。
SVC也考虑到了累不平衡问题,处理方式在fit方法下面。如下:
fit(X, y, sample_weight=None)
Fit the SVM model according to the given training data.
Parameters:
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training vectors, where n_samples is the number of samples and n_features is the number of features.
y : array-like, shape (n_samples,)
Target values (class labels in classification, real numbers in regression)
sample_weight : array-like, shape (n_samples,)
Per-sample weights. Rescale C per sample. Higher weights force the classifier to put more emphasis on these points.
Returns:
self : object
Returns self.
后面的sample_weight和一般的代价敏感相似,只不过这里是每个样本有一个权重。在不平衡学习中,这里增加误分类惩罚项的技术是属于cost sensitive learning 的范畴,其中还有许多更加有效的方式来处理类不平衡问题。
关于SVR的详细说明文档见下面的链接:
http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html#sklearn.svm.SVR
参考链接:
http://www.csie.ntu.edu.tw/~cjlin/libsvm/
http://scikit-learn.org/stable/modules/svm.html
http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf