tensorflow——SVM实现

本文介绍了如何在TensorFlow中实现支持向量机(SVM),包括SVM的基本概念和在TensorFlow中定义SVM类的函数。
摘要由CSDN通过智能技术生成

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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值