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