欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Tensorflow使用支持向量機擬合線性回歸

 更新時間:2018年09月07日 15:01:07   作者:lilongsy  
這篇文章主要為大家詳細介紹了Tensorflow使用支持向量機擬合線性回歸,具有一定的參考價值,感興趣的小伙伴們可以參考一下

支持向量機可以用來擬合線性回歸。

相同的最大間隔(maximum margin)的概念應(yīng)用到線性回歸擬合。代替最大化分割兩類目標(biāo)是,最大化分割包含大部分的數(shù)據(jù)點(x,y)。我們將用相同的iris數(shù)據(jù)集,展示用剛才的概念來進行花萼長度與花瓣寬度之間的線性擬合。

相關(guān)的損失函數(shù)類似于max(0,|yi-(Axi+b)|-ε)。ε這里,是間隔寬度的一半,這意味著如果一個數(shù)據(jù)點在該區(qū)域,則損失等于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()

輸出結(jié)果:

-----------
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數(shù)據(jù)集(花萼長度和花瓣寬度)的支持向量機回歸,間隔寬度為0.5

每次迭代的支持向量機回歸的損失值(訓(xùn)練集和測試集)

直觀地講,我們認為SVM回歸算法試圖把更多的數(shù)據(jù)點擬合到直線兩邊2ε寬度的間隔內(nèi)。這時擬合的直線對于ε參數(shù)更有意義。如果選擇太小的ε值,SVM回歸算法在間隔寬度內(nèi)不能擬合更多的數(shù)據(jù)點;如果選擇太大的ε值,將有許多條直線能夠在間隔寬度內(nèi)擬合所有的數(shù)據(jù)點。作者更傾向于選取更小的ε值,因為在間隔寬度附近的數(shù)據(jù)點比遠處的數(shù)據(jù)點貢獻更少的損失。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Matplotlib實戰(zhàn)之折線圖繪制詳解

    Matplotlib實戰(zhàn)之折線圖繪制詳解

    折線圖是一種用于可視化數(shù)據(jù)變化趨勢的圖表,它可以用于表示任何數(shù)值隨著時間或類別的變化,本文主要介紹了如何利用Matplotlib實現(xiàn)折線圖的繪制,感興趣的可以了解下
    2023-08-08
  • python中使用you-get庫批量在線下載bilibili視頻的教程

    python中使用you-get庫批量在線下載bilibili視頻的教程

    這篇文章主要介紹了使用python中you-get庫批量在線下載bilibili視頻的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • 使用python爬取4K壁紙保存到本地文件夾的全過程

    使用python爬取4K壁紙保存到本地文件夾的全過程

    圖片信息豐富多彩,許多網(wǎng)站上都有大量精美的圖片資源,有時候我們可能需要批量下載這些圖片,而手動一個個下載顯然效率太低,所以本文給大家介紹了使用python爬取4K壁紙保存到本地文件夾的全過程,文中有詳細的代碼示例供大家參考,需要的朋友可以參考下
    2024-03-03
  • Python實現(xiàn)二叉樹前序、中序、后序及層次遍歷示例代碼

    Python實現(xiàn)二叉樹前序、中序、后序及層次遍歷示例代碼

    這篇文章主要給大家介紹了關(guān)于Python實現(xiàn)二叉樹前序、中序、后序及層次遍歷的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • python代碼中怎么換行

    python代碼中怎么換行

    這篇文章主要介紹了python代碼中怎么換行的相關(guān)知識點以及方法,需要的朋友們可以學(xué)習(xí)下。
    2020-06-06
  • 如何使用Python自動控制windows桌面

    如何使用Python自動控制windows桌面

    這篇文章主要介紹了如何使用Python自動控制windows桌面,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • 詳解python之異步編程

    詳解python之異步編程

    這篇文章主要為大家介紹了python之異步編程,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助<BR>
    2021-12-12
  • python 利用百度API識別圖片文字(多線程版)

    python 利用百度API識別圖片文字(多線程版)

    這篇文章主要介紹了python 利用百度API識別圖片文字(多線程版),幫助大家更好的利用python進行機器識別,感興趣的朋友可以了解下
    2020-12-12
  • VsCode終端激活anconda環(huán)境問題解決

    VsCode終端激活anconda環(huán)境問題解決

    本文主要介紹了VsCode終端激活anconda環(huán)境問題解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-01-01
  • Python實現(xiàn)Dijkstra算法

    Python實現(xiàn)Dijkstra算法

    今天小編就為大家分享一篇關(guān)于Python實現(xiàn)Dijkstra算法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-10-10

最新評論