支持向量機SVM代碼示例

Tensorflow

代碼來源:https://www.cnblogs.com/vipyoumay/p/7560061.html
本人新添加了很多註釋,方便理解代碼
我一直想將這個代碼用於多維特徵的二分類,看了挺長時間。

添加多維特徵,對於SVM結構定義的影響就是,x_data、A的維度要對應到特徵的維度。
對於求解斜率,多維的A生成多維元素,在下還未徹底理解SMO算法的多維求解方案,所以沒有深究。

上面那篇博客作爲一個示例性的講解,對於SMO算法,只是選擇的二維作爲示例,沒有提供N維特徵對應的斜率求解方式,所以這裏僅作爲一個加深對SVM理解的方案,代碼本身不太實用。

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets

sess = tf.Session()

# 加載數據
# iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)]
iris = datasets.load_iris()
# 選取數據集中任意兩維特徵作爲訓練特徵
x_vals = np.array([[x[0], x[3]] for x in iris.data]) 
# 將原始數據標籤的0、1(或-1)轉換爲1、-1
y_vals = np.array([1 if y == 0 else -1 for y in iris.target])

# 分離訓練和測試集
# 在數據集中隨機抽取80%作爲訓練集
train_indices = np.random.choice(len(x_vals),
                                 round(len(x_vals)*0.8),
                                 replace=False)
# 測試集=原始數據集-訓練集         
test_indices = np.array(list(set(range(len(x_vals))) - set(train_indices)))
# 分配訓練集、測試集對應的數據特徵、標籤
x_vals_train = x_vals[train_indices]
x_vals_test = x_vals[test_indices]
y_vals_train = y_vals[train_indices]
y_vals_test = y_vals[test_indices]

batch_size = 100

# 初始化feedin
# 由於輸入特徵爲兩維特徵,所以輸入的維度是[None, 2]
x_data = tf.placeholder(shape=[None, 2], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)

# 創建變量
# svm算法求解的是最大間隔超平面,超平面的方程爲y=wx+b,這裏A代表w
A = tf.Variable(tf.random_normal(shape=[2, 1]))
b = tf.Variable(tf.random_normal(shape=[1, 1]))

# 定義線性模型
# 定義了超平面方程y=xA-b,即y=wx+(-b)
model_output = tf.subtract(tf.matmul(x_data, A), b)

# Declare vector L2 'norm' function squared
# 定義了L2範數,A中元素的平方和
l2_norm = tf.reduce_sum(tf.square(A))

# Loss = max(0, 1-pred*actual) + alpha * L2_norm(A)^2
alpha = tf.constant([0.01])
# 損失函數的前半部分,對模型輸出(預測)的每個y與真實值y求積,預測正確時乘積爲1,預測錯誤乘積爲-1。
# 用1減去這個乘積,然後求其與0的最大值,預測正確時最大值爲0,預測錯誤時最大值爲2。
# 最後對所有預測值y的計算結果求平均,計算平均損失。
classification_term = tf.reduce_mean(tf.maximum(0., tf.subtract(1., tf.multiply(model_output, y_target))))
# 損失函數後半部分爲alpha與L2範數的乘積,alpha爲L2正則化的懲罰係數
loss = tf.add(classification_term, tf.multiply(alpha, l2_norm))

# 採用學習率恆定的梯度下降優化器,訓練目標爲最小化損失
my_opt = tf.train.GradientDescentOptimizer(0.01)
train_step = my_opt.minimize(loss)

init = tf.global_variables_initializer()
sess.run(init)

# Training loop
loss_vec = []
train_accuracy = []
test_accuracy = []
for i in range(20000):
	# 隨機選取每一個batch的數據
    rand_index = np.random.choice(len(x_vals_train), size=batch_size)
    rand_x = x_vals_train[rand_index]
    # 批量取出的數據標籤shape=[batch,],需轉置爲shape=[batch,1]才能與定義的y_target一致
    rand_y = np.transpose([y_vals_train[rand_index]])
    sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})

# 定義的A的shape=[2, 1],訓練完畢會生成2個值分別爲a1、a2
[[a1], [a2]] = sess.run(A)
# 定義的b的shape=[1, 1],訓練完畢會生成1個值b
[[b]] = sess.run(b)
# 求斜率、截距,公式來自SMO算法推導
slope = -a2/a1
y_intercept = b/a1
best_fit = []

# 根據斜率、截距以及原始數據,計算超平面上點的座標,用於可視化
x1_vals = [d[1] for d in x_vals]

for i in x1_vals:
    best_fit.append(slope*i+y_intercept)


# Separate I. setosa
# 基於最開始選取的兩維特徵,分別作爲xoy座標系的x軸、y軸,生成可視化圖標
setosa_x = [d[1] for i, d in enumerate(x_vals) if y_vals[i] == 1]
setosa_y = [d[0] for i, d in enumerate(x_vals) if y_vals[i] == 1]
not_setosa_x = [d[1] for i, d in enumerate(x_vals) if y_vals[i] == -1]
not_setosa_y = [d[0] for i, d in enumerate(x_vals) if y_vals[i] == -1]

plt.plot(setosa_x, setosa_y, 'o', label='I. setosa')
plt.plot(not_setosa_x, not_setosa_y, 'x', label='Non-setosa')
plt.plot(x1_vals, best_fit, 'r-', label='Linear Separator', linewidth=3)
plt.ylim([0, 10])
plt.legend(loc='lower right')
plt.title('Sepal Length vs Pedal Width')
plt.xlabel('Pedal Width')
plt.ylabel('Sepal Length')
plt.show()

在這裏插入圖片描述

sklearn

來源:https://www.jianshu.com/p/731610dca805
這裏用上工具包,就方便了許多,SMO算法的多維求解方式也是內置的,有時間可以去了解一下。

import sklearn.svm as sk_svm
model = sk_svm.SVC(C=1.0,kernel='rbf',gamma='auto')
model.fit(X_train,y_train)
acc=model.score(X_test,y_test) #根據給定數據與標籤返回正確率的均值
print('SVM模型評價:',acc)

參數說明:

  • C:誤差項的懲罰參數C
  • kernel:核函數選擇 默認:rbf(高斯核函數),
    • 可選:‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’
  • gamma: 核相關係數。
    • 浮點數,If gamma is ‘auto’ then 1/n_features will be used instead.點將被拆分。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章