[机器学习实战] SVM-支持向量机

支持向量机(Support Vector Machines, SVM)

基于SMO(序列最小优化)算法实现

一、基于最大间隔分隔数据

SVM优点
泛化错误率低,计算开销小,结果易解释。
SVM缺点
对参数调节和核函数的选择敏感,原始分类器不加修改仅适用于处理二类问题。

分隔超平面(separating hyperplane): 如果数据集是1024维,那么就需要一个1023维的超平面来对数据进行分隔,也就是分类的决策边界。
间隔(margin): 点到分隔面的距离。
支持向量(support vector): 离分割超平面最近的那些点,SVM即最大化支持向量的间隔。

二、寻找最大间隔

寻找最大间隔:最大化最小间隔的数据点,利用拉格朗日乘子法+KKT条件通过求解alpha来求W^T X+b=0。见P92

三、SMO高效优化算法

SMO算法的工作原理:
每次循环中选择两个alpha进行优化处理。一旦找到一对合适的alpha,那么就增大其中一个同时减小另一个。

合适的alpha对:

  1. 必须在间隔边界之外。
  2. 还没有进行过区间化处理或者不在边界上。
from numpy import *
import matplotlib.pyplot as pp
%matplotlib inline
# SMO算法中的辅助函数
def loadDataSet(fileName):
    dataMat = []; labelMat = []
    fr = open(fileName)
    for line in fr.readlines():
        lineArr = line.strip().split('\t')
        dataMat.append([float(lineArr[0]), float(lineArr[1])])
        labelMat.append(float(lineArr[2]))
    return dataMat,labelMat
def selectJrand(i,m): # i是第一个alpha的下标,m是所有alpha的数目
    j=i #we want to select any J not equal to i
    while (j==i):
        j = int(random.uniform(0,m))
    return j
def clipAlpha(aj,H,L):
    if aj > H:
        aj = H
    if L > aj:
        aj = L
    return aj
dataArr, labelArr = loadDataSet('data/SVM/testSet.txt')
print(labelArr)
[-1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0]
# 简化版SMO算法
def smoSimple(dataMatIn, classLabels, C, toler, maxIter): # 数据集,类别标签,常数C,容错率,最大循环次数
    dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()
    b = 0; m,n = shape(dataMatrix)
    alphas = mat(zeros((m,1)))
    iter = 0
    while (iter < maxIter):
        alphaPairsChanged = 0
        for i in range(m):
            fXi = float(multiply(alphas,labelMat).T*(dataMatrix*dataMatrix[i,:].T)) + b # 预测的类别
            Ei = fXi - float(labelMat[i])#if checks if an example violates KKT conditions 计算基于当前样本对应的alpha[i]的误差
            if ((labelMat[i]*Ei < -toler) and (alphas[i] < C)) or ((labelMat[i]*Ei > toler) and (alphas[i] > 0)):
                # 如果alpha在0~C之间,且误差大于容错范围,则对alpha进行优化
                j = selectJrand(i,m)
                fXj = float(multiply(alphas,labelMat).T*(dataMatrix*dataMatrix[j,:].T)) + b
                Ej = fXj - float(labelMat[j])
                alphaIold = alphas[i].copy(); alphaJold = alphas[j].copy(); # python会通过引用的方式传递所有列表,所以这里分配新的内存存储old
                if (labelMat[i] != labelMat[j]): #重新计算L,H保证alpha在0~C之间
                    L = max(0, alphas[j] - alphas[i])
                    H = min(C, C + alphas[j] - alphas[i])
                else:
                    L = max(0, alphas[j] + alphas[i] - C)
                    H = min(C, alphas[j] + alphas[i])
                if L==H: 
                    #print "L==H"
                    continue
                eta = 2.0 * dataMatrix[i,:]*dataMatrix[j,:].T - dataMatrix[i,:]*dataMatrix[i,:].T - dataMatrix[j,:]*dataMatrix[j,:].T
                if eta >= 0: 
                    #print "eta>=0"
                    continue
                alphas[j] -= labelMat[j]*(Ei - Ej)/eta
                alphas[j] = clipAlpha(alphas[j],H,L)
                if (abs(alphas[j] - alphaJold) < 0.00001): 
                    #print "j not moving enough"
                    continue
                alphas[i] += labelMat[j]*labelMat[i]*(alphaJold - alphas[j])#update i by the same amount as j
                                                                        #the update is in the oppostie direction
                b1 = b - Ei- labelMat[i]*(alphas[i]-alphaIold)*dataMatrix[i,:]*dataMatrix[i,:].T - labelMat[j]*(alphas[j]-alphaJold)*dataMatrix[i,:]*dataMatrix[j,:].T
                b2 = b - Ej- labelMat[i]*(alphas[i]-alphaIold)*dataMatrix[i,:]*dataMatrix[j,:].T - labelMat[j]*(alphas[j]-alphaJold)*dataMatrix[j,:]*dataMatrix[j,:].T
                if (0 < alphas[i]) and (C > alphas[i]): b = b1
                elif (0 < alphas[j]) and (C > alphas[j]): b = b2
                else: b = (b1 + b2)/2.0
                alphaPairsChanged += 1
                #print "iter: %d i:%d, pairs changed %d" % (iter,i,alphaPairsChanged)
        if (alphaPairsChanged == 0): iter += 1 # 只有当没有任何alpha发生改变时才会记为一次迭代
        else: iter = 0
        #print "iteration number: %d" % iter
    return b,alphas
def calcWs(alphas,dataArr,classLabels):
    X = mat(dataArr); labelMat = mat(classLabels).transpose()
    m,n = shape(X)
    w = zeros((n,1))
    for i in range(m):
        w += multiply(alphas[i]*labelMat[i],X[i,:].T)
    return w
b, alphas = smoSimple(dataArr, labelArr, 0.6, 0.001, 40)
ws = calcWs(alphas, dataArr, labelArr)
ws
array([[ 0.81340485],
       [-0.27295608]])
b
matrix([[-3.83163006]])
alphas[alphas>0]
matrix([[ 0.12746939,  0.24093776,  0.36840715]])
shape(alphas[alphas>0]) # 支持向量的个数
(1, 3)
x0 = []; y0 = []
x1 = []; y1 = []
x_sv = []; y_sv = []
for i in range(100):
    if alphas[i] > 0.0:
        x_sv.append(dataArr[i][0])
        y_sv.append(dataArr[i][1])
    elif labelArr[i] > 0.0:
        x0.append(dataArr[i][0])
        y0.append(dataArr[i][1])
    else:
        x1.append(dataArr[i][0])
        y1.append(dataArr[i][1])
pp.scatter(x0,y0,color='r')
pp.scatter(x1,y1,color='g')
pp.scatter(x_sv,y_sv,color='b')
X = linspace(2,6,1000)
Y = [(float(ws[0])*x + float(b))/-float(ws[1]) for x in X]
pp.plot(X, Y)
[<matplotlib.lines.Line2D at 0x1ff2892b748>]

四、利用完整Platt SMO算法加速优化

唯一的不同点在于选择alpha的方式。
Platt SMO算法是通过一个外循环选择第一个alpha值,其选择过程在两种方式之间进行交替:

  1. 在所有数据集上进行单遍扫描。
  2. 在非边界alpha中实现单遍扫描。

在选择第一个alpha值后,算法会通过一个内循环来选择第二个alpha值,优化方法是通过最大化步长的方式来获得第二个alpha值。建立一个全局的缓存用于保存误差值,并从中选择使得步长或者Ei-Ej最大的alpha值。

# 完整版Platt SMO的支持函数
# 通过一个仅包含__init__方法的对象来建立一个数据结构用以保存所有重要的值
class optStructK:
    def __init__(self,dataMatIn, classLabels, C, toler):  # Initialize the structure with the parameters
        self.X = dataMatIn
        self.labelMat = classLabels
        self.C = C
        self.tol = toler
        self.m = shape(dataMatIn)[0]
        self.alphas = mat(zeros((self.m,1)))
        self.b = 0
        self.eCache = mat(zeros((self.m,2))) #first column is valid flag
# 对于给定的alpha的值,计算E值并返回
def calcEkK(oS, k):
    fXk = float(multiply(oS.alphas,oS.labelMat).T*(oS.X*oS.X[k,:].T)) + oS.b
    Ek = fXk - float(oS.labelMat[k])
    return Ek
# 用于选择第二个alpha值
def selectJK(i, oS, Ei):         #this is the second choice -heurstic, and calcs Ej
    maxK = -1; maxDeltaE = 0; Ej = 0
    oS.eCache[i] = [1,Ei]  #set valid #choose the alpha that gives the maximum delta E
    validEcacheList = nonzero(oS.eCache[:,0].A)[0]
    if (len(validEcacheList)) > 1:
        for k in validEcacheList:   #loop through valid Ecache values and find the one that maximizes delta E
            if k == i: continue #don't calc for i, waste of time
            Ek = calcEkK(oS, k)
            deltaE = abs(Ei - Ek)
            if (deltaE > maxDeltaE):
                maxK = k; maxDeltaE = deltaE; Ej = Ek
        return maxK, Ej
    else:   #in this case (first time around) we don't have any valid eCache values
        j = selectJrand(i, oS.m)
        Ej = calcEkK(oS, j)
    return j, Ej
# 计算误差值并存入缓存当中
def updateEkK(oS, k):#after any alpha has changed update the new value in the cache
    Ek = calcEkK(oS, k)
    oS.eCache[k] = [1,Ek]
# 完整PLatt SMO算法中的优化例程
def innerLK(i, oS):
    Ei = calcEkK(oS, i)
    if ((oS.labelMat[i]*Ei < -oS.tol) and (oS.alphas[i] < oS.C)) or ((oS.labelMat[i]*Ei > oS.tol) and (oS.alphas[i] > 0)):
        j,Ej = selectJK(i, oS, Ei) #this has been changed from selectJrand
        alphaIold = oS.alphas[i].copy(); alphaJold = oS.alphas[j].copy();
        if (oS.labelMat[i] != oS.labelMat[j]):
            L = max(0, oS.alphas[j] - oS.alphas[i])
            H = min(oS.C, oS.C + oS.alphas[j] - oS.alphas[i])
        else:
            L = max(0, oS.alphas[j] + oS.alphas[i] - oS.C)
            H = min(oS.C, oS.alphas[j] + oS.alphas[i])
        if L==H: 
            #print "L==H"
            return 0
        eta = 2.0 * oS.X[i,:]*oS.X[j,:].T - oS.X[i,:]*oS.X[i,:].T - oS.X[j,:]*oS.X[j,:].T
        if eta >= 0: 
            #print "eta>=0"
            return 0
        oS.alphas[j] -= oS.labelMat[j]*(Ei - Ej)/eta
        oS.alphas[j] = clipAlpha(oS.alphas[j],H,L)
        updateEkK(oS, j) #added this for the Ecache
        if (abs(oS.alphas[j] - alphaJold) < 0.00001): 
            #print "j not moving enough"
            return 0
        oS.alphas[i] += oS.labelMat[j]*oS.labelMat[i]*(alphaJold - oS.alphas[j])#update i by the same amount as j
        updateEkK(oS, i) #added this for the Ecache                    #the update is in the oppostie direction
        b1 = oS.b - Ei- oS.labelMat[i]*(oS.alphas[i]-alphaIold)*oS.X[i,:]*oS.X[i,:].T - oS.labelMat[j]*(oS.alphas[j]-alphaJold)*oS.X[i,:]*oS.X[j,:].T
        b2 = oS.b - Ej- oS.labelMat[i]*(oS.alphas[i]-alphaIold)*oS.X[i,:]*oS.X[j,:].T - oS.labelMat[j]*(oS.alphas[j]-alphaJold)*oS.X[j,:]*oS.X[j,:].T
        if (0 < oS.alphas[i]) and (oS.C > oS.alphas[i]): oS.b = b1
        elif (0 < oS.alphas[j]) and (oS.C > oS.alphas[j]): oS.b = b2
        else: oS.b = (b1 + b2)/2.0
        return 1
    else: return 0
# 完整版Platt SMO的外循环代码
def smoPK(dataMatIn, classLabels, C, toler, maxIter):    #full Platt SMO
    oS = optStructK(mat(dataMatIn),mat(classLabels).transpose(),C,toler)
    iter = 0
    entireSet = True; alphaPairsChanged = 0
    while (iter < maxIter) and ((alphaPairsChanged > 0) or (entireSet)):
        alphaPairsChanged = 0
        if entireSet:   #go over all
            for i in range(oS.m):
                alphaPairsChanged += innerLK(i,oS)
                #print "fullSet, iter: %d i:%d, pairs changed %d" % (iter,i,alphaPairsChanged)
            iter += 1
        else:#go over non-bound (railed) alphas
            nonBoundIs = nonzero((oS.alphas.A > 0) * (oS.alphas.A < C))[0]
            for i in nonBoundIs:
                alphaPairsChanged += innerLK(i,oS)
                #print "non-bound, iter: %d i:%d, pairs changed %d" % (iter,i,alphaPairsChanged)
            iter += 1
        if entireSet: entireSet = False #toggle entire set loop
        elif (alphaPairsChanged == 0): entireSet = True
        #print "iteration number: %d" % iter
    return oS.b,oS.alphas
dataArr, labelArr = loadDataSet('data/SVM/testSet.txt')
b, alphas = smoPK(dataArr, labelArr, 0.6, 0.001, 40)
b
matrix([[-2.89901748]])
alphas[alphas>0]
matrix([[ 0.06961952,  0.0169055 ,  0.0169055 ,  0.0272699 ,  0.04522972,
          0.0272699 ,  0.0243898 ,  0.06140181,  0.06140181]])
def calcWs(alphas, dataArr, classLabels):
    X = mat(dataArr)
    labelMat = mat(classLabels).transpose()
    m, n = shape(X)
    w = zeros((n, 1))
    for i in range(m):
        w += multiply(alphas[i]*labelMat[i], X[i,:].T)
    return w
ws = calcWs(alphas, dataArr, labelArr)
ws
array([[ 0.65307162],
       [-0.17196128]])
datMat = mat(dataArr)
datMat[0]*mat(ws)+b
matrix([[-0.92555695]])
labelArr[0]
-1.0
print(datMat[1]*mat(ws)+b)
print(labelArr[1])
[[-1.36706674]]
-1.0
print(datMat[2]*mat(ws)+b)
print(labelArr[2])
[[ 2.30436336]]
1.0
b
matrix([[-2.89901748]])
x0 = []; y0 = []
x1 = []; y1 = []
x_sv = []; y_sv = []
for i in range(100):
    if alphas[i] > 0.0:
        x_sv.append(dataArr[i][0])
        y_sv.append(dataArr[i][1])
    elif labelArr[i] > 0.0:
        x0.append(dataArr[i][0])
        y0.append(dataArr[i][1])
    else:
        x1.append(dataArr[i][0])
        y1.append(dataArr[i][1])
pp.scatter(x0,y0,color='r')
pp.scatter(x1,y1,color='g')
pp.scatter(x_sv,y_sv,color='b')
X = linspace(2,6,1000)
Y = [(float(ws[0])*x + float(b))/-float(ws[1]) for x in X]
pp.plot(X, Y)
[<matplotlib.lines.Line2D at 0x1ff28eedef0>]

五、在复杂数据上应用核函数(kernel)

低维空间中的非线性问题 ---kernel--> 高维空间中的线性问题

将内积替换成核函数的方式成为kenel trick

径向基函数是一个采用向量作为自变量的函数,能够给予向量距离运算输出一个标量。

径向基函数的高斯版本:

k(x,y) = exp(-║x-y║² / 2*σ²)

σ是用户定义的用于确定到达率(reach)或者说函数值跌落到0的速度参数

径向基核函数的高斯版本可以将数据从其特征空间映射到一个无穷维的空间。

# 核转换函数
def kernelTrans(X, A, kTup): #calc the kernel or transform data to a higher dimensional space
    m,n = shape(X)
    K = mat(zeros((m,1)))
    if kTup[0]=='lin': K = X * A.T   #linear kernel
    elif kTup[0]=='rbf':
        for j in range(m):
            deltaRow = X[j,:] - A
            K[j] = deltaRow*deltaRow.T
        K = exp(K/(-1*kTup[1]**2)) #divide in NumPy is element-wise not matrix like Matlab
    else: raise NameError('Houston We Have a Problem -- \
    That Kernel is not recognized')
    return K
class optStruct:
    def __init__(self,dataMatIn, classLabels, C, toler, kTup):  # Initialize the structure with the parameters
        self.X = dataMatIn
        self.labelMat = classLabels
        self.C = C
        self.tol = toler
        self.m = shape(dataMatIn)[0]
        self.alphas = mat(zeros((self.m,1)))
        self.b = 0
        self.eCache = mat(zeros((self.m,2))) #first column is valid flag
        self.K = mat(zeros((self.m,self.m)))
        for i in range(self.m):
            self.K[:,i] = kernelTrans(self.X, self.X[i,:], kTup)
def calcEk(oS, k):
    fXk = float(multiply(oS.alphas,oS.labelMat).T*oS.K[:,k] + oS.b)
    Ek = fXk - float(oS.labelMat[k])
    return Ek
def selectJ(i, oS, Ei):         #this is the second choice -heurstic, and calcs Ej
    maxK = -1; maxDeltaE = 0; Ej = 0
    oS.eCache[i] = [1,Ei]  #set valid #choose the alpha that gives the maximum delta E
    validEcacheList = nonzero(oS.eCache[:,0].A)[0]
    if (len(validEcacheList)) > 1:
        for k in validEcacheList:   #loop through valid Ecache values and find the one that maximizes delta E
            if k == i: continue #don't calc for i, waste of time
            Ek = calcEk(oS, k)
            deltaE = abs(Ei - Ek)
            if (deltaE > maxDeltaE):
                maxK = k; maxDeltaE = deltaE; Ej = Ek
        return maxK, Ej
    else:   #in this case (first time around) we don't have any valid eCache values
        j = selectJrand(i, oS.m)
        Ej = calcEk(oS, j)
    return j, Ej
def updateEk(oS, k):#after any alpha has changed update the new value in the cache
    Ek = calcEk(oS, k)
    oS.eCache[k] = [1,Ek]
def innerL(i, oS):
    Ei = calcEk(oS, i)
    if ((oS.labelMat[i]*Ei < -oS.tol) and (oS.alphas[i] < oS.C)) or ((oS.labelMat[i]*Ei > oS.tol) and (oS.alphas[i] > 0)):
        j,Ej = selectJ(i, oS, Ei) #this has been changed from selectJrand
        alphaIold = oS.alphas[i].copy(); alphaJold = oS.alphas[j].copy();
        if (oS.labelMat[i] != oS.labelMat[j]):
            L = max(0, oS.alphas[j] - oS.alphas[i])
            H = min(oS.C, oS.C + oS.alphas[j] - oS.alphas[i])
        else:
            L = max(0, oS.alphas[j] + oS.alphas[i] - oS.C)
            H = min(oS.C, oS.alphas[j] + oS.alphas[i])
        if L==H: 
            #print "L==H"
            return 0
        eta = 2.0 * oS.K[i,j] - oS.K[i,i] - oS.K[j,j] #changed for kernel
        if eta >= 0: 
            #print "eta>=0"
            return 0
        oS.alphas[j] -= oS.labelMat[j]*(Ei - Ej)/eta
        oS.alphas[j] = clipAlpha(oS.alphas[j],H,L)
        updateEk(oS, j) #added this for the Ecache
        if (abs(oS.alphas[j] - alphaJold) < 0.00001): 
            #print "j not moving enough"
            return 0
        oS.alphas[i] += oS.labelMat[j]*oS.labelMat[i]*(alphaJold - oS.alphas[j])#update i by the same amount as j
        updateEk(oS, i) #added this for the Ecache                    #the update is in the oppostie direction
        b1 = oS.b - Ei- oS.labelMat[i]*(oS.alphas[i]-alphaIold)*oS.K[i,i] - oS.labelMat[j]*(oS.alphas[j]-alphaJold)*oS.K[i,j]
        b2 = oS.b - Ej- oS.labelMat[i]*(oS.alphas[i]-alphaIold)*oS.K[i,j]- oS.labelMat[j]*(oS.alphas[j]-alphaJold)*oS.K[j,j]
        if (0 < oS.alphas[i]) and (oS.C > oS.alphas[i]): oS.b = b1
        elif (0 < oS.alphas[j]) and (oS.C > oS.alphas[j]): oS.b = b2
        else: oS.b = (b1 + b2)/2.0
        return 1
    else: return 0
def smoP(dataMatIn, classLabels, C, toler, maxIter,kTup=('lin', 0)):    #full Platt SMO
    oS = optStruct(mat(dataMatIn),mat(classLabels).transpose(),C,toler, kTup)
    iter = 0
    entireSet = True; alphaPairsChanged = 0
    while (iter < maxIter) and ((alphaPairsChanged > 0) or (entireSet)):
        alphaPairsChanged = 0
        if entireSet:   #go over all
            for i in range(oS.m):
                alphaPairsChanged += innerL(i,oS)
                #print "fullSet, iter: %d i:%d, pairs changed %d" % (iter,i,alphaPairsChanged)
            iter += 1
        else:#go over non-bound (railed) alphas
            nonBoundIs = nonzero((oS.alphas.A > 0) * (oS.alphas.A < C))[0]
            for i in nonBoundIs:
                alphaPairsChanged += innerL(i,oS)
                #print "non-bound, iter: %d i:%d, pairs changed %d" % (iter,i,alphaPairsChanged)
            iter += 1
        if entireSet: entireSet = False #toggle entire set loop
        elif (alphaPairsChanged == 0): entireSet = True
        #print "iteration number: %d" % iter
    return oS.b,oS.alphas
def calcWs(alphas,dataArr,classLabels):
    X = mat(dataArr); labelMat = mat(classLabels).transpose()
    m,n = shape(X)
    w = zeros((n,1))
    for i in range(m):
        w += multiply(alphas[i]*labelMat[i],X[i,:].T)
    return w
# 利用核函数进行分类的径向基测试函数
def testRbf(k1=1.3):
    dataArr,labelArr = loadDataSet('data/SVM/testSetRBF.txt')
    b,alphas = smoP(dataArr, labelArr, 200, 0.0001, 10000, ('rbf', k1)) #C=200 important
    datMat=mat(dataArr); labelMat = mat(labelArr).transpose()
    svInd=nonzero(alphas.A>0)[0]
    sVs=datMat[svInd] #get matrix of only support vectors
    labelSV = labelMat[svInd];
    print("there are %d Support Vectors" % shape(sVs)[0])
    m,n = shape(datMat)
    errorCount = 0
    for i in range(m):
        kernelEval = kernelTrans(sVs,datMat[i,:],('rbf', k1))
        predict=kernelEval.T * multiply(labelSV,alphas[svInd]) + b
        if sign(predict)!=sign(labelArr[i]): errorCount += 1
    print("the training error rate is: %f" % (float(errorCount)/m))
    dataArr,labelArr = loadDataSet('data/SVM/testSetRBF2.txt')
    errorCount = 0
    datMat=mat(dataArr); labelMat = mat(labelArr).transpose()
    m,n = shape(datMat)
    for i in range(m):
        kernelEval = kernelTrans(sVs,datMat[i,:],('rbf', k1))
        predict=kernelEval.T * multiply(labelSV,alphas[svInd]) + b
        if sign(predict)!=sign(labelArr[i]): errorCount += 1
    print("the test error rate is: %f" % (float(errorCount)/m))
    
    x0 = []; y0 = []
    x1 = []; y1 = []
    x_sv = []; y_sv = []
    for i in range(100):
        if alphas[i] > 0.0:
            x_sv.append(dataArr[i][0])
            y_sv.append(dataArr[i][1])
        elif labelArr[i] > 0.0:
            x0.append(dataArr[i][0])
            y0.append(dataArr[i][1])
        else:
            x1.append(dataArr[i][0])
            y1.append(dataArr[i][1])
    pp.scatter(x0,y0,color='r')
    pp.scatter(x1,y1,color='g')
    pp.scatter(x_sv,y_sv,color='b')
testRbf()
there are 26 Support Vectors
the training error rate is: 0.090000
the test error rate is: 0.180000

testRbf(0.1)
there are 88 Support Vectors
the training error rate is: 0.000000
the test error rate is: 0.080000

支持向量的数目存在一个最优值
SVM的有点在于它能对数据进行高效分类。
如果支持向量太少,就可能会得到一个很差的决策边界。
如果支持向量太多,就相当于每次都利用整个数据集进行分类,即k近邻。

六、示例:手写识别问题回顾

kNN方法需要保留所有的训练样本。
支持向量机只需要保留支持向量,即少量的样本。

def img2vector(filename):
    returnVect = zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0,32*i+j] = int(lineStr[j])
    return returnVect
# 基于SVM的手写数字识别
def loadImage(dirName):
    from os import listdir
    hwLabels = []
    trainingFileList = listdir(dirName)
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        filrStr = fileNameStr.split('.')[0]
        classNumStr = int(filrStr.split('_')[0])
        if classNumStr == 9:
            hwLabels.append(-1)
        else:
            hwLabels.append(1)
        trainingMat[i,:] = img2vector('%s/%s' % (dirName, fileNameStr))
    return trainingMat, hwLabels
def testDigits(kTup=('rbf', 10)):
    dataArr, labelArr = loadImage('data/trainingDigits/')
    b, alphas = smoP(dataArr, labelArr, 200, 0.0001, 10000, kTup)
    datMat = mat(dataArr)
    labelMat = mat(labelArr).transpose()
    svInd = nonzero(alphas.A>0)[0]
    sVs = datMat[svInd]
    labelSV = labelMat[svInd]
    print('there are %d Support Vectors' % shape(sVs)[0])
    m, n = shape(datMat)
    errorCount = 0.0
    for i in range(m):
        kernelEval = kernelTrans(sVs, datMat[i,:], kTup)
        predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b
        if sign(predict) != sign(labelArr[i]):
            errorCount += 1
    print('the training error rate is : %f' % (float(errorCount)/m))
    dataArr, labelArr = loadImage('data/testDigits/')
    errorCount = 0.0
    datMat = mat(dataArr)
    labelMat = mat(labelArr).transpose()
    m, n = shape(datMat)
    for i in range(m):
        kernelEval = kernelTrans(sVs, datMat[i,:], kTup)
        predict = kernelEval.T * multiply(labelSV, alphas[svInd]) + b
        if sign(predict) != sign(labelArr[i]):
            errorCount += 1
    print('the testing error rate is : %f' % (float(errorCount)/m))
testDigits(('rbf', 20))
there are 157 Support Vectors
the training error rate is : 0.000000
the testing error rate is : 0.012685
testDigits(('lin', 0))
there are 136 Support Vectors
the training error rate is : 0.054809
the testing error rate is : 0.049683
  1. 径向基核函数中的参数σ取值在于数据的不同,另外C的设置也会影响到分类的结果。
  2. 最小的训练错误并不对应于最小的支持向量数目。
  3. 线性核函数的效果并不是特别糟糕,可以牺牲线性核函数的错误率来换取分类速度的提高。

七、小结

  1. SVM是一种决策机,产生一个二值决策结果。
  2. 泛化错误率低,即具有良好的学习能力且具有推广性。
  3. SVM通过求解一个二次优化问题来最大化分类间隔。
  4. SMO算法通过每次只优化2个alpha值来加快SVM的训练速度。
  5. kernel将数据从一个低维空间映射到一个高维空间,将低维空间中的非线性问题转换成高维空间中的线性问题。
  6. 径向基函数是一个常用的度量两个向量距离的核函数。
  7. SVM时一个二类分类器,当用其解决多类问题时,则需要额外的方法对其进行扩展。
  8. SVM的效果对优化参数和核函数的参数敏感。
posted @ 2017-06-29 20:26  戴戴Day  阅读(1308)  评论(1编辑  收藏  举报