svm理论太难理解了,先上个sklearn中的SVM代码提升点信心吧,理论后续补上。
import numpy as np
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
def sklearn_svm_test():
iris = datasets.load_iris()#加载sklearn自带的鸢尾花数据。一共150条数据,分三类,每类50条数据,这三类用0,1,2表示,分别表示:setosa, versicolor, virginica
#第一条数据特征分别表示:花萼长度, 花萼宽度,花瓣长度, 花瓣宽度.
X = iris["data"][:, (2,3)]#取"data"第行的第3和第4列,即取的花瓣长度和花瓣宽度。
y = (iris["target"] == 2).astype( np.float64 )
#"target"中label为2的值转成float64类型(原来是整形)。
#另外注意是把满足条件的位置置为1.0,其它位置为0.0
svm_clf = Pipeline(( ("scaler", StandardScaler()),
("linear_svc", LinearSVC(C=1, loss="hinge")) ,))
#X,y都是ndarray类型。
#X的数据长这样:
# [[ 1.4 0.2]
# [ 1.4 0.2]
# [ 1.3 0.2]
# [ 1.5 0.2]
# [ 1.4 0.2]
# [ 1.7 0.4]
# [ 1.4 0.3]
# [ 1.5 0.2]
# [ 1.4 0.2]
# [ 1.5 0.1]
# […… ]]
#y的数据长这样:
# [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
# 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1.
# 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
# 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
# 1. 1. 1. 1. 1. 1.]
svm_clf.fit( X, y )
res = svm_clf.predict( [[1.3, 2.6]] )
print(res)
if __name__ == '__main__':
#使用sklearn中的SVM算法
sklearn_svm_test()
所以,学到到现,发现要用机器学习的算法是很简单的,直接调用sklearn中相关的接口就可以了,最多就换下参数看看不同算法的效果,难的是去理解其背后的理论基础,以及正负样本的获取和特征的选择。