tensorflow——SVM实现
tensorflow——SVM实现
ei1994 2017-08-07 15:42:37 9182 收藏
版权
1、SVM实现
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# 生成数据集
def gen_two_clusters(size=100, n_dim=2, center=0, dis=2, scale=1, one_hot=True):
center1 = (np.random.random(n_dim) + center - 0.5) * scale + dis
center2 = (np.random.random(n_dim) + center - 0.5) * scale - dis
cluster1 = (np.random.randn(size, n_dim) + center1) * scale
cluster2 = (np.random.randn(size, n_dim) + center2) * scale
data = np.vstack((cluster1, cluster2)).astype(np.float32)
labels = np.array([1] * size + [0] * size)
indices = np.random.permutation(size * 2)
data, labels = data[indices], labels[indices]
if not one_hot:
return data, labels
labels = np.array([[0, 1] if label == 1 else [1, 0] for label in labels], dtype=np.int8)
return data, labels
# 生成网格数据集
def get_base(_nx, _ny):
_xf = np.linspace(x_min, x_max, _nx)
_yf = np.linspace(y_min, y_max, _ny)
n_xf, n_yf = np.meshgrid(_xf, _yf)
return _xf, _yf, np.c_[n_xf.ravel(), n_yf.ravel()]
#用于生成数据
#x, y = gen_two_clusters(n_dim=2, dis=2.5, center=5, one_hot=False)
#np.save('x.npy',x)
#np.save('y.npy',y)
x_ = np.load('x.npy')
y_ = np.load('y.npy')
y_ = y_.reshape(-1,1)
title = 'linear_SVM'
#plt.figure()
plt.title(title)
#plt.xlim(x_min, x_max)
#plt.ylim(y_min, y_max)
y_0 = np.where(y_==1)
y_1 = np.where(y_==-1)
#plt.scatter(x_[y_0,0], x_[y_0,1], c='g')
#plt.scatter(x_[y_1,0], x_[y_1,1], c='r')
#plt.show()
c = 1
lr = 0.01
batch_size = 128
epoch = 1000
tol = 1e-3
padding = 0.1
x = tf.placeholder(tf.float32, [None, 2])
y = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(np.zeros([2,1]), dtype=tf.float32, name='w')
b = tf.Variable(0, dtype=tf.float32, name='b')
y_pred1 = tf.matmul(x, W) + b
y_pred = tf.sign(y_pred1)
loss = tf.reduce_mean(tf.reduce_sum( tf.nn.relu(1-y_*y_pred1)) + c* tf.nn.l2_loss(W))
optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss)
tf.summary.scalar('loss', loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('nlogs/', sess.graph)
sess.run(init)
for i in range(epoch):
_, loss_ ,W_,b_= sess.run([optimizer,loss,W,b], feed_dict={x: x_, y:y_})
y_pred_,y_pred1_, w = sess.run([ y_pred,y_pred1,W], feed_dict={x: x_, y:y_})
if i%50 ==0:
# loss_ = sess.run(loss, feed_dict={x: x_, y:y_})
# print(loss_)
result= sess.run(merged, feed_dict={x: x_, y:y_})
writer.add_summary(result, i)
x_min, x_max = np.min(x_[:,0]), np.max(x_[:,0])
y_min, y_max = np.min(x_[:,1]), np.max(x_[:,1])
x_padding = max(abs(x_min), abs(x_max)) * padding
y_padding = max(abs(y_min), abs(y_max)) * padding
x_min -= x_padding
x_max += x_padding
y_min -= y_padding
y_max += y_padding
xf, yf, base_matrix = get_base(200, 200)
z = np.sign(np.matmul(base_matrix,w)+b_).reshape((200, 200))
#z = npbase_matrix.reshape((200, 200))
plt.contour(xf, yf, z, c='k-', levels=[0.5]) #画分界限的(等高线)
#xy_xf, xy_yf = np.meshgrid(xf, yf, sparse=True)
plt.pcolormesh(xf, yf, z, cmap=plt.cm.Paired) #画分界线背景颜色的
#visualize2d(x_, y_, padding=0.1, dense=400)
plt.scatter(x_[y_0,0], x_[y_0,1], c='g')
plt.scatter(x_[y_1,0], x_[y_1,1], c='b')
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
2、SVM—定义类的函数
import tensorflow as tf
import numpy as np
import math
from matplotlib import pyplot as plt
from tensorflow import flags
class SVM():
def __init__(self):
self.x=tf.placeholder('float',shape=[None,2],name='x_batch')
self.y=tf.placeholder('float',shape=[None,1],name='y_batch')
# self.sess=tf.Session()
def creat_dataset(self,size, n_dim=2, center=0, dis=2, scale=1, one_hot=False):
center1 = (np.random.random(n_dim) + center - 0.5) * scale + dis
center2 = (np.random.random(n_dim) + center - 0.5) * scale - dis
cluster1 = (np.random.randn(size, n_dim) + center1) * scale
cluster2 = (np.random.randn(size, n_dim) + center2) * scale
x_data = np.vstack((cluster1, cluster2)).astype(np.float32)
y_data = np.array([1] * size + [-1] * size)
indices = np.random.permutation(size * 2)
data, labels = x_data[indices], y_data[indices]
labels=np.reshape(labels,(-1,1))
if not one_hot:
return data, labels
labels = np.array([[0, 1] if label == 1 else [1, 0] for label in labels], dtype=np.int8)
return data, labels
@staticmethod
def get_base(self,_nx, _ny):
_xf = np.linspace(self.x_min, self.x_max, _nx)
_yf = np.linspace(self.y_min, self.y_max, _ny)
n_xf, n_yf = np.meshgrid(_xf, _yf)
return _xf, _yf,np.c_[n_xf.ravel(), n_yf.ravel()]
# def readdata(self):
#
# x_data=np.load('x.npy')
# y1=np.load('y.npy')
# y_data=np.reshape(y1,[200,1])
# return x_data ,y_data
def predict(self,y_data):
correct = tf.equal(self.y_predict_value, y_data)
precision=tf.reduce_mean(tf.cast(correct, tf.float32))
precision_value=self.sess.run(precision)
return precision_value, self.y_predict_value
def shuffle(self,epoch,batch,x_data,y_data):
for i in range(epoch):
shuffle_index=np.random.permutation(y_data.shape[0])
x_data1, y_data1 = x_data[shuffle_index], y_data[shuffle_index]
batch_per_epoch = math.ceil(y_data.shape[0]*2 / batch)
for b in range(batch_per_epoch):
if (b*batch+batch)>y_data.shape[0]:
a,b = b*batch, y_data.shape[0]
else:
a,b = b*batch, b*batch+batch
data, labels = x_data1[a:b,:], y_data1[a:b,:]
yield data, labels
def train(self,epoch,x_data,y_data,x_edata,y_edata):
w = tf.Variable(np.ones([2,1]), dtype=tf.float32, name="w_v")
b = tf.Variable(0., dtype=tf.float32, name="b_v")
y_pred =tf.matmul(self.x,w)+b
cost = tf.nn.l2_loss(w)+tf.reduce_sum(tf.maximum(1-self.y*y_pred,0))
train_step = tf.train.AdamOptimizer(0.01).minimize(cost)
y_predict =tf.sign( y_pred)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
shuffle= self.shuffle(epoch,100,x_data,y_data)
for i, (x_batch, y_batch) in enumerate(shuffle):
# index=np.random.permutation(y_data.shape[0])
# x_data1, y_data1 = x_data[index], y_data[index]
sess.run(train_step,feed_dict={self.x:x_batch,self.y:y_batch})
if i%1000==0:
self.y_predict_value,self.w_value,self.b_value,cost_value=sess.run([y_predict,w,b,cost],feed_dict={self.x:x_data,self.y:y_data})
print('step= %d , cost=%f '%(i, cost_value))
y_pre = np.sign(np.matmul(x_edata,self.w_value)+self.b_value)
correct = np.equal(y_pre, y_edata)
precision=np.mean(np.cast[ 'float32'](correct))
# precision_value=sess.run(precision)
print('eval= %d'%precision)
def drawresult(self,x_data):
x_min, x_max = np.min(x_data[:,0]), np.max(x_data[:,0])
y_min, y_max = np.min(x_data[:,1]), np.max(x_data[:,1])
x_padding = max(abs(x_min), abs(x_max)) * FLAGS.padding
y_padding = max(abs(y_min), abs(y_max)) * FLAGS.padding
self.x_min -= x_padding
self.x_max += x_padding
self.y_min -= y_padding
self.y_max += y_padding
# self.x_min, self.y_min = np.minimum.reduce(x_data,axis=0) -2
# self.x_max, self.y_max = np.maximum.reduce(x_data,axis=0) +2
xf, yf , matrix_= self.get_base(self,200, 200)
print(self.w_value,self.b_value)
z=np.sign(np.matmul(matrix_,self.w_value)+self.b_value).reshape((200,200))
plt.pcolormesh(xf, yf, z, cmap=plt.cm.Paired)
ypv = self.y_predict_value
y_0 = np.where(ypv==1)
y_1 = np.where(ypv==-1)
plt.scatter(x_data[y_0,0], x_data[y_0,1], c='g')
plt.scatter(x_data[y_1,0], x_data[y_1,1], c='r')
plt.axis([self.x_min,self.x_max,self.y_min ,self.y_max])
# plt.contour(xf, yf, z)
plt.show()
flags.DEFINE_integer('epoch', 1000, "number of epoch")
flags.DEFINE_float('lr', 0.01, "learning rate")
flags.DEFINE_integer('padding', 0.1, "padding")
flags.DEFINE_integer('batch', 100, "batch size")
FLAGS = flags.FLAGS
svm=SVM()
x_data,y_data=svm.creat_dataset(size=100, n_dim=2, center=0, dis=4, one_hot=False)
x_edata,y_edata=svm.creat_dataset(size=100, n_dim=2, center=0, dis=4, one_hot=False)
svm.train(FLAGS.epoch,x_data,y_data,x_edata,y_edata)
#precision_value,y_predict_value=svm.predict(y_data)
#print(precision_value)
svm.drawresult(x_data)
————————————————
版权声明:本文为CSDN博主「ei1994」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ei1990/java/article/details/76849994
用tensorflow实现svm的线性和非线性分类
线性分割:
-
# coding: utf-8
-
-
# In[1]:
-
-
-
import matplotlib.pyplot as plt
-
import numpy as np
-
from sklearn import datasets
-
import tensorflow as tf
-
-
-
# In[2]:
-
-
-
iris = datasets.load_iris()
-
x_vals = np.array([[x[0],x[3]] for x in iris.data])
-
y_vals = np.array([1 if y == 0 else -1 for y in iris.target])
-
-
-
# In[3]:
-
-
-
x_vals[:5],y_vals[:5]
-
-
-
# In[4]:
-
-
-
from sklearn import model_selection
-
train_data,test_data,train_target,test_target = model_selection.train_test_split(x_vals,y_vals,test_size=0.2)
-
-
-
# In[5]:
-
-
-
train_data.shape,test_data.shape
-
-
-
# In[6]:
-
-
-
batch_size = 100
-
x_data = tf.placeholder(shape=[None,2],dtype=tf.float32)
-
y_target = tf.placeholder(shape=[None,1],dtype=tf.float32)
-
A = tf.Variable(tf.random_normal(shape=[2,1]))
-
b = tf.Variable(tf.random_normal(shape=[1,1]))
-
-
-
# In[7]:
-
-
-
model_output = tf.subtract(tf.matmul(x_data,A),b)
-
-
-
# In[8]:
-
-
-
l2_norm = tf.reduce_sum(tf.square(A))
-
alpha = tf.constant([0.1])
-
classification_term=tf.reduce_mean(tf.maximum(0.,tf.subtract(1.,tf.multiply(model_output,y_target))))
-
loss = tf.add(classification_term,tf.multiply(alpha,l2_norm))
-
-
-
# In[9]:
-
-
-
prediction = tf.sign(model_output)
-
accuracy = tf.reduce_mean(tf.cast(tf.equal(prediction,y_target),tf.float32))
-
-
-
# In[10]:
-
-
-
my_opt = tf.train.GradientDescentOptimizer(0.01)
-
train_step = my_opt.minimize(loss)
-
init = tf.global_variables_initializer()
-
sess = tf.Session()
-
sess.run(init)
-
-
-
# In[11]:
-
-
-
loss_vec = []
-
train_accuracy = []
-
test_accuracy = []
-
for i in range(500):
-
rand_index = np.random.choice(len(train_data),size = batch_size)
-
rand_x = train_data[rand_index]
-
rand_y = np.transpose([train_target[rand_index]])
-
sess.run(train_step,feed_dict={x_data:rand_x,y_target:rand_y})
-
temp_loss = sess.run(loss,feed_dict={x_data:rand_x,y_target:rand_y})
-
loss_vec.append(temp_loss)
-
train_acc_temp = sess.run(accuracy,feed_dict={x_data:train_data,y_target:np.transpose([train_target])})
-
train_accuracy.append(train_acc_temp)
-
test_acc_temp = sess.run(accuracy,feed_dict={x_data:test_data,y_target:np.transpose([test_target])})
-
test_accuracy.append(test_acc_temp)
-
if (i+1)% 100 ==0:
-
print('step # '+str(i+1)+'A='+str(sess.run(A))+'b='+str(sess.run(b)))
-
print('Loss = '+str(temp_loss))
-
-
-
# In[12]:
-
-
-
[[a1],[a2]]= sess.run(A)
-
[[b]]=sess.run(b)
-
slope=-a2/a1
-
y_intercept=b/a1
-
x1_vals = [d[1] for d in x_vals]
-
best_fit = []
-
for i in x1_vals:
-
best_fit.append(slope*i+y_intercept)
-
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]
-
best_fit
-
-
-
# In[13]:
-
-
-
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 edal width')
-
plt.xlabel('pedal width')
-
plt.ylabel('sepal length')
-
plt.show()
-
-
plt.plot(train_accuracy,'k-',label='Training Accuracy')
-
plt.plot(test_accuracy,'r--',label='Test Accuracy')
-
plt.title('Train and Test Set Accuracy')
-
plt.xlabel('Generation')
-
plt.ylabel('Accuracy')
-
plt.legend(loc='lower right')
-
plt.show()
-
-
plt.plot(loss_vec,'k--')
-
plt.title('Loss per Generation')
-
plt.xlabel('Generation')
-
plt.ylabel('Loss')
-
plt.show()
-
非线性分割:
-
# coding: utf-8
-
-
# In[1]:
-
-
-
import matplotlib.pyplot as plt
-
import numpy as np
-
import tensorflow as tf
-
from sklearn import datasets
-
-
-
# In[11]:
-
-
-
sess = tf.Session()
-
x_vals,y_vals = datasets.make_circles(n_samples = 1000,factor=0.5,noise=0.1)
-
y_vals = np.array([1 if y==1 else -1 for y in y_vals])
-
class1_x = [x[0] for i,x in enumerate(x_vals) if y_vals[i]==1]
-
class1_y = [x[1] for i,x in enumerate(x_vals) if y_vals[i]==1]
-
class2_x = [x[0] for i,x in enumerate(x_vals) if y_vals[i]==-1]
-
class2_y = [x[1] for i,x in enumerate(x_vals) if y_vals[i]==-1]
-
-
-
# In[12]:
-
-
-
batch_size = 250
-
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)
-
b = tf.Variable(tf.random_normal(shape=[1,batch_size]))
-
-
-
# In[13]:
-
-
-
gamma = tf.constant(-50.0)
-
dist = tf.reduce_sum(tf.square(x_data),1)
-
dist = tf.reshape(dist,[-1,1])
-
sq_dists = tf.add(tf.subtract(dist,tf.multiply(2.,tf.matmul(x_data,tf.transpose(x_data)))),tf.transpose(dist))
-
my_kernel = tf.exp(tf.multiply(gamma,tf.abs(sq_dists)))
-
-
-
# In[14]:
-
-
-
model_output = tf.matmul(b,my_kernel)
-
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(my_kernel,tf.multiply(b_vec_cross,y_target_cross)))
-
loss = tf.negative(tf.subtract(first_term,second_term))
-
-
-
# In[15]:
-
-
-
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)))
-
prediction_output = tf.matmul(tf.multiply(tf.transpose(y_target),b),pred_kernel)
-
prediction = tf.sign(prediction_output- tf.reduce_mean(prediction_output))
-
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.squeeze(prediction),tf.squeeze(y_target)),tf.float32))
-
-
-
# In[16]:
-
-
-
my_opt = tf.train.GradientDescentOptimizer(0.001)
-
train_step = my_opt.minimize(loss)
-
init = tf.global_variables_initializer()
-
sess.run(init)
-
-
-
# In[17]:
-
-
-
loss_vec = []
-
batch_accuracy = []
-
for i in range(500):
-
rand_index = np.random.choice(len(x_vals),size=batch_size)
-
rand_x = x_vals[rand_index]
-
rand_y = np.transpose([y_vals[rand_index]])
-
sess.run(train_step,feed_dict={x_data:rand_x,y_target:rand_y})
-
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)
-
if (i+1)%100==0:
-
print('Step #'+str(i+1))
-
print('Loss = '+str(temp_loss))
-
-
-
# In[18]:
-
-
-
x_min,x_max = x_vals[:,0].min()-1,x_vals[:,0].max()+1
-
y_min,y_max = x_vals[:,1].min()-1,x_vals[:,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)
-
-
-
# In[19]:
-
-
-
plt.contourf(xx,yy,grid_predictions,cmap = plt.cm.Paired,alpha=0.8)
-
plt.plot(class1_x,class1_y,'ro',label='Class 1')
-
plt.plot(class2_x,class2_y,'kx',label='Class -1')
-
plt.legend(loc='lower right')
-
plt.ylim([-1.5,1.5])
-
plt.xlim([-1.5,1.5])
-
plt.show()
-
-
plt.plot(batch_accuracy,'k-',label='Accuracy')
-
plt.title('Batch Accuracy')
-
plt.xlabel('Generation')
-
plt.ylabel('Accuracy')
-
plt.legend(loc='lower right')
-
plt.show()
-
-
plt.plot(loss_vec,'k-')
-
plt.title('Loss per Generation')
-
plt.xlabel('Generation')
-
plt.ylabel('Loss')
-
plt.show()
-
-
浙公网安备 33010602011771号