機器學習-SVM

\[此篇文章介紹關於SVM中的一些不懂的地方的公式推導,以及代碼實現和一些SVM問題,經過作題檢驗掌握的效果。\]python

1、代碼實現

\[調用sklearn包,進行SVM分類\]算法

#!/usr/bin/python
# -*- coding utf-8 -*-


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib as mpl
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score


def load_data():
    path = 'E:\數據挖掘\Machine learning\[小象學院]機器學習課件\8.Regression代碼\8.Regression\iris.data'  
    # 讀取文件路徑
    data = pd.read_csv(path, header = None)
    # 從data 讀取數據, x爲前4列的全部數據, y爲第5列數據
    x, y = data[range(4)], data[4]
    # 返回字符類別的位置索引, 因y數組包含三類, 對應返回下標值
    y = pd.Categorical(y).codes
    # 取x的前兩列數據, 通常SVM只作二特徵分類, 多特徵的轉化爲多個二特徵分類再bagging?
    x = x[[0, 1]]
    # x = x[[0 ,2]]
    return x, y



def classifier(x,y):
    # 鳶尾花包含四個特徵屬性, 包含三類標籤, 山鳶尾(0), 變色鳶尾(1), 維吉尼亞鳶尾(2)
    iris_feature = u'花萼長度', u'花萼寬度', u'花瓣長度', u'花瓣寬度'
    # 按 0.6 的比例,test_data 佔40%, train_data 佔60%, random_state隨機數的種子, 1爲產生相同隨機數, 產生不一樣隨機數
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, train_size=0.6)
    # 使用SVM進行分類訓練, 包含關鍵字, C, gamma, kernel
    # kernel='linear'時,爲線性核,C越大分類效果越好, kernel= 'rbf' 時(default), 爲高斯核
    # gamma值越小,分類界面越連續;gamma值越大,分類界面越「散」,分類效果越好
    # decision_function_shape = 'ovr' 時,爲one vs rest, 即一個類別與其餘類別進行劃分,decision_function_shape = 'ovo'
    # 爲one vs one,即將類別兩兩之間進行劃分,用二分類的方法模擬多分類的結果
    clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr')
    clf.fit(x_train, y_train.ravel())
    # score函數返回返回該次預測的係數R2, 在(0, 1)之間、accuracy_score指的是分類準確率,即分類正確佔全部分類的百分比
    # recall_score 召回率 = 提取出的正確信息條數 / 樣本中的信息條數
    print(clf.score(x_train, y_train))
    print('訓練集準確率:', accuracy_score(y_train, clf.predict(x_train)))
    print(clf.score(x_test, y_test))
    print('測試集準確率:', accuracy_score(y_test, clf.predict(x_test)))

    # decision_function()的功能: 計算樣本點到分割超平面的函數距離, 每一列的值表明距離各種別的距離
    print('decision_function:\n', clf.decision_function(x_train))
    print('\npredict:\n', clf.predict(x_train))

    # 畫圖
    x1_min, x2_min = x.min()  # 第0列的範圍
    x1_max, x2_max = x.max()  # 第1列的範圍
    x1, x2 = np.mgrid[x1_min:x1_max:500j, x2_min:x2_max:500j]  # 生成網格採樣點
    grid_test = np.stack((x1.flat, x2.flat), axis=1)  # 測試點
    # print 'grid_test = \n', grid_test
    # Z = clf.decision_function(grid_test)    # 樣本到決策面的距離
    # print Z
    grid_hat = clf.predict(grid_test)  # 預測分類值
    grid_hat = grid_hat.reshape(x1.shape)  # 使之與輸入的形狀相同
    mpl.rcParams['font.sans-serif'] = [u'SimHei']
    mpl.rcParams['axes.unicode_minus'] = False

    cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
    cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
    plt.figure(facecolor='w')
    plt.pcolormesh(x1, x2, grid_hat, cmap=cm_light)
    plt.scatter(x[0], x[1], c=y, edgecolors='k', s=50, cmap=cm_dark)  # 樣本
    plt.scatter(x_test[0], x_test[1], s=120, facecolors='none', zorder=10)  # 圈中測試集樣本
    plt.xlabel(iris_feature[0], fontsize=13)
    plt.ylabel(iris_feature[1], fontsize=13)
    plt.xlim(x1_min, x1_max)
    plt.ylim(x2_min, x2_max)
    plt.title(u'鳶尾花SVM二特徵分類', fontsize=16)
    plt.grid(b=True, ls=':')
    plt.tight_layout(pad=1.5)
    plt.show()


if __name__ == "__main__":
    x, y = load_data()
    classifier(x, y)

\[SMO算法\]數組

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt


def loadDataSet(fileName):
    # 數據矩陣
    dataMat = []
    # 標籤向量
    labelMat = []
    # 打開文件
    fr = open(fileName)
    # 逐行讀取
    for line in fr.readlines():
        # 去掉每一行首尾的空白符,例如'\n','\r','\t',' '
        # 將每一行內容根據'\t'符進行切片
        lineArr = line.strip().split('\t')
        # 添加數據(100個元素排成一行)
        dataMat.append([float(lineArr[0]), float(lineArr[1])])
        # 添加標籤(100個元素排成一行)
        labelMat.append(float(lineArr[2]))
    return dataMat, labelMat

def selectJrand(i, m):
    # i爲第一個alpha的下標,m是全部alpha的數目
    j = i
    while (j == i):
        # uniform()方法將隨機生成一個實數,它在[x, y)範圍內
        j = int(np.random.uniform(0, m))
    return j


def clipAlpha(aj, H, L):
    if aj > H:
        aj = H
    if L > aj:
        aj = L
    return aj

def smoSimple(dataMatIn, classLabels, C, toler, maxIter):
    # 轉換爲numpy的mat矩陣存儲(100,2)
    dataMatrix = np.mat(dataMatIn)
    # 轉換爲numpy的mat矩陣存儲並轉置(100,1)
    labelMat = np.mat(classLabels).transpose()
    # 初始化b參數,統計dataMatrix的維度,m:行;n:列
    b = 0
    # 統計dataMatrix的維度,m:100行;n:2列
    m, n = np.shape(dataMatrix)
    # 初始化alpha參數,設爲0
    alphas = np.mat(np.zeros((m, 1)))
    # 初始化迭代次數
    iter_num = 0
    # 最多迭代maxIter次
    while (iter_num < maxIter):
        alphaPairsChanged = 0
        for i in range(m):
            # 步驟1:計算偏差Ei
            # multiply(a,b)就是個乘法,若是a,b是兩個數組,那麼對應元素相乘
            # .T爲轉置
            fxi = float(np.multiply(alphas, labelMat).T * (dataMatrix * dataMatrix[i, :].T)) + b
            # 偏差項計算公式
            Ei = fxi - float(labelMat[i])
            # 優化alpha,設定必定的容錯率
            if ((labelMat[i] * Ei < -toler) and (alphas[i] < C)) or ((labelMat[i] * Ei > toler) and (alphas[i] > 0)):
                # 隨機選擇另外一個alpha_i成對比優化的alpha_j
                j = selectJrand(i, m)
                # 步驟1,計算偏差Ej
                fxj = float(np.multiply(alphas, labelMat).T * (dataMatrix * dataMatrix[j, :].T)) + b
                # 偏差項計算公式
                Ej = fxj - float(labelMat[j])
                # 保存更新前的alpha值,使用深拷貝(徹底拷貝)A深層拷貝爲B,A和B是兩個獨立的個體
                alphaIold = alphas[i].copy()
                alphaJold = alphas[j].copy()
                # 步驟2:計算上下界H和L
                if (labelMat[i] != labelMat[j]):
                    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
                # 步驟3:計算eta
                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
                # 步驟4:更新alpha_j
                alphas[j] -= labelMat[j] * (Ei - Ej) / eta
                # 步驟5:修剪alpha_j
                alphas[j] = clipAlpha(alphas[j], H, L)
                if (abs(alphas[j] - alphaJold) < 0.00001):
                    print("alpha_j變化過小")
                    continue
                # 步驟6:更新alpha_i
                alphas[i] += labelMat[j] * labelMat[i] * (alphaJold - alphas[j])
                # 步驟7:更新b_1和b_2
                b1 = b - Ei - labelMat[i] * (alphas[i] - alphaIold) * dataMatrix[i, :] * dataMatrix[i, :].T - labelMat[
                    j] * (alphas[j] - alphaJold) * dataMatrix[j, :] * dataMatrix[i, :].T
                b2 = b - Ej - labelMat[i] * (alphas[i] - alphaIold) * dataMatrix[i, :] * dataMatrix[j, :].T - labelMat[
                    j] * (alphas[j] - alphaJold) * dataMatrix[j, :] * dataMatrix[j, :].T
                # 步驟8:根據b_1和b_2更新b
                if (0 < alphas[i] < C):
                    b = b1
                elif (0 < alphas[j] < C):
                    b = b2
                else:
                    b = (b1 + b2) / 2.0
                # 統計優化次數
                alphaPairsChanged += 1
                # 打印統計信息
                print("第%d次迭代 樣本:%d, alpha優化次數:%d" % (iter_num, i, alphaPairsChanged))
        # 更新迭代次數
        if (alphaPairsChanged == 0):
            iter_num += 1
        else:
            iter_num = 0
        print("迭代次數:%d" % iter_num)
    return b, alphas


def get_w(dataMat, labelMat, alphas):
    alphas, dataMat, labelMat = np.array(alphas), np.array(dataMat), np.array(labelMat)
    # 咱們不知道labelMat的shape屬性是多少,
    # 可是想讓labelMat變成只有一列,行數不知道多少,
    # 經過labelMat.reshape(1, -1),Numpy自動計算出有100行,
    # 新的數組shape屬性爲(100, 1)
    # np.tile(labelMat.reshape(1, -1).T, (1, 2))將labelMat擴展爲兩列(將第1列複製獲得第2列)
    # dot()函數是矩陣乘,而*則表示逐個元素相乘
    # w = sum(alpha_i * yi * xi)
    w = np.dot((np.tile(labelMat.reshape(1, -1).T, (1, 2)) * dataMat).T, alphas)
    return w.tolist()


def showClassifer(dataMat, w, b):
    # 正樣本
    data_plus = []
    # 負樣本
    data_minus = []
    for i in range(len(dataMat)):
        if labelMat[i] > 0:
            data_plus.append(dataMat[i])
        else:
            data_minus.append(dataMat[i])
    # 轉換爲numpy矩陣
    data_plus_np = np.array(data_plus)
    # 轉換爲numpy矩陣
    data_minus_np = np.array(data_minus)
    # 正樣本散點圖(scatter)
    # transpose轉置
    plt.scatter(np.transpose(data_plus_np)[0], np.transpose(data_plus_np)[1], s=30, alpha=0.7)
    # 負樣本散點圖(scatter)
    plt.scatter(np.transpose(data_minus_np)[0], np.transpose(data_minus_np)[1], s=30, alpha=0.7)
    # 繪製直線
    x1 = max(dataMat)[0]
    x2 = min(dataMat)[0]
    a1, a2 = w
    b = float(b)
    a1 = float(a1[0])
    a2 = float(a2[0])
    y1, y2 = (-b - a1 * x1) / a2, (-b - a1 * x2) / a2
    plt.plot([x1, x2], [y1, y2])
    # 找出支持向量點
    # enumerate在字典上是枚舉、列舉的意思
    for i, alpha in enumerate(alphas):
        # 支持向量機的點
        if (abs(alpha) > 0):
            x, y = dataMat[i]
            plt.scatter([x], [y], s=150, c='none', alpha=0.7, linewidth=1.5, edgecolors='red')
    plt.show()


if __name__ == '__main__':
    dataMat, labelMat = loadDataSet('E:\\數據挖掘\\Machine learning\\代碼\\SVM_Project1\\testSet.txt')
    b, alphas = smoSimple(dataMat, labelMat, 0.6, 0.001, 40)
    w = get_w(dataMat, labelMat, alphas)
    showClassifer(dataMat, w, b)

\[核函數測試\]緩存

# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np
import random

class optStruct:
    def __init__(self, dataMatIn, classLabels, C, toler, kTup):
        # 數據矩陣
        self.X = dataMatIn
        # 數據標籤
        self.labelMat = classLabels
        # 鬆弛變量
        self.C = C
        # 容錯率
        self.tol = toler
        # 矩陣的行數
        self.m = np.shape(dataMatIn)[0]
        # 根據矩陣行數初始化alphas矩陣,一個m行1列的全零列向量
        self.alphas = np.mat(np.zeros((self.m, 1)))
        # 初始化b參數爲0
        self.b = 0
        # 根據矩陣行數初始化偏差緩存矩陣,第一列爲是否有效標誌位,第二列爲實際的偏差E的值
        self.eCache = np.mat(np.zeros((self.m, 2)))
        # 初始化核K
        self.K = np.mat(np.zeros((self.m, self.m)))
        # 計算全部數據的核K
        for i in range(self.m):
            self.K[:, i] = kernelTrans(self.X, self.X[i, :], kTup)

def kernelTrans(X, A, kTup):
    # 讀取X的行列數
    m, n = np.shape(X)
    # K初始化爲m行1列的零向量
    K = np.mat(np.zeros((m, 1)))
    # 線性核函數只進行內積
    if kTup[0] == 'lin':
        K = X * A.T
    # 高斯核函數,根據高斯核函數公式計算
    elif kTup[0] == 'rbf':
        for j in range(m):
            deltaRow = X[j, :] - A
            K[j] = deltaRow * deltaRow.T
        K = np.exp(K / (-1 * kTup[1] ** 2))
    else:
        raise NameError('核函數沒法識別')
    return K


def loadDataSet(fileName):
    # 數據矩陣
    dataMat = []
    # 標籤向量
    labelMat = []
    # 打開文件
    fr = open(fileName)
    # 逐行讀取
    for line in fr.readlines():
        # 去掉每一行首尾的空白符,例如'\n','\r','\t',' '
        # 將每一行內容根據'\t'符進行切片
        lineArr = line.strip().split('\t')
        # 添加數據(100個元素排成一行)
        dataMat.append([float(lineArr[0]), float(lineArr[1])])
        # 添加標籤(100個元素排成一行)
        labelMat.append(float(lineArr[2]))
    return dataMat, labelMat

def calcEk(oS, k):
    # multiply(a,b)就是個乘法,若是a,b是兩個數組,那麼對應元素相乘
    # .T爲轉置
    fXk = float(np.multiply(oS.alphas, oS.labelMat).T * oS.K[:, k] + oS.b)
    # 計算偏差項
    Ek = fXk - float(oS.labelMat[k])
    # 返回偏差項
    return Ek


def selectJrand(i, m):
    j = i
    while (j == i):
        # uniform()方法將隨機生成一個實數,它在[x, y)範圍內
        j = int(random.uniform(0, m))
    return j


def selectJ(i, oS, Ei):
    # 初始化
    maxK = -1
    maxDeltaE = 0
    Ej = 0
    # 根據Ei更新偏差緩存
    oS.eCache[i] = [1, Ei]
    # 對一個矩陣.A轉換爲Array類型
    # 返回偏差不爲0的數據的索引值
    validEcacheList = np.nonzero(oS.eCache[:, 0].A)[0]
    # 有不爲0的偏差
    if (len(validEcacheList) > 1):
        # 遍歷,找到最大的Ek
        for k in validEcacheList:
            # 不計算k==i節省時間
            if k == i:
                continue
            # 計算Ek
            Ek = calcEk(oS, k)
            # 計算|Ei - Ek|
            deltaE = abs(Ei - Ek)
            # 找到maxDeltaE
            if (deltaE > maxDeltaE):
                maxK = k
                maxDeltaE = deltaE
                Ej = Ek
        # 返回maxK,Ej
        return maxK, Ej
    # 沒有不爲0的偏差
    else:
        # 隨機選擇alpha_j的索引值
        j = selectJrand(i, oS.m)
        # 計算Ej
        Ej = calcEk(oS, j)
    # 返回j,Ej
    return j, Ej


def updateEk(oS, k):
    # 計算Ek
    Ek = calcEk(oS, k)
    # 更新偏差緩存
    oS.eCache[k] = [1, Ek]


def clipAlpha(aj, H, L):
    if aj > H:
        aj = H
    if L > aj:
        aj = L
    return aj

def innerL(i, oS):
    # 步驟1:計算偏差Ei
    Ei = calcEk(oS, i)
    # 優化alpha,設定必定的容錯率
    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)):
        # 使用內循環啓發方式2選擇alpha_j,並計算Ej
        j, Ej = selectJ(i, oS, Ei)
        # 保存更新前的alpha值,使用深層拷貝
        alphaIold = oS.alphas[i].copy()
        alphaJold = oS.alphas[j].copy()
        # 步驟2:計算上界H和下界L
        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
        # 步驟3:計算eta
        eta = 2.0 * oS.K[i, j] - oS.K[i, i] - oS.K[j, j]
        if eta >= 0:
            print("eta >= 0")
            return 0
        # 步驟4:更新alpha_j
        oS.alphas[j] -= oS.labelMat[j] * (Ei - Ej) / eta
        # 步驟5:修剪alpha_j
        oS.alphas[j] = clipAlpha(oS.alphas[j], H, L)
        # 更新Ej至偏差緩存
        updateEk(oS, j)
        if (abs(oS.alphas[j] - alphaJold) < 0.00001):
            print("alpha_j變化過小")
            return 0
        # 步驟6:更新alpha_i
        oS.alphas[i] += oS.labelMat[i] * oS.labelMat[j] * (alphaJold - oS.alphas[j])
        # 更新Ei至偏差緩存
        updateEk(oS, i)
        # 步驟7:更新b_1和b_2:
        b1 = oS.b - Ei - oS.labelMat[i] * (oS.alphas[i] - alphaIold) * oS.K[i, i] - oS.labelMat[j] * (
                    oS.alphas[j] - alphaJold) * oS.K[j, i]
        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]
        # 步驟8:根據b_1和b_2更新b
        if (0 < oS.alphas[i] < oS.C):
            oS.b = b1
        elif (0 < oS.alphas[j] < oS.C):
            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)):
    # 初始化數據結構
    oS = optStruct(np.mat(dataMatIn), np.mat(classLabels).transpose(), C, toler, kTup)
    # 初始化當前迭代次數
    iter = 0
    entrieSet = True
    alphaPairsChanged = 0
    # 遍歷整個數據集alpha都沒有更新或者超過最大迭代次數,則退出循環
    while (iter < maxIter) and ((alphaPairsChanged > 0) or (entrieSet)):
        alphaPairsChanged = 0
        # 遍歷整個數據集
        if entrieSet:
            for i in range(oS.m):
                # 使用優化的SMO算法
                alphaPairsChanged += innerL(i, oS)
                print("全樣本遍歷:第%d次迭代 樣本:%d, alpha優化次數:%d" % (iter, i, alphaPairsChanged))
            iter += 1
        # 遍歷非邊界值
        else:
            # 遍歷不在邊界0和C的alpha
            nonBoundIs = np.nonzero((oS.alphas.A > 0) * (oS.alphas.A < C))[0]
            for i in nonBoundIs:
                alphaPairsChanged += innerL(i, oS)
                print("非邊界遍歷:第%d次迭代 樣本:%d, alpha優化次數:%d" % (iter, i, alphaPairsChanged))
            iter += 1
        # 遍歷一次後改成非邊界遍歷
        if entrieSet:
            entrieSet = False
        # 若是alpha沒有更新,計算全樣本遍歷
        elif (alphaPairsChanged == 0):
            entrieSet = True
        print("迭代次數:%d" % iter)
    # 返回SMO算法計算的b和alphas
    return oS.b, oS.alphas

def testRbf(k1=1.3):
    # 加載訓練集
    dataArr, labelArr = loadDataSet('E:\\數據挖掘\\Machine learning\\代碼\\SVM_Project3\\testSetRBF.txt')
    # 根據訓練集計算b, alphas
    b, alphas = smoP(dataArr, labelArr, 200, 0.0001, 100, ('rbf', k1))
    datMat = np.mat(dataArr)
    labelMat = np.mat(labelArr).transpose()
    # 得到支持向量
    svInd = np.nonzero(alphas.A > 0)[0]
    sVs = datMat[svInd]
    labelSV = labelMat[svInd]
    print("支持向量個數:%d" % np.shape(sVs)[0])
    m, n = np.shape(datMat)
    errorCount = 0
    for i in range(m):
        # 計算各個點的核
        kernelEval = kernelTrans(sVs, datMat[i, :], ('rbf', k1))
        # 根據支持向量的點計算超平面,返回預測結果
        predict = kernelEval.T * np.multiply(labelSV, alphas[svInd]) + b
        # 返回數組中各元素的正負號,用1和-1表示,並統計錯誤個數
        if np.sign(predict) != np.sign(labelArr[i]):
            errorCount += 1
    # 打印錯誤率
    print('訓練集錯誤率:%.2f%%' % ((float(errorCount) / m) * 100))
    # 加載測試集
    dataArr, labelArr = loadDataSet('E:\\數據挖掘\\Machine learning\\代碼\\SVM_Project3\\testSetRBF2.txt')
    errorCount = 0
    datMat = np.mat(dataArr)
    labelMat = np.mat(labelArr).transpose()
    m, n = np.shape(datMat)
    for i in range(m):
        # 計算各個點的核
        kernelEval = kernelTrans(sVs, datMat[i, :], ('rbf', k1))
        # 根據支持向量的點計算超平面,返回預測結果
        predict = kernelEval.T * np.multiply(labelSV, alphas[svInd]) + b
        # 返回數組中各元素的正負號,用1和-1表示,並統計錯誤個數
        if np.sign(predict) != np.sign(labelArr[i]):
            errorCount += 1
    # 打印錯誤率
    print('訓練集錯誤率:%.2f%%' % ((float(errorCount) / m) * 100))


def showDataSet(dataMat, labelMat):
    # 正樣本
    data_plus = []
    # 負樣本
    data_minus = []
    for i in range(len(dataMat)):
        if labelMat[i] > 0:
            data_plus.append(dataMat[i])
        else:
            data_minus.append(dataMat[i])
    # 轉換爲numpy矩陣
    data_plus_np = np.array(data_plus)
    # 轉換爲numpy矩陣
    data_minus_np = np.array(data_minus)
    # 正樣本散點圖(scatter)
    # transpose轉置
    plt.scatter(np.transpose(data_plus_np)[0], np.transpose(data_plus_np)[1])
    # 負樣本散點圖(scatter)
    plt.scatter(np.transpose(data_minus_np)[0], np.transpose(data_minus_np)[1])
    # 顯示
    plt.show()


if __name__ == '__main__':
    testRbf()

2、公式推導

\(在樣本空間中任意點x到超平面(w,b)的距離可寫爲:\)數據結構

\[ r = \frac{|w^Tx + b|}{||w||} \]app

\[推導以下:\\ 取x_0爲任意點x在超平面y= w^Tx + b的投影\\ wx_0 +b = 0 \Longrightarrow |w\vec {xx_0}| = |w\vec r|= ||w||r \\ 另外一方面:|w\vec{xx_0}| = |w(x_0 -x)|=|-b-wx|=|b+wx|\\ \therefore r = \frac{|w^Tx + b|}{||w||}\]
\[ \hat r=yf(x)=y(w^Tx + b)\\ \tilde r = ry = y\frac{|w^Tx + b|}{||w||}=\frac {\hat r}{||w||}\\ \\定義\hat r爲函數間隔,\tilde r爲幾何間隔 \]dom

\[ L(\boldsymbol{w}, b, \boldsymbol{\alpha})=\frac{1}{2}\|\boldsymbol{w}\|^{2}+\sum_{i=1}^{m} \alpha_{i}\left(1-y_{i}\left(\boldsymbol{w}^{\top} \boldsymbol{x}_{i}+b\right)\right) \]機器學習

\[原問題爲極小極大問題\min_{\boldsymbol{w,b}}\quad \max_{\boldsymbol{\alpha}}\quad L(w,b,\alpha)\\ 轉化爲極大極小問題\max_{\boldsymbol{\alpha}}\quad \min_{\boldsymbol{w,b}}\quad L(w,b,\alpha)\]函數

\[推導以下:\\ 目標函數:min\frac{1}{2}||w||^2\\ 約束條件:y_i(w^Tx_i + b) \geq 1\\ \therefore 對每一個在y_i(w^Tx_i+b)-1的i乘以\alpha_i\\ \therefore L(\boldsymbol{w}, b, \boldsymbol{\alpha})=\frac{1}{2}\|\boldsymbol{w}\|^{2}+\sum_{i=1}^{m} \alpha_{i}\left(1-y_{i}\left(\boldsymbol{w}^{\top} \boldsymbol{x}_{i}+b\right)\right)\]學習

\[在其餘的機器學習上述公式是L(\boldsymbol{w}, b, \boldsymbol{\alpha})=\frac{1}{2}\|\boldsymbol{w}\|^{2}-\sum_{i=1}^{m} \alpha_{i}\left(y_{i}\left(\boldsymbol{w}^{\top} \boldsymbol{x}_{i}+b\right)-1\right),二者等價\]
\[ \begin{aligned} w &= \sum_{i=1}^m\alpha_iy_i\boldsymbol{x}_i \\ 0 &=\sum_{i=1}^m\alpha_iy_i \end{aligned} \]

\[推導以下:\\ \begin{aligned} L(\boldsymbol{w},b,\boldsymbol{\alpha}) &= \frac{1}{2}||\boldsymbol{w}||^2+\sum_{i=1}^m\alpha_i(1-y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)) \\ & = \frac{1}{2}||\boldsymbol{w}||^2+\sum_{i=1}^m(\alpha_i-\alpha_iy_i \boldsymbol{w}^T\boldsymbol{x}_i-\alpha_iy_ib)\\ & =\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}+\sum_{i=1}^m\alpha_i -\sum_{i=1}^m\alpha_iy_i\boldsymbol{w}^T\boldsymbol{x}_i-\sum_{i=1}^m\alpha_iy_ib \end{aligned}\]

\[\frac {\partial L}{\partial \boldsymbol{w}}=\frac{1}{2}\times2\times\boldsymbol{w} + 0 - \sum_{i=1}^{m}\alpha_iy_i \boldsymbol{x}_i-0= 0 \Longrightarrow \boldsymbol{w}=\sum_{i=1}^{m}\alpha_iy_i \boldsymbol{x}_i\]

\[\frac {\partial L}{\partial b}=0+0-0-\sum_{i=1}^{m}\alpha_iy_i=0 \Longrightarrow \sum_{i=1}^{m}\alpha_iy_i=0\]
\[ \begin{aligned} \max_{\boldsymbol{\alpha}} & \sum_{i=1}^m\alpha_i - \frac{1}{2}\sum_{i = 1}^m\sum_{j=1}^m\alpha_i \alpha_j y_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j \\ s.t. & \sum_{i=1}^m \alpha_i y_i =0 \\ & \alpha_i \geq 0 \quad i=1,2,\dots ,m \end{aligned} \]
\(推導以下:\\計算拉格朗日函數,即將求得的兩個公式代入\)

\[\begin{aligned} \min_{\boldsymbol{w},b} L(\boldsymbol{w},b,\boldsymbol{\alpha}) &=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}+\sum_{i=1}^m\alpha_i -\sum_{i=1}^m\alpha_iy_i\boldsymbol{w}^T\boldsymbol{x}_i-\sum_{i=1}^m\alpha_iy_ib \\ &=\frac {1}{2}\boldsymbol{w}^T\sum _{i=1}^m\alpha_iy_i\boldsymbol{x}_i-\boldsymbol{w}^T\sum _{i=1}^m\alpha_iy_i\boldsymbol{x}_i+\sum _{i=1}^m\alpha_ i -b\sum _{i=1}^m\alpha_iy_i \\ & = -\frac {1}{2}\boldsymbol{w}^T\sum _{i=1}^m\alpha_iy_i\boldsymbol{x}_i+\sum _{i=1}^m\alpha_i -b\sum _{i=1}^m\alpha_iy_i \end{aligned}\]

\[\begin{aligned} \min_{\boldsymbol{w},b} L(\boldsymbol{w},b,\boldsymbol{\alpha}) &= -\frac {1}{2}\boldsymbol{w}^T\sum _{i=1}^m\alpha_iy_i\boldsymbol{x}_i+\sum _{i=1}^m\alpha_i \\ &=-\frac {1}{2}(\sum_{i=1}^{m}\alpha_iy_i\boldsymbol{x}_i)^T(\sum _{i=1}^m\alpha_iy_i\boldsymbol{x}_i)+\sum _{i=1}^m\alpha_i \\ &=-\frac {1}{2}\sum_{i=1}^{m}\alpha_iy_i\boldsymbol{x}_i^T\sum _{i=1}^m\alpha_iy_i\boldsymbol{x}_i+\sum _{i=1}^m\alpha_i \\ &=\sum _{i=1}^m\alpha_i-\frac {1}{2}\sum_{i=1 }^{m}\sum_{j=1}^{m}\alpha_i\alpha_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j \end{aligned}\]
\[ \begin{aligned} & \min_{\boldsymbol{\alpha}}\frac{1}{2}\sum_{i = 1}^m\sum_{j=1}^m\alpha_i \alpha_j y_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j- \sum_{i=1}^m\alpha_i\\ & s.t. \sum_{i=1}^m \alpha_i y_i =0 \\ & \alpha_i \geq 0 \quad i=1,2,\dots ,m \end{aligned} \]
\[在原\max_{\boldsymbol{\alpha}}\quad \min_{\boldsymbol{w,b}}\quad L(w,b,\alpha)加負號,一樣轉化爲約束最優化問題,爲了求解最優解\alpha^*\]
\[ 計算獲得\\w^* = \sum_{i =1}^m{\alpha_i}^*y_ix_i\\ b^* = y_i -\sum_{i=1}^m{\alpha_i}^*y_i(x_ix_j)\\ 分離獲得超平面:\\ w^*x+ b^* =0\\ 分類決策函數:\\ f(x) =sign(w^*x+b^*) \]

\[引入鬆弛因子\xi_i的目標函數以下:\\\]
\[ \begin{aligned} & \min_{\boldsymbol{w,b,\xi}}\frac{1}{2}||w||^2 +C\sum_{i = 1}^m\xi_i\\ s.t. & y_i(w.x_i+b)\geq1-\xi_i, i=1,2,\dots ,m \\ & \xi_i \geq 0 \quad i=1,2,\dots ,m \end{aligned} \]

\[同理如上式,構造拉格朗日函數L,再對w,b,\xi分別求偏導,再代入L\]
\[ \begin{aligned} L(\boldsymbol{w},b,\boldsymbol{\alpha},\boldsymbol{\xi},\boldsymbol{\mu}) &= \frac{1}{2}||\boldsymbol{w}||^2+C\sum_{i=1}^m \xi_i+\sum_{i=1}^m \alpha_i(1-\xi_i-y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b))-\sum_{i=1}^m\mu_i \xi_i \end{aligned} \]
\[對w,b,\xi求偏導\]
\[ \begin{aligned} w &= \sum_{i=1}^m\alpha_iy_i\boldsymbol{x}_i \\ 0 &=\sum_{i=1}^m\alpha_iy_i\\ C & = a_i+\mu_i \end{aligned} \]

\[代入L\]
\[ \begin{aligned} \min_{\boldsymbol{w},b,\boldsymbol{\xi}}L(\boldsymbol{w},b,\boldsymbol{\alpha},\boldsymbol{\xi},\boldsymbol{\mu}) &= \frac{1}{2}||\boldsymbol{w}||^2+C\sum_{i=1}^m \xi_i+\sum_{i=1}^m \alpha_i(1-\xi_i-y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b))-\sum_{i=1}^m\mu_i \xi_i \\ &=\frac{1}{2}||\boldsymbol{w}||^2+\sum_{i=1}^m\alpha_i(1-y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b))+C\sum_{i=1}^m \xi_i-\sum_{i=1}^m \alpha_i \xi_i-\sum_{i=1}^m\mu_i \xi_i \\ & = -\frac {1}{2}\sum_{i=1}^{m}\alpha_iy_i\boldsymbol{x}_i^T\sum _{i=1}^m\alpha_iy_i\boldsymbol{x}_i+\sum _{i=1}^m\alpha_i +\sum_{i=1}^m C\xi_i-\sum_{i=1}^m \alpha_i \xi_i-\sum_{i=1}^m\mu_i \xi_i \\ & = -\frac {1}{2}\sum_{i=1}^{m}\alpha_iy_i\boldsymbol{x}_i^T\sum _{i=1}^m\alpha_iy_i\boldsymbol{x}_i+\sum _{i=1}^m\alpha_i +\sum_{i=1}^m (C-\alpha_i-\mu_i)\xi_i \\ &=\sum _{i=1}^m\alpha_i-\frac {1}{2}\sum_{i=1 }^{m}\sum_{j=1}^{m}\alpha_i\alpha_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j \end{aligned} \]
\[再求\alpha極大\max\]
\[ \begin{aligned} &\max_{\alpha}\sum _{i=1}^m\alpha_i-\frac {1}{2}\sum_{i=1 }^{m}\sum_{j=1}^{m}\alpha_i\alpha_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j\\ 轉化爲\\ &\min_{\alpha}\frac {1}{2}\sum_{i=1 }^{m}\sum_{j=1}^{m}\alpha_i\alpha_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j-\sum _{i=1}^m\alpha_i\\ &s.t.\sum_{i=1}^m \alpha_i y_i=0 \\ &0 \leq\alpha_i \leq C \quad i=1,2,\dots ,m \end{aligned} \]
\[求最優解\alpha^*\]
\[ 計算獲得\\w^* = \sum_{i =1}^m{\alpha_i}^*y_ix_i\\ b^* = (\max_{i: y_i =1} w^*.x_i + \min_{i: y_i =-1} w^x* +x_i)/2\\ 分離獲得超平面:\\ w^*x+ b^* =0\\ 分類決策函數:\\ f(x) =sign(w^*x+b^*) \]

\[ \left\{\begin{array}{l} {\alpha_{i}\left(f\left(\boldsymbol{x}_{i}\right)-y_{i}-\epsilon-\xi_{i}\right)=0} \\ {\hat{\alpha}_{i}\left(y_{i}-f\left(\boldsymbol{x}_{i}\right)-\epsilon-\hat{\xi}_{i}\right)=0} \\ {\alpha_{i} \hat{\alpha}_{i}=0, \xi_{i} \hat{\xi}_{i}=0} \\ {\left(C-\alpha_{i}\right) \xi_{i}=0,\left(C-\hat{\alpha}_{i}\right) \hat{\xi}_{i}=0} \end{array}\right. \]
\[推導以下:\\\]
\[ \left\{\begin{array}{l}2{f\left(\boldsymbol{x}_{i}\right)-y_{i}-\epsilon-\xi_{i} \leq 0 }  \\ 3{y_{i}-f\left(\boldsymbol{x}_{i}\right)-\epsilon-\hat{\xi}_{i} \leq 0 } \\ 4{-\xi_{i} \leq 0} \\5{-\hat{\xi}_{i} \leq 0}6\end{array}\right. \]

\[ \left\{\begin{array}{l} {\alpha_i\left(f\left(\boldsymbol{x}_{i}\right)-y_{i}-\epsilon-\xi_{i} \right) = 0 } \\ {\hat{\alpha}_i\left(y_{i}-f\left(\boldsymbol{x}_{i}\right)-\epsilon-\hat{\xi}_{i} \right) = 0 } \\ {-\mu_i\xi_{i} = 0 \Rightarrow \mu_i\xi_{i} = 0 } \\ {-\hat{\mu}_i \hat{\xi}_{i} = 0 \Rightarrow \hat{\mu}_i \hat{\xi}_{i} = 0 } \end{array}\right. \]

\[\because\begin{aligned} \mu_i=C-\alpha_i \\ \hat{\mu}_i=C-\hat{\alpha}_i \end{aligned}\]
\[ \left\{\begin{array}{l} {\alpha_i\left(f\left(\boldsymbol{x}_{i}\right)-y_{i}-\epsilon-\xi_{i} \right) = 0 } \\ {\hat{\alpha}_i\left(y_{i}-f\left(\boldsymbol{x}_{i}\right)-\epsilon-\hat{\xi}_{i} \right) = 0 } \\ {(C-\alpha_i)\xi_{i} = 0 } \\ {(C-\hat{\alpha}_i) \hat{\xi}_{i} = 0 } \end{array}\right. \]
\[前面硬間隔與軟間隔均處理線性問題,而對非線性問題須要將低維空間映射到高維空間,引入核函數\]

\[多項式核函數\]
\[ k(\vec x,\vec y)= (\vec x,\vec y +c)^2\\ =(\vec x, \vec y)^2+2c\vec x\vec y+c^2\\ =\sum_{i =1}^n \sum_{j=1}^m(x_ix_j)(y_iy_j)+\sum_{i=1}^m(\sqrt {2c}x_i \sqrt{2cy_i})+c^2 \]
\(高斯核函數\)
\[ k(\vec x_1,\vec x_2) = e^-\frac{x_1^2+x_2^2}{2\sigma^2}(1+\frac {x_1 x_2}{\sigma^2}+\frac{x_1^2+x_2^2}{2\sigma^2 \sigma^2}+...+\frac{x_1^n+x_2^n}{n!\sigma^n\sigma^n}) \]

3、練習題目

3.1 給定三個數據點,正例點\(x_1 = (3, 3)^T\), \(x_2 = (4, 3)^T\),負例點\(x_3 = (1, 1)^T\),求線性可分SVM

3.2 SVM能否用於多分類

3.3 SVM和Logistic迴歸的比較

3.4 核函數是什麼?高斯核映射到無窮維是怎麼回事?

3.5 如何理解SVM的損失函數?

3.6 使用高斯核函數,請描述SVM的參數C和 \(\sigma\) 對分類器的影響

3.7 比較感知機的對偶性形式與線性可分支持向量機的對偶形式

3-8 證實內積的正整數冪函數:

\[ K(x,z) = (x,z)^p\\ 是正定核函數,此處p爲正整數,x,z爲R \]

3.9 線性支持向量機還可定義爲如下形式:

\[ \begin{aligned} \min_{\boldsymbol{w,b,\xi}}\quad \frac{1}{2}||w||^2+C\sum_{i=1}^N{\xi_i}^2\\ s.t.\quad y_i(\boldsymbol w.{x_i}+b)\geq 1-\xi_i, i= 1,2,...,N\\ {\xi}_i \geq 0, i=1, 2,...,N \end{aligned}\\ 求其對偶形式 \]

3.10 給定數據點,正例點\(x_1 = (1, 2)^T\), \(x_2 = (2, 3)^T\), \(x_3 = (1, 1)^T,\)負例點\(x_4 = (1, 1)^T\),\(x_5 = (1, 1)^T\),求最大間隔分離超平面和分類決策函數,並在圖上畫出分離超平面,間隔邊界及支持向量

3.11 分析SVM對噪聲敏感的緣由

3.12 使用核技巧推廣對數概率迴歸,產生覈對率迴歸

3.13 給出式(6.52)的KKT條件

3.13 討論線性判別分析與線性核支持向量機在何種條件等價

4、參看文獻

[1] 《機器學習》 鄒博

[2] 《SVM的三重境界》 July

[3] 《pumpkin-book》 Datawhale

[4] 《機器學習》周志華

[5] 《機器學習實戰》Peter

[6] 《統計學習方法》李航,清華大學出版社,2012

[7] 《機器學習算法精講》 秦曾昌,2018

相關文章
相關標籤/搜索