Tensorflow使用支持向量机拟合线性回归
作者:lilongsy 发布时间:2021-01-20 03:38:42
标签:Tensorflow,向量机,线性回归
支持向量机可以用来拟合线性回归。
相同的最大间隔(maximum margin)的概念应用到线性回归拟合。代替最大化分割两类目标是,最大化分割包含大部分的数据点(x,y)。我们将用相同的iris数据集,展示用刚才的概念来进行花萼长度与花瓣宽度之间的线性拟合。
相关的损失函数类似于max(0,|yi-(Axi+b)|-ε)。ε这里,是间隔宽度的一半,这意味着如果一个数据点在该区域,则损失等于0。
# SVM Regression
#----------------------------------
#
# This function shows how to use TensorFlow to
# solve support vector regression. We are going
# to find the line that has the maximum margin
# which INCLUDES as many points as possible
#
# We will use the iris data, specifically:
# y = Sepal Length
# x = Pedal Width
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets
from tensorflow.python.framework import ops
ops.reset_default_graph()
# Create graph
sess = tf.Session()
# Load the data
# iris.data = [(Sepal Length, Sepal Width, Petal Length, Petal Width)]
iris = datasets.load_iris()
x_vals = np.array([x[3] for x in iris.data])
y_vals = np.array([y[0] for y in iris.data])
# Split data into train/test sets
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]
# Declare batch size
batch_size = 50
# Initialize placeholders
x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
# Create variables for linear regression
A = tf.Variable(tf.random_normal(shape=[1,1]))
b = tf.Variable(tf.random_normal(shape=[1,1]))
# Declare model operations
model_output = tf.add(tf.matmul(x_data, A), b)
# Declare loss function
# = max(0, abs(target - predicted) + epsilon)
# 1/2 margin width parameter = epsilon
epsilon = tf.constant([0.5])
# Margin term in loss
loss = tf.reduce_mean(tf.maximum(0., tf.subtract(tf.abs(tf.subtract(model_output, y_target)), epsilon)))
# Declare optimizer
my_opt = tf.train.GradientDescentOptimizer(0.075)
train_step = my_opt.minimize(loss)
# Initialize variables
init = tf.global_variables_initializer()
sess.run(init)
# Training loop
train_loss = []
test_loss = []
for i in range(200):
rand_index = np.random.choice(len(x_vals_train), size=batch_size)
rand_x = np.transpose([x_vals_train[rand_index]])
rand_y = np.transpose([y_vals_train[rand_index]])
sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
temp_train_loss = sess.run(loss, feed_dict={x_data: np.transpose([x_vals_train]), y_target: np.transpose([y_vals_train])})
train_loss.append(temp_train_loss)
temp_test_loss = sess.run(loss, feed_dict={x_data: np.transpose([x_vals_test]), y_target: np.transpose([y_vals_test])})
test_loss.append(temp_test_loss)
if (i+1)%50==0:
print('-----------')
print('Generation: ' + str(i+1))
print('A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b)))
print('Train Loss = ' + str(temp_train_loss))
print('Test Loss = ' + str(temp_test_loss))
# Extract Coefficients
[[slope]] = sess.run(A)
[[y_intercept]] = sess.run(b)
[width] = sess.run(epsilon)
# Get best fit line
best_fit = []
best_fit_upper = []
best_fit_lower = []
for i in x_vals:
best_fit.append(slope*i+y_intercept)
best_fit_upper.append(slope*i+y_intercept+width)
best_fit_lower.append(slope*i+y_intercept-width)
# Plot fit with data
plt.plot(x_vals, y_vals, 'o', label='Data Points')
plt.plot(x_vals, best_fit, 'r-', label='SVM Regression Line', linewidth=3)
plt.plot(x_vals, best_fit_upper, 'r--', linewidth=2)
plt.plot(x_vals, best_fit_lower, 'r--', linewidth=2)
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()
# Plot loss over time
plt.plot(train_loss, 'k-', label='Train Set Loss')
plt.plot(test_loss, 'r--', label='Test Set Loss')
plt.title('L2 Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('L2 Loss')
plt.legend(loc='upper right')
plt.show()
输出结果:
-----------
Generation: 50
A = [[ 2.91328382]] b = [[ 1.18453276]]
Train Loss = 1.17104
Test Loss = 1.1143
-----------
Generation: 100
A = [[ 2.42788291]] b = [[ 2.3755331]]
Train Loss = 0.703519
Test Loss = 0.715295
-----------
Generation: 150
A = [[ 1.84078252]] b = [[ 3.40453291]]
Train Loss = 0.338596
Test Loss = 0.365562
-----------
Generation: 200
A = [[ 1.35343242]] b = [[ 4.14853334]]
Train Loss = 0.125198
Test Loss = 0.16121
基于iris数据集(花萼长度和花瓣宽度)的支持向量机回归,间隔宽度为0.5
每次迭代的支持向量机回归的损失值(训练集和测试集)
直观地讲,我们认为SVM回归算法试图把更多的数据点拟合到直线两边2ε宽度的间隔内。这时拟合的直线对于ε参数更有意义。如果选择太小的ε值,SVM回归算法在间隔宽度内不能拟合更多的数据点;如果选择太大的ε值,将有许多条直线能够在间隔宽度内拟合所有的数据点。作者更倾向于选取更小的ε值,因为在间隔宽度附近的数据点比远处的数据点贡献更少的损失。
来源:https://blog.csdn.net/lilongsy/article/details/79391059


猜你喜欢
- 导读:SQL Server数据迁移的知识之前已经为大家介绍了很多,比如SQL Server数据库迁移方法,接下来就为大家详细介绍SQL Se
- 【JS对象属性的查询和设置】可以通过点(.) 或 方括号([]) 运算符来获取属性的值。运算符左侧应当是一个表达式,它返回一个对象。对于点(
- 有时,我们需要获得某张表所有的元数据,我们可能想到的是通过查询系统表获得,但是这比较繁琐,而在SQL Server2005(包含)以后,提供
- windows系统下Python环境的搭建step1:下载Python程序 https://www.python.org/downloads
- 1. 从官网下载 mysql-5.7.13-linux-glibc2.5-x86_64.tar.gz经测试, 本文还适用于如下版本:MySQ
- 在《 详解Python拼接字符串的七种方式 》这篇文章里,我提到过,字符串是程序员离不开的事情。后来,我看到了一个英文版本的说法:There
- 通信信息包是发送至MySQL服务器的单个SQL语句,或发送至客户端的单一行。在MySQL 5.1服务器和客户端之间最大能发送的可能信息包为1
- 这系列文章将介绍一下Oracle的基础知识,将会使用docker下运行的oracle11g的精简版进行说明。这篇文章介绍一下oracle的版
- python记录程序运行时间的三种方法 &nb
- 什么是冗余字段?在设计数据库时,某一字段属于一个表,但它又同时出现在另一个或多个表,且完全等同于它在其本来所属表的意义表示,那么这个字段就是
- 昨天遇到了一个奇怪的问题,在Python中需要传递dict参数,利用json.dumps将dict转为json格式用post方法发起请求:p
- 思考:测试用例执行后,如何生成一个直观漂亮的测试报告呢?分析:1.unittest单元测试框架本身带有一个textTestRunner类,可
- 任何东西只要跟Google有关就总能给我们带来点儿惊喜,2008年9月2日发布的Google Chrome浏览器也不例外。Google Ch
- 最近想做实时目标检测,需要用到python开启摄像头,我手上只有两个uvc免驱的摄像头,性能一般。利用python开启摄像头费了一番功夫,主
- 方法: 使用urlencode函数urllib.request.urlopen()import urllib.requestimport u
- 本文实例讲述了php mailer类调用远程SMTP服务器发送邮件实现方法。分享给大家供大家参考,具体如下:php mailer 是一款很好
- 本文实例讲述了php+mysql开发的最简单在线题库。分享给大家供大家参考,具体如下:题库,对于教育机构,学校,在线教育,是很有必要的,网上
- 在开发项目中,我们可以通过MySQL的慢查询日志对有效率问题的SQL进行监控。下面一些命令是开启日志:查找慢查询日志文件的目录show va
- 本文实例为大家分享了python实现学生信息管理系统的具体代码,含代码注释、增删改查、排序、统计显示学生信息,供大家参考,具体内容如下运行如
- 当Django的内置权限无法满足需求的时候就自己扩展吧~背景介绍overmind项目使用了Django内置的权限系统,Django内置权限系