Featured image of post 支持向量机及SMO

支持向量机及SMO

实现预测,数据集规模为150*4,(标签不计)

保姆级笔记-详细剖析SMO算法中的知识点 - 知乎

软间隔支持向量机(soft-margin SVM)详细推导过程 - 知乎

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import pandas as pd
import numpy as np

# 数据加载和预处理
data = pd.read_csv("iris.txt", header=None)
name_list = ["setosa", "versicolor", "virginica"]

# 标签编码
def safe_index(x, name_list):
    try:
        return name_list.index(x)
    except ValueError:
        return -1

def data_process(X,y):
    index=np.arange(0,len(y))
    np.random.shuffle(index)
    return X[index,:],y[index]

def split_dataset(X, y, train_ratio=0.8, random_state=None):
    if random_state is not None:
        np.random.seed(random_state)
    n_samples = X.shape[0]
    indices = np.arange(n_samples)
    np.random.shuffle(indices)
    X_shuffled = X[indices]
    y_shuffled = y[indices]
    train_size = int(train_ratio * n_samples)
    X_train, X_predict = X_shuffled[:train_size], X_shuffled[train_size:]
    y_train, y_predict = y_shuffled[:train_size], y_shuffled[train_size:]
    return X_train/10, y_train, X_predict/10, y_predict

data[4] = data[4].apply(lambda x: safe_index(x, name_list))
data = data[data[4] != -1]  # 过滤掉无效数据
print(data)

# 提取特征和标签
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
y = np.where(y == 0, -1, 1)  # 将标签转换为 -1 和 1
x_train, y_train, x_test, y_test = split_dataset(X, y)


class SVM:
    def __init__(self,x_train,y_train,x_test,y_test,C=1,max_iter=100,tol=0.001):
        self.X=x_train
        self.y=y_train
        self.C=C
        self.max_iter=max_iter
        self.a=np.zeros_like(self.y)
        self.b=0
        self.K_matrix=self.compute_k_matrix()
        self.tol=tol
        self.X_test=x_test
        self.y_test=y_test

    def compute_k_matrix(self):
        n_samples=self.X.shape[0]
        K=np.zeros((n_samples,n_samples))
        for i in range(n_samples):
            K[i,:]=np.exp(-np.linalg.norm(self.X[i,:]-self.X,axis=1))
        return K
    
    def f(self,index):
        K=self.K_matrix[index,:]
        return np.sum(self.a*self.y*K)+self.b
    
    def choose_index(self):
        indices=np.where((self.a>0) & (self.a<self.C))[0]
        if len(indices)==0:
            indices=np.arange(len(self.y))
        index1=np.random.choice(indices)
        E=np.array([self.compute_E(i) for i in range(len(self.y))])
        delta_E=np.abs(E-self.compute_E(index1))
        index2=np.argmax(delta_E)
        return index1,index2
    
    def compute_E(self, index):
        return self.f(index) - self.y[index]

    def smo(self):
        iter_num=0
        while iter_num<self.max_iter:
            max_inner_iter = 100
            inner_iter = 0
            while inner_iter<max_inner_iter:
                index1,index2=self.choose_index()
                a1_old,a2_old=self.a[index1],self.a[index2]
                y1,y2=self.y[index1],self.y[index2]
                if y1!=y2:
                    L=max(0,a2_old-a1_old)
                    H=min(self.C,self.C+a2_old-a1_old)
                else:
                    L = max(0, a1_old + a2_old - self.C)
                    H = min(self.C, a1_old + a2_old)
                eta=self.K_matrix[index1,index1]+self.K_matrix[index2,index2]-2*self.K_matrix[index1,index2]
                if eta <= 1e-10:
                    continue
                a2_new=self.a[index2]+self.y[index2]*(self.compute_E(index1)-self.compute_E(index2))/eta
                if L == H:
                    continue
                a2_new=np.clip(a2_new,L,H)
                a1_new=self.a[index1]+self.y[index1]*self.y[index2]*(self.a[index2]-a2_new)
                self.a[index1],self.a[index2]=a1_new,a2_new
                b1 = self.b - self.compute_E(index1) \
                    - self.y[index1] * (a1_new - a1_old) * self.K_matrix[index1, index1] \
                    - self.y[index2] * (a2_new - a2_old) * self.K_matrix[index1, index2]
                b2 = self.b - self.compute_E(index2) \
                    - self.y[index1] * (a1_new - a1_old) * self.K_matrix[index1, index2] \
                    - self.y[index2] * (a2_new - a2_old) * self.K_matrix[index2, index2]
                if 0 < a1_new < self.C:
                    self.b = b1
                elif 0 < a2_new < self.C:
                    self.b = b2
                else:
                    self.b = (b1 + b2) / 2
                inner_iter+=1
                if np.abs(a1_new - a1_old)<self.tol and np.abs(a2_new - a2_old)<self.tol:
                    break
            if iter_num%10==0:
                print(f"第{iter_num}轮,预测准确率为{round(self.calculate_accuracy(), 3)}")
                print(f"L:{L},H:{H},eta:{eta}")
                print(f"a[:20]:{self.a[:20]},b:{self.b}")
            iter_num+=1
    
    def predict(self,X):
        K=np.exp(-np.linalg.norm(self.X-X,axis=1))
        if  np.sum(self.a*self.y*K)+self.b>=0:
            return 1
        else:
            return -1
    def calculate_accuracy(self):
        correct_predictions = 0
        n_samples = len(self.y_test)
        for i in range(n_samples):
            y_pred = self.predict(self.X_test[i])  # 对单个样本预测
            if y_pred == y_test[i]:
                correct_predictions += 1
        accuracy = correct_predictions / n_samples
        return accuracy
    
if __name__=="__main__":
    print(x_train)
    svm=SVM(x_train,y_train,x_test,y_test)
    svm.smo()
    y_pred=np.zeros_like(y_test)
    for i in range(len(svm.X_test)):
        y_pred[i]=svm.predict(svm.X_test[i,:])
    print(f"预测值{y_pred}")
    print(f"真实值{y_test}")
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计