一、應用簡化版SMO算法來處理小規模數據集
該SMO函數的僞代碼:
創建一個alpha向量並將其初始化爲O 向量
當迭代次數小於最大迭代次數時(外循環)
對數據集中的每個數據向量(內循環):
如果該數據向量可以被優化:
隨機選擇另外一個數據向量
同時優化這兩個向量
如果兩個向量都不能被優化,退出內循環
如果所有向量都沒被優化,增加迭代數目,繼續下一次循環
Python源碼:
from numpy import *
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): #選擇兩個不同的alpha值,如果一個選爲第alpha[i],則另一個alpha值選擇除了i隨機的一個
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): #由於aj的取值範圍的限制,H爲上限,L爲下限
if aj > H:
aj = H
if L > aj:
aj = L
return aj
'''
功能:簡單版的SMO
輸入參數:
dataMatIn:數據集
classLabels:類別標籤
C:控制參數(懲罰參數)
toler:容錯率
maxIter:最大的循環次數
輸出參數:
b:f(x)中的b值
alpha:拉格朗日乘子
'''
def smoSimple(dataMatIn, classLabels, C, toler, maxIter):
dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()
b = 0; m,n = shape(dataMatrix) #將多個列表和輸人蔘數轉換成爲numpy矩陣,這樣就可以簡化很多數學處理操作
alphas = mat(zeros((m,1)))
iter = 0 #初始化遍歷次數
while (iter < maxIter): #只有在所有數據集上遍歷maxIter次,且不再發生任何alpha修改之後,程序纔會停止並退出while循環
alphaPairsChanged = 0 #記錄alpha是否巳經進行優化
for i in range(m):
fXi = float(multiply(alphas,labelMat).T*(dataMatrix*dataMatrix[i,:].T)) + b #預測的類別
Ei = fXi - float(labelMat[i]) #Ei爲計算誤差;if checks if an example violates KKT conditions
#一旦alphas等於0或C,那麼它們就巳經在“邊界”上了,因而不再能夠減小或增大,因此也就不值得再對它們進行優化了
if ((labelMat[i]*Ei < -toler) and (alphas[i] < C)) or ((labelMat[i]*Ei > toler) and (alphas[i] > 0)):
j = selectJrand(i,m) #隨機選擇第二個alpha值
fXj = float(multiply(alphas,labelMat).T*(dataMatrix*dataMatrix[j,:].T)) + b
Ej = fXj - float(labelMat[j]) #計算第二個alpha值的誤差
alphaIold = alphas[i].copy(); alphaJold = alphas[j].copy();
if (labelMat[i] != labelMat[j]): #當y1和y2異號,計算alpha的取值範圍
L = max(0, alphas[j] - alphas[i])
H = min(C, C + alphas[j] - alphas[i])
else: #當y1和y2同號,計算alpha的取值範圍
L = max(0, alphas[j] + alphas[i] - C)
H = min(C, alphas[j] + alphas[i])
if L==H: print "i:%d, L==H" %(i); continue
#eta = K11+K22-2*K12,也是f(x)的二階導數
eta = 2.0 * dataMatrix[i,:]*dataMatrix[j,:].T - dataMatrix[i,:]*dataMatrix[i,:].T - dataMatrix[j,:]*dataMatrix[j,:].T
if eta >= 0: print "i:%d, eta>=0" %(i); continue
alphas[j] -= labelMat[j]*(Ei - Ej)/eta #利用公式更新alpha[j]
alphas[j] = clipAlpha(alphas[j],H,L)
if (abs(alphas[j] - alphaJold) < 0.00001): print "i:%d, j not moving enough" %(i); 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 #把新值b給原來的舊值b,爲了後續的循環
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)
## else:
## print "i: %d" %(i)
if (alphaPairsChanged == 0): iter += 1 #檢査alpha值是否做了更新,如果有更新則將iter爲0後繼續運行程序
else: iter = 0
print "iteration number: %d" % iter
return b,alphas
運行以下命令:
dataArr,labelArr = loadDataSet('testSet.txt')
b,alphas = smoSimple(dataArr,labelArr,0.6,0.001,40)
加上求解w的函數(利用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 plotfig_SVM(xMat,yMat,ws,b,alphas):
xMat = mat(xMat)
yMat = mat(yMat)
b = array(b)[0] #b原來是矩陣,先轉爲數組類型後其數組大小爲(1,1),所以後面加[0],變爲(1,)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xMat[:,0].flatten().A[0],xMat[:,1].flatten().A[0]) #注意flatten的用法
x = arange(-1.0,10.0,0.1) #x最大值,最小值根據原數據集dataArr[:,0]的大小而定
y =(-b-ws[0][0]*x)/ws[1][0] #根據x.w + b = 0 得到,其式子展開爲w0.x1 + w1.x2 + b = 0,x2就是y值
ax.plot(x,y)
for i in range(100): #找到支持向量,並在圖中標紅
if alphas[i]>0.0:
ax.plot(xMat[i,0],xMat[i,1],'ro')
plt.show()
ws = calcWs(alphas,dataArr,labelArr)
plotfig_SVM(dataArr,labelArr,ws,b,alphas)
畫圖:(其中紅色的點爲支持向量)
二、利用完整Platt SMO算法加速優化
Platt SMO 算法是通過一個外循環來選擇第一個alpha值的,並且其選擇過程會在兩種方式之間進行交替: 一種方式是在所有數據集上進行單遍掃描, 另一種方式則是在非邊界alpha中實現單遍掃描。而所謂非邊界alpha是指的就是那些不等於邊界0或C的alpha值。對整個數據集的掃描相當容易,而實現非邊界alpha值的掃描時,首先需要建立這些alpha值的列表,然後再對這個表進行遍歷。同時,該步驟會跳過那些已知的不會改變的alpha值 。
Python代碼:
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(是否有效的標誌位),第二列是實際的E值(誤差值)
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
#選擇第二個alhpa值以保證在每次優化中採用最大步長
oS.eCache[i] = [1,Ei] #set valid(將即將使用的Ei值設爲有效) #choose the alpha that gives the maximum delta E
validEcacheList = nonzero(oS.eCache[:,0].A)[0]
if (len(validEcacheList)) > 1: #選擇其中使改變最大的那個E值
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]
'''
功能:和smoSimple函數一樣(包括選擇第二個乘子)
'''
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]): #當y1和y2異號,計算alpha[j]的取值範圍
L = max(0, oS.alphas[j] - oS.alphas[i])
H = min(oS.C, oS.C + oS.alphas[j] - oS.alphas[i])
else: #當y1和y2同號,計算alpha[j]的取值範圍
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 #alpha改變標誌位
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
運行以下代碼:
dataArr,labelArr = loadDataSet('testSet.txt')
b,alphas = smoP(dataArr,labelArr,0.6,0.001,40)
ws = calcWs(alphas,dataArr,labelArr)
plotfig_SVM(dataArr,labelArr,ws,b,alphas)
畫圖:
三、在複雜數據上利用核函數
添加函數:
'''
功能:利用核函數進行分類
'''
def testRbf(k1=1.3):
dataArr,labelArr = loadDataSet('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] #找到非零的alphas值,從而得到了所需要的支持向量
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)
predict_label0_index = []
predict_label1_index = []
errorCount = 0
for i in range(m):
kernelEval = kernelTrans(sVs,datMat[i,:],('rbf', k1)) #只利用支持向量就可進行分類
predict = array(kernelEval.T * multiply(labelSV,alphas[svInd]) + b) #計算預測值
if sign(predict) == -1: #如果預測的標籤是-1,則保存一個列表中
predict_label0_index.append(i)
elif sign(predict) == 1: #如果預測的標籤是-1,則保存另一個列表中
predict_label1_index.append(i)
if sign(predict)!=sign(labelArr[i]): errorCount += 1 #利用sign函數,判斷預測是否正確
print "the training error rate is: %f" % (float(errorCount)/m)
plotfig_kernel(dataArr,predict_label0_index,predict_label1_index,alphas)#畫圖
dataArr,labelArr = loadDataSet('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)
其中畫圖函數換爲:
'''
功能:畫利用核函數進行分類的圖
'''
def plotfig_kernel(xMat,predict_label0_index,predict_label1_index,alphas):
fig = plt.figure()
ax = fig.add_subplot(111)
for i in predict_label0_index: #預測標籤爲-1的標爲紅色三角形
ax.plot(xMat[i][0],xMat[i][1],'r^')
for i in predict_label1_index: #預測標籤爲1的標爲藍色正方形
ax.plot(xMat[i][0],xMat[i][1],'bs')
plt.show()
運行命令:
testRbf()
畫圖:
說明:
爲什麼核轉換函數只用支持向量?
因爲根據公式:,其中K( xi , x )爲核函數,當xi不是支持向量時,其前面的ai爲0,所以不是支持向量的元素不用計算,這樣可以大大降低計算量。
參考文章:
4、Stanford機器學習---第八講. 支持向量機SVM
5、機器學習實戰 李銳等譯