原理
- 尋找一個(gè)分割超平面來作為分類邊界,找到離分割超平面最近的點(diǎn),確保它們離分割超平面的距離盡可能遠(yuǎn)。
- 支持向量就是離分割超平面最近的那些點(diǎn)
優(yōu)點(diǎn):
- 泛化錯(cuò)誤率低,計(jì)算開銷不大,結(jié)果易解釋。
缺點(diǎn):
- 對(duì)參數(shù)調(diào)節(jié)和核函數(shù)的選擇敏感,原始分類器不加修改僅適用于處理二類問題。
適用數(shù)據(jù)類型:
- 數(shù)值型和標(biāo)稱型數(shù)據(jù)。
簡(jiǎn)化版SMO算法
#加載數(shù)據(jù)
def loadData(path):
#新建數(shù)據(jù)和標(biāo)簽列表
dataList = [];labelList= []
#獲得文件指針
fr = open(path)
#一行一行讀取
for line in fr.readlines():
#分割返回list
lineList = line.strip().split()
#取前1,2列作為訓(xùn)練數(shù)據(jù)
dataList.append([float(lineList[0]),float(lineList[1])])
#最后一列最為標(biāo)簽數(shù)據(jù)
labelList.append(float(lineList[-1]))
return dataList,labelList
dataList,labelList = loadData('../../Reference Code/Ch06/testSet.txt')
#隨機(jī)選擇alpha
import random
def selectJrand(i,m):
#這里可能隨機(jī)取值會(huì)取到和i相等的值,為了j!=i,所以才先賦值j=1,再while循環(huán)
j = i
while(j==i):
j = int(random.uniform(0,m))
return j
j = selectJrand(1,6)
# def selectJrand(m):
# j = int(random.uniform(0,m))
# return j
# j = selectJrand(6)
def clipAlpha(aj,H,L):
if aj>H:
aj = H
if L>aj:
aj = L
return aj
import sys
print(sys.executable)
/home/ubuntu/anaconda3/bin/python
#簡(jiǎn)化版SMO
import numpy as np
def smoSimple(dataMatIn,classLabels,C,toler,maxIter):
'''
參數(shù):
dataMatIn:輸入數(shù)據(jù)
classLabels:標(biāo)簽
C:懲罰項(xiàng)
toler:錯(cuò)誤容忍度
maxIter:最大迭代次數(shù)
返回:
b:偏置項(xiàng)
alphas:拉格朗日乘子
'''
#數(shù)據(jù)和標(biāo)簽轉(zhuǎn)化為ndarray
#等價(jià)于dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).T
dataArray = np.array(dataMatIn); labelArray = np.array(classLabels).reshape(-1,1)
#初始化b,獲得數(shù)據(jù)矩陣的行列
b = 0; m,n = shape(dataArray)
#初始化alphas全為0向量
alphas = np.zeros((m,1))
#初始化迭代次數(shù)
Iter =0
#當(dāng)?shù)螖?shù)小于最大迭代次數(shù)
while (Iter<maxIter):
#alpha對(duì)
alphaPairsChanged = 0
#遍歷每一個(gè)實(shí)例
for i in range(m):
#計(jì)算g(xi)
'''
兩個(gè)array的相乘*指的是對(duì)應(yīng)元素的相乘;兩個(gè)array的dot表示矩陣的相乘。
a=np.array([1,2])
b=np.array([1,2])
print(a*b) # [1 4]
print(np.dot(a,b)) #5
'''
fXi = float(np.dot((alphas*labelArray).T,np.dot(dataArray,dataArray[i:i+1,:].T))) + b
#計(jì)算Ei
Ei = fXi - float(labelArray[i])
#找到違反KKT條件的實(shí)例
if ((labelArray[i]*Ei < toler) and (alphas[i] < C)) \
or ((labelArray[i] *Ei > toler) and (alphas[i] > 0)):
#隨機(jī)選擇j,j!=i
j = selectJrand(i,m)
#計(jì)算g(xj)
'''
注意區(qū)別
shape(dataArray[1,:]) #(2, )
shape(dataArray[1,:].T)# (2, )
shape(dataArray[1:2,:].T)(2, 1)
'''
fXj = float(np.dot((alphas*labelArray).T,np.dot(dataArray,dataArray[j:j+1,:].T))) + b
#計(jì)算Ej
Ej = fXj - float(labelArray[j])
#賦值舊的alphai和alphaj
alphaIold = alphas[i].copy()
alphaJold = alphas[j].copy()
#若yi!=yj
if (labelArray[i] != labelArray[j]):
L = max(0, alphas[j] - alphas[i])
H = min(C, C + alphas[j] - alphas[i])
#若yi=yj
else:
L = max(0, alphas[j] + alphas[i] - C)
H = min(C, alphas[j] - alphas[i])
if L==H:print('L==H');continue
#計(jì)算eta,參考李航PP127
eta = 2.0*np.dot(dataArray[i],dataArray[j]) \
- np.dot(dataArray[i],dataArray[i])\
- np.dot(dataArray[j],dataArray[j])
if eta >= 0:print('eta>=0');continue
#跟新alphaj
alphas[j] -= labelArray[j]*(Ei - Ej)/eta
#若alphaj>H,則取H,若alphaj<L,則取L,若L<alphaj<H,則取alphaj.
alphas[j] = clipAlpha(alphas[j],H,L)
#判斷alphaj是否有足夠大的變化
if (abs(alphas[j] - alphaJold) < 0.00001):print('j not moving enough');continue
#跟新alphai
alphas[i] += labelArray[j]*labelArray[i]*(alphaJold - alphas[j])
#重新計(jì)算閾值b
b1 = b- Ei - labelArray[i]*(alphas[i] - alphaIold)*np.dot(dataArray[i],dataArray[i,:]) \
- labelArray[j]*(alphas[j] - alphaJold) * np.dot(dataArray[i],dataArray[j])
b2 = b- Ei - labelArray[i]*(alphas[i] - alphaIold)*np.dot(dataArray[i],dataArray[j]) \
- labelArray[j]*(alphas[j] - alphaJold) * np.dot(dataArray[j],dataArray[j])
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
#alpha對(duì)加一
alphaPairsChanged += 1
print("循環(huán)次數(shù): {} alpha:{}, alpha對(duì)修改了 {} 次".format(Iter,i,alphaPairsChanged))
if(alphaPairsChanged == 0): Iter += 1
else: Iter = 0
print("迭代次數(shù): {}".format(Iter))
return b,alphas
dataList,labelList = loadData('../../Reference Code/Ch06/testSet.txt')
b, alphas = smoSimple(dataList, labelList, 0.6, 0.001, 40)
print('b= {}'.format(b))
print('(支持向量對(duì)應(yīng)的alpha>0)alpha>0\n{}'.format(alphas[alphas>0]))
循環(huán)次數(shù): 0 alpha:0, alpha對(duì)修改了 1 次
循環(huán)次數(shù): 0 alpha:2, alpha對(duì)修改了 2 次
L==H
j not moving enough
循環(huán)次數(shù): 0 alpha:6, alpha對(duì)修改了 3 次
j not moving enough
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:22, alpha對(duì)修改了 4 次
j not moving enough
L==H
j not moving enough
L==H
j not moving enough
j not moving enough
L==H
L==H
循環(huán)次數(shù): 0 alpha:54, alpha對(duì)修改了 5 次
循環(huán)次數(shù): 0 alpha:55, alpha對(duì)修改了 6 次
j not moving enough
L==H
j not moving enough
L==H
L==H
迭代次數(shù): 0
j not moving enough
j not moving enough
L==H
L==H
L==H
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
L==H
L==H
L==H
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
L==H
循環(huán)次數(shù): 0 alpha:97, alpha對(duì)修改了 1 次
迭代次數(shù): 0
j not moving enough
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:54, alpha對(duì)修改了 1 次
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:97, alpha對(duì)修改了 2 次
迭代次數(shù): 0
j not moving enough
循環(huán)次數(shù): 0 alpha:13, alpha對(duì)修改了 1 次
迭代次數(shù): 25
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 26
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 27
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 28
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 29
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 30
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 31
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 32
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 33
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 34
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 35
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 36
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 37
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 38
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 39
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 40
b= [-4.48392829]
(支持向量對(duì)應(yīng)的alpha>0)alpha>0
[0.02485639 0.33967041 0.26285541 0.1016714 ]
#打印支持向量
for i in range(len(dataList)):
if alphas[i]>0.0:
print(dataList[i],labelList[i])
[4.658191, 3.507396] -1
[2.893743, -1.643468] -1
[5.286862, -2.358286] 1
[6.080573, 0.418886] 1
import matplotlib.pyplot as plt
import numpy as np
def dataToShow(dataList,labelList,b,alphas):
#array形式方便處理
dataArray = np.array(dataList)
alphasArray = np.array(alphas.tolist())
#變成一列,-1表示自動(dòng)計(jì)算多少行
labelArray = np.array(labelList).reshape(-1,1)
#正類負(fù)類分開畫圖,np.squeeze轉(zhuǎn)化成一維的
posData = dataArray[np.squeeze(labelArray>0.0)]
negData = dataArray[np.squeeze(labelArray<0.0)]
svData = dataArray[np.squeeze(alphasArray>0.0)]
plt.figure()
plt.scatter(posData[:,0],posData[:,1],c='b',s=20)
plt.scatter(negData[:,0],negData[:,1],c='r',s=20)
plt.scatter(svData[:,0],svData[:,1],marker='o',c='',s=100,edgecolors='g')
plt.legend(['Positive Point','Negatibe Poin','Support Vector'])
#畫分割超平面
w = np.dot((alphasArray * labelArray).T, dataArray)
x0 = np.array([2, 8])
#分割線:w0*x0+w1*x1+b=0
x1 = -(w[0, 0] * x0 + np.squeeze(np.array(b))) / w[0, 1]
plt.plot(x0, x1, color = 'y')
plt.ylim((-10,12))
plt.show()
dataToShow(dataList,labelList,b,alphas)

output_7_0.png
完整版SMO算法
class optStructK:
def __init__(self,dataMatIn, classLabels, C, toler):
self.X = dataMatIn
selef.labelMat = classLabels
self.C = C
self.tol = toler
self.m = shape(dataMatIn)[0]
self.alphas = np.zeros((self.m,1))
self.b = 0
self.eCache = np.zeros((self.m,2)) #誤差緩存
#計(jì)算Ei
def calcEk(oS, k):
fXk = float(np.dot((oS.alphas * oS.labelMat).T, np.dot(oS.X, oS.X[k:k+1,:].T))) + oS.b
#計(jì)算Ej
Ek = fXk - float(oS.labelMat[k])
return Ek
#內(nèi)循環(huán)選擇alpha
def selectJK(i,oS,Ei):
'''
內(nèi)循環(huán)選擇alpha的啟發(fā)式算法
參數(shù):
i -- 外循環(huán)alpha的下標(biāo)
oS -- 類
Ei -- 誤差
返回:
j -- 選擇alpha的下標(biāo)
Ej -- 誤差
'''
#初始化
maxK = -1;maxDeltaE = 0; Ej = 0
oS.eCache[i] = [1,Ei]
#選擇合理的集合
validEcacheList = np.nonzero(oS.eCache[:,0])[0]
if (len(validEcacheList)) > 1:
#選擇最大步長(zhǎng)的alpha
for k in validEcacheList:
#不重復(fù)計(jì)算
if k == i: continue
#計(jì)算誤差
Ek = calcEk(oS, k)
#計(jì)算步長(zhǎng)
deltaE = abs(Ei - Ek)
#記錄最佳選擇
if (deltaE > maxDeltaE):
maxK = k;maxDeltaE = deltaE; Ej = Ek
return maxK, Ej
#沒有合理值
else:
#隨機(jī)選擇
j = select(i,oS.m)
Ej = calcEk(oS,j)
return j,Ej
def updateEkK(oS,k):
#在alpha更新后存儲(chǔ)計(jì)算得到的誤差
Ek = calcEk(oS,k)
oS.eCache[k] = [1,Ek]
def innerLK(i, oS):
#計(jì)算誤差
Ei = calcEkK(oS, i)
#找出不滿足KKT條件的alpha
if ((oS.labelMat[i, 0]*Ei < -oS.tol) and (oS.alphas[i, 0] < oS.C)) or ((oS.labelMat[i, 0]*Ei > oS.tol) and (oS.alphas[i, 0] > 0)):
#選擇j
j,Ej = selectJK(i, oS, Ei)
#存儲(chǔ)舊的值
alphaIold = oS.alphas[i, 0].copy(); alphaJold = oS.alphas[j, 0].copy();
#兩種情況求邊界值
if (oS.labelMat[i, 0] != oS.labelMat[j, 0]):
L = max(0, oS.alphas[j, 0] - oS.alphas[i, 0])
H = min(oS.C, oS.C + oS.alphas[j, 0] - oS.alphas[i, 0])
else:
L = max(0, oS.alphas[j, 0] + oS.alphas[i, 0] - oS.C)
H = min(oS.C, oS.alphas[j, 0] + oS.alphas[i, 0])
if L==H: return 0
#計(jì)算變化量
eta = 2.0 * np.dot(oS.X[i:i+1,:], oS.X[j:j+1,:].T) - np.dot(oS.X[i:i+1,:], oS.X[i:i+1,:].T) - np.dot(oS.X[j:j+1,:], oS.X[j:j+1,:].T)
if eta >= 0: return 0
#更新alpha
oS.alphas[j, 0] -= oS.labelMat[j, 0]*(Ei - Ej)/eta
#約束alpha
oS.alphas[j, 0] = clipAlpha(oS.alphas[j, 0],H,L)
updateEkK(oS, j)
if (abs(oS.alphas[j, 0] - alphaJold) < 0.00001): return 0
oS.alphas[i, 0] += oS.labelMat[j, 0]*oS.labelMat[i, 0]*(alphaJold - oS.alphas[j, 0])
updateEkK(oS, i)
b1 = oS.b - Ei- oS.labelMat[i, 0]*(oS.alphas[i, 0]-alphaIold)*np.dot(oS.X[i:i+1,:], oS.X[i:i+1,:].T) - oS.labelMat[j, 0]*(oS.alphas[j, 0]-alphaJold)*np.dot(oS.X[i:i+1,:], oS.X[j:j+1,:].T)
b2 = oS.b - Ej- oS.labelMat[i, 0]*(oS.alphas[i, 0]-alphaIold)*np.dot(oS.X[i:i+1,:], oS.X[j:j+1,:].T) - oS.labelMat[j, 0]*(oS.alphas[j, 0]-alphaJold)*np.dot(oS.X[j:j+1,:], oS.X[j:j+1,:].T)
if (0 < oS.alphas[i, 0]) and (oS.C > oS.alphas[i, 0]): oS.b = b1
elif (0 < oS.alphas[j, 0]) and (oS.C > oS.alphas[j, 0]): oS.b = b2
else: oS.b = (b1 + b2)/2.0
return 1
else: return 0
def smoPK(dataMatIn, classLabels, C, toler, maxIter):
#建立類變量
oS = optStructK(np.array(dataMatIn),np.array(classLabels).reshape(-1, 1),C,toler)
iter = 0
entireSet = True; alphaPairsChanged = 0
#執(zhí)行循環(huán)
while (iter < maxIter) and ((alphaPairsChanged > 0) or (entireSet)):
alphaPairsChanged = 0
if entireSet:
#遍歷所有
for i in range(oS.m):
alphaPairsChanged += innerLK(i,oS)
#print("fullSet, iter: {} i:{}, pairs changed {}".format(iter,i,alphaPairsChanged))
iter += 1
else:
#遍歷非邊界值
nonBoundIs = np.nonzero((oS.alphas > 0) * (oS.alphas < C))[0]
for i in nonBoundIs:
alphaPairsChanged += innerLK(i,oS)
#print("non-bound, iter: {} i:{}, pairs changed {}".format(iter,i,alphaPairsChanged))
iter += 1
if entireSet: entireSet = False
elif (alphaPairsChanged == 0): entireSet = True
#print("iteration number: {}".format(iter))
return oS.b,oS.alphas
dataList,labelList = loadData('../../Reference Code/Ch06/testSet.txt')
b, alphas = smoSimple(dataList, labelList, 0.6, 0.001, 40)
print('b= {}'.format(b))
print('(支持向量對(duì)應(yīng)的alpha>0)alpha>0\n{}'.format(alphas[alphas>0]))
循環(huán)次數(shù): 0 alpha:0, alpha對(duì)修改了 1 次
L==H
循環(huán)次數(shù): 0 alpha:4, alpha對(duì)修改了 2 次
j not moving enough
循環(huán)次數(shù): 0 alpha:6, alpha對(duì)修改了 3 次
L==H
j not moving enough
L==H
循環(huán)次數(shù): 0 alpha:25, alpha對(duì)修改了 4 次
L==H
循環(huán)次數(shù): 0 alpha:29, alpha對(duì)修改了 5 次
L==H
循環(huán)次數(shù): 0 alpha:52, alpha對(duì)修改了 6 次
j not moving enough
循環(huán)次數(shù): 0 alpha:55, alpha對(duì)修改了 7 次
L==H
j not moving enough
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 0
j not moving enough
j not moving enough
j not moving enough
j not moving enough
L==H
L==H
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
L==H
循環(huán)次數(shù): 0 alpha:52, alpha對(duì)修改了 1 次
j not moving enough
循環(huán)次數(shù): 0 alpha:55, alpha對(duì)修改了 2 次
j not moving enough
j not moving enough
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:76, alpha對(duì)修改了 3 次
j not moving enough
L==H
L==H
迭代次數(shù): 0
循環(huán)次數(shù): 0 alpha:0, alpha對(duì)修改了 1 次
j not moving enough
j not moving enough
L==H
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:96, alpha對(duì)修改了 2 次
j not moving enough
迭代次數(shù): 0
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:8, alpha對(duì)修改了 1 次
循環(huán)次數(shù): 0 alpha:10, alpha對(duì)修改了 2 次
L==H
j not moving enough
j not moving enough
j not moving enough
L==H
L==H
循環(huán)次數(shù): 0 alpha:54, alpha對(duì)修改了 3 次
j not moving enough
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 0
j not moving enough
循環(huán)次數(shù): 0 alpha:5, alpha對(duì)修改了 1 次
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:17, alpha對(duì)修改了 2 次
L==H
j not moving enough
j not moving enough
L==H
j not moving enough
L==H
L==H
j not moving enough
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
L==H
L==H
迭代次數(shù): 0
j not moving enough
循環(huán)次數(shù): 0 alpha:5, alpha對(duì)修改了 1 次
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:29, alpha對(duì)修改了 2 次
j not moving enough
循環(huán)次數(shù): 0 alpha:52, alpha對(duì)修改了 3 次
循環(huán)次數(shù): 0 alpha:54, alpha對(duì)修改了 4 次
j not moving enough
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 0
j not moving enough
j not moving enough
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:54, alpha對(duì)修改了 1 次
j not moving enough
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:86, alpha對(duì)修改了 2 次
L==H
L==H
j not moving enough
L==H
j not moving enough
迭代次數(shù): 0
j not moving enough
j not moving enough
循環(huán)次數(shù): 0 alpha:5, alpha對(duì)修改了 1 次
j not moving enough
j not moving enough
L==H
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 38
j not moving enough
j not moving enough
j not moving enough
j not moving enough
迭代次數(shù): 39
j not moving enough
j not moving enough
L==H
j not moving enough
迭代次數(shù): 40
b= [-4.65074859]
(支持向量對(duì)應(yīng)的alpha>0)alpha>0
[0.11699604 0.29638533 0.41338137]
dataToShow(dataList,labelList,b,alphas)

output_12_0.png
引入核函數(shù)
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] = np.dot(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: return 0
eta = 2.0 * oS.K[i,j] - oS.K[i,i] - oS.K[j,j] #changed for kernel
if 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): 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
測(cè)試
def testRbf(k1=1.3):
dataArr,labelArr = loadData('../../Reference Code/Ch06/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 = loadData('../../Reference Code/Ch06/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) )
return b,alphas
import matplotlib.pyplot as plt
import numpy as np
def dataToShow(dataList,labelList,b,alphas):
#array形式方便處理
dataArray = np.array(dataList)
alphasArray = np.array(alphas.tolist())
#變成一列,-1表示自動(dòng)計(jì)算多少行
labelArray = np.array(labelList).reshape(-1,1)
#正類負(fù)類分開畫圖,np.squeeze轉(zhuǎn)化成一維的
posData = dataArray[np.squeeze(labelArray>0.0)]
negData = dataArray[np.squeeze(labelArray<0.0)]
svData = dataArray[np.squeeze(alphasArray>0.0)]
plt.figure()
plt.scatter(posData[:,0],posData[:,1],c='b',s=20)
plt.scatter(negData[:,0],negData[:,1],c='r',s=20)
plt.scatter(svData[:,0],svData[:,1],marker='o',c='',s=100,edgecolors='g')
plt.legend(['Positive Point','Negatibe Poin','Support Vector'])
# #畫分割超平面
# w = np.dot((alphasArray * labelArray).T, dataArray)
# x0 = np.array([2, 8])
# #分割線:w0*x0+w1*x1+b=0
# x1 = -(w[0, 0] * x0 + np.squeeze(np.array(b))) / w[0, 1]
# plt.plot(x0, x1, color = 'y')
# plt.ylim((-10,12))
plt.show()
dataList,labelList = loadData('../../Reference Code/Ch06/testSetRBF.txt')
b,alphas = testRbf(k1=1.3)
dataToShow(dataList,labelList,b,alphas)
there are 29 Support Vectors
the training error rate is: 0.130000
the test error rate is: 0.150000

output_19_1.png
b,alphas = testRbf(k1=0.1)
dataToShow(dataList,labelList,b,alphas)
there are 84 Support Vectors
the training error rate is: 0.000000
the test error rate is: 0.090000

output_20_1.png
手寫識(shí)別
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
def loadImages(dirName):
from os import listdir
hwLabels = []
trainingFileList = listdir(dirName) #load the training set
m = len(trainingFileList)
trainingMat = zeros((m,1024))
for i in range(m):
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0] #take off .txt
classNumStr = int(fileStr.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 = loadImages('../../../Week1/Reference Code/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
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 = loadImages('../../../Week1/Reference Code/testDigits')
errorCount = 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 test error rate is: %f" % (float(errorCount)/m))
testDigits(('rbf', 20))
there are 204 Support Vectors
the training error rate is: 0.000000
the test error rate is: 0.010571