SVM代码实现--Tensorflow部分--潘登同学的机器学习笔记
python版本--3.6 ; Tensorflow版本--1.15.0 ;编辑器--Pycharm
@
软间隔SVM
- 任务:
把iris数据集的setosa与非setosa区分开
- 模型:
我们这里采用的模型是SVM中无约束优化的SVM模型
- SVM的损失函数(要加正则项) $$ \min_{w,b}\sum_{i=1}^m[1-y(w^Tx+b)]_+ + \lambda||w||^2 $$
不详细介绍代码了, 直接看代码
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from tensorflow.python.framework import ops
ops.get_default_graph()
sess = tf.Session()
iris = datasets.load_iris()
X = np.array([x[2:4] for x in iris.data])
Y = np.array([1 if y == 0 else -1 for y in iris.target])
# 分离训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, Y)
# 声明学习率, 批量大小, 占位符和模型变量
learning_rate = 0.01
batch_size = 50
x_data = tf.placeholder(shape=[None, 2], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
W = tf.Variable(tf.random_normal(shape=[2, 1]))
b = tf.Variable(tf.random_normal(shape=[1, 1]))
# 定义线性模型
model_output = tf.add(tf.matmul(x_data, W), b)
# 声明L2损失函数, 其为批量损失的平均值, 初始化变量, 声明优化器
L2_norm_square = tf.square(tf.reduce_sum(tf.square(W)))
lambda_1 = tf.constant([0.01])
Loss = tf.add(tf.reduce_sum(tf.maximum(0., tf.subtract(1., tf.multiply(y_target, model_output)))),
tf.multiply(lambda_1, L2_norm_square))
init = tf.global_variables_initializer()
my_opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_step = my_opt.minimize(Loss)
sess.run(init)
# 迭代遍历, 并在随机选择的数据上进行模型训练, 迭代1000次
for i in range(1000):
rand_index = np.random.choice(len(X_train), size=batch_size)
rand_x = X_train[rand_index]
rand_y = np.transpose([y_train[rand_index]])
# 目标:最优化损失
sess.run(train_step, feed_dict={x_data:rand_x,
y_target:rand_y})
# 对测试集进行分类
test_result = np.array(sess.run(model_output, feed_dict={x_data:X_test})).reshape(-1)
test_result = [1 if i > 0 else -1 for i in test_result]
print("测试集分类的正确率:%d %%" %((test_result==y_test).sum()/len(y_test)*100))
# 绘制图像
[[a1], [a2]] = sess.run(W)
[[b1]] = sess.run(b)
slope = -a1 / a2
y_intercept = -b1 / a2
best_fit = slope*X[:,1]+y_intercept
setosa_x = [d[1] for i,d in enumerate(X) if Y[i] == 1]
setosa_y = [d[0] for i,d in enumerate(X) if Y[i] == 1]
not_setosa_x = [d[1] for i,d in enumerate(X) if Y[i] == -1]
not_setosa_y = [d[0] for i,d in enumerate(X) if Y[i] == -1]
plt.plot(setosa_x, setosa_y, 'o', label="setosa")
plt.plot(not_setosa_x, not_setosa_y, 'x', label="not-setosa")
plt.plot(X[:,1], best_fit, 'r-', label='Linear Separator', linewidth=3)
plt.ylim([0, 10])
plt.legend(loc='lower right')
plt.title('Petal Length vs Petal Width')
plt.xlabel('Petal Width')
plt.ylabel('Petal Length')
plt.show()
非线性SVM
- 模型: $$ \min_{\alpha}\frac{1}{2}\sum_{i=1,j=1}^m\alpha_i\alpha_jy_iy_jK(x_i, x_j) - \sum_{i=1}^m\alpha_i\ $$
我们这里用的核函数是高斯核 $$ K(x_i,x_j) = e^{-gamma||x_i-x_j||^2} $$
采用不同的gamma来进行模型训练, 并绘制分割平面
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from tensorflow.python.framework import ops
ops.get_default_graph()
sess = tf.Session()
iris = datasets.load_iris()
X = np.array([x[2:4] for x in iris.data])
Y = np.array([1 if y == 0 else -1 for y in iris.target])
# 声明学习率, 批量大小, 占位符和模型变量
learning_rate = 0.01
batch_size = 50
x_data = tf.placeholder(shape=[None, 2], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
prediction_grid = tf.placeholder(shape=[None, 2], dtype=tf.float32)
# 为SVM创建变量
b = tf.Variable(tf.random_normal(shape=[1, batch_size]))
# 绘制点和网格
plt.figure(figsize=(16,16))
for n, g in enumerate([1., 10., 25., 100.]):
# 声明高斯核函数
gamma = tf.constant([-g])
sq_dists = tf.multiply(2., tf.matmul(x_data, tf.transpose(x_data)))
Kernel = tf.exp(tf.multiply(gamma, tf.abs(sq_dists)))
# 计算SVM模型
first_term = tf.reduce_sum(b)
b_vec_cross = tf.matmul(tf.transpose(b), b)
y_target_cross = tf.matmul(y_target, tf.transpose(y_target))
second_term = tf.reduce_sum(tf.multiply(Kernel, tf.multiply(b_vec_cross, y_target_cross)))
loss = tf.negative(tf.subtract(first_term, second_term))
# 创建一个预测核函数
rA = tf.reshape(tf.reduce_sum(tf.square(x_data), 1), [-1, 1])
rB = tf.reshape(tf.reduce_sum(tf.square(prediction_grid), 1), [-1, 1])
pred_sq_dist = tf.add(tf.subtract(rA, tf.multiply(2., tf.matmul(x_data, tf.transpose(prediction_grid)))),
tf.transpose(rB))
pred_kernel = tf.exp(tf.multiply(gamma, tf.abs(pred_sq_dist)))
# 声明一个准确度函数, 其为正确分类的数据点的百分比
predictions_output = tf.matmul(tf.multiply(tf.transpose(y_target), b), pred_kernel)
prediction = tf.sign(predictions_output - tf.reduce_mean(predictions_output))
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.squeeze(prediction), tf.squeeze(y_target)), tf.float32))
# 声明优化器
my_opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_step = my_opt.minimize(loss)
# 初始化变量
init = tf.global_variables_initializer()
sess.run(init)
# 训练模型
loss_vec = []
batch_accuracy = []
for i in range(300):
rand_index = np.random.choice(len(X), size=batch_size)
rand_x = X[rand_index]
rand_y = np.transpose([Y[rand_index]])
# 目标:最优化损失
sess.run(train_step, feed_dict={x_data: rand_x,
y_target: rand_y})
# 更新loss值
temp_loss = sess.run(loss, feed_dict={x_data: rand_x,
y_target: rand_y})
loss_vec.append(temp_loss)
acc_temp = sess.run(accuracy, feed_dict={x_data: rand_x,
y_target: rand_y,
prediction_grid: rand_x})
batch_accuracy.append(acc_temp)
# 每50次打印
if (i + 1) % 50 == 0:
print('Step:', i + 1)
print('Loss为:', temp_loss)
# 创建一个网格来绘制点
# 为了绘制决策边界, 创建一个数据点(x,y)的网络来评估预测函数
x_min, x_max = X[:,0].min() - 1, X[:,0].max() + 1
y_min, y_max = X[:,1].min() - 1, X[:,1].max() + 1
xx,yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
grid_points = np.c_[xx.ravel(),yy.ravel()]
[grid_predictions] = sess.run(prediction, feed_dict={x_data: rand_x,
y_target: rand_y,
prediction_grid: grid_points})
grid_predictions = grid_predictions.reshape(xx.shape)
plt.subplot(2, 2, n+1)
plt.contourf(xx, yy, grid_predictions, cmap=plt.cm.Paired, alpha=0.8)
class1_x = [x[0] for i,x in enumerate(X) if Y[i]==1]
class1_y = [x[1] for i,x in enumerate(X) if Y[i]==1]
class2_x = [x[0] for i,x in enumerate(X) if Y[i]==-1]
class2_y = [x[1] for i,x in enumerate(X) if Y[i]==-1]
plt.plot(class1_x, class1_y, 'ro', label='setosa')
plt.plot(class2_x, class2_y, 'kx', label='not-setosa')
plt.title('Gamma=%d Gaussion SVM Results on Iris Data'%abs(sess.run(gamma)))
plt.xlabel('Pedak Length')
plt.xlabel('Sepal Width')
plt.legend(loc='lower right')
plt.show()
# # 随着时间推移绘制损失
# plt.figure(2)
# plt.plot(loss_vec, 'k-')
# plt.title('Loss per Generation')
# plt.xlabel('Generation')
# plt.ylabel('Loss')
# plt.show()
# 随着时间推移绘制准确率
plt.figure(3)
plt.plot(batch_accuracy, 'k-')
plt.title('accuracy per Generation')
plt.xlabel('Generation')
plt.ylabel('accuracy')
plt.show()
非线性SVM实现多分类
采用的是OVR的形式--多分类任务OVO、OVR及softmax回归
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from tensorflow.python.framework import ops
ops.get_default_graph()
sess = tf.Session()
iris = datasets.load_iris()
X = np.array([x[2:4] for x in iris.data])
y_1 = np.array([1 if i==0 else -1 for i in iris.target]) # Istosa
y_2 = np.array([1 if i==1 else -1 for i in iris.target]) # Virginica
y_3 = np.array([i if i==2 else -1 for i in iris.target]) # Versicolor
Y = np.array([y_1, y_2, y_3])
class1_x = [x[0] for i, x in enumerate(X) if iris.target[i] == 0]
class1_y = [x[1] for i, x in enumerate(X) if iris.target[i] == 0]
class2_x = [x[0] for i, x in enumerate(X) if iris.target[i] == 1]
class2_y = [x[1] for i, x in enumerate(X) if iris.target[i] == 1]
class3_x = [x[0] for i, x in enumerate(X) if iris.target[i] == 2]
class3_y = [x[1] for i, x in enumerate(X) if iris.target[i] == 2]
# 声明学习率, 批量大小, 占位符和模型变量
learning_rate = 0.01
batch_size = 50
x_data = tf.placeholder(shape=[None, 2], dtype=tf.float32)
y_target = tf.placeholder(shape=[3, None], dtype=tf.float32)
prediction_grid = tf.placeholder(shape=[None, 2], dtype=tf.float32)
# 为SVM创建变量
b = tf.Variable(tf.random_normal(shape=[3, batch_size]))
# 声明高斯核函数
gamma = tf.constant([-10.])
sq_dists = tf.multiply(2., tf.matmul(x_data, tf.transpose(x_data)))
Kernel = tf.exp(tf.multiply(gamma, tf.abs(sq_dists)))
### 声明函数进行整形\批量乘法
# 最大的变化是批量矩阵乘法
# 最终的结果是三维矩阵,并且需要传播矩阵乘法
# 所以数据矩阵和目标矩阵需要预处理, 比如x^T x操作需要增加一个维度
# 这里创建一个函数来扩展矩阵维度, 然后进行矩阵转置
def reshape_matmul(mat, batch_size):
'''
:param
mat: y_target
:return:
y_target的三维内积
'''
v1 = tf.expand_dims(mat, 1)
v2 = tf.reshape(v1, [3, batch_size, 1])
return tf.matmul(v2, v1)
# ---------------------------------
# 计算SVM模型
first_term = tf.reduce_sum(b)
b_vec_cross = tf.matmul(tf.transpose(b), b)
y_target_cross = reshape_matmul(y_target, batch_size)
second_term = tf.reduce_sum(tf.multiply(Kernel, tf.multiply(b_vec_cross, y_target_cross)))
loss = tf.negative(tf.subtract(first_term, second_term))
# 创建一个预测核函数
rA = tf.reshape(tf.reduce_sum(tf.square(x_data), 1), [-1, 1])
rB = tf.reshape(tf.reduce_sum(tf.square(prediction_grid), 1), [-1, 1])
pred_sq_dist = tf.add(tf.subtract(rA, tf.multiply(2., tf.matmul(x_data, tf.transpose(prediction_grid)))),
tf.transpose(rB))
pred_kernel = tf.exp(tf.multiply(gamma, tf.abs(pred_sq_dist)))
# 与二分类不同的是, 不再对模型输出进行sign()运算
# 因为这里实现的是一对多方法, 所以预测值是分类器有最大返回值的类别
# 使用Tensorflow内建函数arg_max()来实现
predictions_output = tf.matmul(tf.multiply(y_target, b), pred_kernel)
prediction = tf.arg_max(predictions_output-tf.expand_dims(tf.reduce_mean(predictions_output, 1), 1), 0)
accuracy = tf.reduce_mean(tf.cast(tf.equal(prediction, tf.arg_max(y_target, 0)), tf.float32))
# 声明优化器
my_opt = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_step = my_opt.minimize(loss)
# 初始化变量
init = tf.global_variables_initializer()
sess.run(init)
# 训练模型
loss_vec = []
batch_accuracy = []
for i in range(300):
rand_index = np.random.choice(len(X), size=batch_size)
rand_x = X[rand_index]
rand_y = Y[:, rand_index]
# 目标:最优化损失
sess.run(train_step, feed_dict={x_data: rand_x,
y_target: rand_y})
# 更新loss值
temp_loss = sess.run(loss, feed_dict={x_data: rand_x,
y_target: rand_y})
loss_vec.append(temp_loss)
acc_temp = sess.run(accuracy, feed_dict={x_data: rand_x,
y_target: rand_y,
prediction_grid: rand_x})
batch_accuracy.append(acc_temp)
# 每50次打印
if (i + 1) % 50 == 0:
print('Step:', i + 1)
print('Loss为:', temp_loss)
print('Accuracy为:', acc_temp)
# 创建一个网格来绘制点
# 为了绘制决策边界, 创建一个数据点(x,y)的网络来评估预测函数
x_min, x_max = X[:,0].min() - 1, X[:,0].max() + 1
y_min, y_max = X[:,1].min() - 1, X[:,1].max() + 1
xx,yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
grid_points = np.c_[xx.ravel(),yy.ravel()]
grid_predictions = sess.run(prediction, feed_dict={x_data: rand_x,
y_target: rand_y,
prediction_grid: grid_points})
grid_predictions = grid_predictions.reshape(xx.shape)
plt.figure(figsize=(8,8))
plt.contourf(xx, yy, grid_predictions, cmap=plt.cm.Paired, alpha=0.8)
plt.plot(class1_x, class1_y, 'ro', label='setosa')
plt.plot(class2_x, class2_y, 'kx', label='Virginica')
plt.plot(class3_x, class3_y, 'gv', label='Versicolor')
plt.title('Gamma=%d Gaussion SVM Results on Iris Data'%abs(sess.run(gamma)))
plt.xlabel('Pedak Length')
plt.xlabel('Sepal Width')
plt.legend(loc='lower right')
plt.show()
# 随着时间推移绘制准确率
plt.figure(3)
plt.plot(batch_accuracy, 'k-')
plt.title('accuracy per Generation')
plt.xlabel('Generation')
plt.ylabel('accuracy')
plt.show()
SVM代码实现--Tensorflow部分就是这样了, 继续下一章吧!pd的Machine Learning