7 支持向量机SMO算法(python代码)

原理参考:https://zhuanlan.zhihu.com/p/77750026
SMO算法python代码
公式参考统计学习方法第7章

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import math

def create_data():
    iris = load_iris()
    df=pd.DataFrame(iris.data,columns=iris.feature_names)
    df['label']=iris.target
    df.columns=['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
    data=np.array(df.iloc[:100,[0,1,-1]])
    for i in range(len(data)):
        if data[i,-1]==0:
            data[i,-1]=-1
    return data[:,:2], data[:,-1]

X,y=create_data()
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)

# SMO算法
class SVM:
#     定义最大迭代次数,核函数
    def __init__(self, max_iter, kernel='linear'):
        self.max_iter = max_iter
        self._kernel = kernel
#     m样本量,n维度,X样本, Y样本类别,b,alpha拉格朗日乘子,E,C
    def init_args(self, features, labels):
        self.m, self.n = features.shape
        self.X = features
        self.Y = labels
        self.b = 0.0
        self.alpha = np.ones(self.m)
        
        # Ei是g(x)预测值-实际值,保存至列表
        self.E = [self._E(i) for i in range(self.m)]
        # 惩罚参数
        self.C=1.0 
 
    # 核函数
    def kernel(self,x1,x2):
        if self._kernel=='linear': #线性分类器 k(x,y)=x*y
            return sum([x1[k]*x2[k] for k in range(self.n)])  
        elif self._kernel=='poly':
            return (sum([x1[k]*x2[k] for k in range(self.n)])+1)**2  #d阶多项式分类器 k(x,y)={(x*y)+1}d
        return 0

    def _KKT(self, i):  #p147   7.111~7.113
        y_g = self._g(i)*self.Y[i]
        if self.alpha[i]==0:
            return y_g >=1
        elif 0= 0:
                j = min(range(self.m), key=lambda x: self.E[x])
            else:
                j = max(range(self.m), key=lambda x: self.E[x])
            return i, j
    
    def _compare(self,_alpha, L, H):  #7.108
        if _alpha > H:
            return H
        elif _alpha 0 else -1

    def score(self, X_test, y_test):
        right_count = 0
        for i in range(len(X_test)):
            result = self.predict(X_test[i])
            if result == y_test[i]:
                right_count += 1
        return right_count / len(X_test)

svm = SVM(max_iter=200,kernel='poly')
svm.fit(X_train, y_train)
svm.score(X_test, y_test)

直接调用sklearn函数
from sklearn.svm import SVC
clf = SVC()
clf.fit(X_train, y_train)
clf.score(X_test, y_test)

你可能感兴趣的:(7 支持向量机SMO算法(python代码))