1. 程式人生 > >用TensorFlow實現非線性支援向量機

用TensorFlow實現非線性支援向量機

這裡將載入iris資料集,建立一個山鳶尾花(I.setosa)的分類器。

# Nonlinear SVM Example
#----------------------------------
#
# This function wll illustrate how to
# implement the gaussian kernel on
# the iris dataset.
#
# Gaussian Kernel:
# K(x1, x2) = exp(-gamma * abs(x1 - x2)^2)

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資料集,抽取花萼長度和花瓣寬度,分割每類的x_vals值和y_vals值 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]) 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] # Declare batch size # 宣告批量大小(偏向於更大批量大小) batch_size = 150 # Initialize placeholders
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) # Create variables for svm b = tf.Variable(tf.random_normal(shape=[1,batch_size])) # Gaussian (RBF) kernel # 宣告批量大小(偏向於更大批量大小) gamma = tf.constant(-25.0) sq_dists = tf.multiply(2., tf.matmul(x_data, tf.transpose(x_data))) my_kernel = tf.exp(tf.multiply(gamma, tf.abs(sq_dists))) # Compute SVM Model 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)) # Gaussian (RBF) prediction kernel # 建立一個預測核函式 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)) # Declare optimizer my_opt = tf.train.GradientDescentOptimizer(0.01) train_step = my_opt.minimize(loss) # Initialize variables init = tf.global_variables_initializer() sess.run(init) # Training loop loss_vec = [] batch_accuracy = [] for i in range(300): 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)%75==0: print('Step #' + str(i+1)) print('Loss = ' + str(temp_loss)) # Create a mesh to plot points in # 為了繪製決策邊界(Decision Boundary),我們建立一個數據點(x,y)的網格,評估預測函式 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) # Plot points and grid plt.contourf(xx, yy, grid_predictions, cmap=plt.cm.Paired, alpha=0.8) plt.plot(class1_x, class1_y, 'ro', label='I. setosa') plt.plot(class2_x, class2_y, 'kx', label='Non setosa') plt.title('Gaussian SVM Results on Iris Data') plt.xlabel('Pedal Length') plt.ylabel('Sepal Width') plt.legend(loc='lower right') plt.ylim([-0.5, 3.0]) plt.xlim([3.5, 8.5]) plt.show() # Plot batch accuracy plt.plot(batch_accuracy, 'k-', label='Accuracy') plt.title('Batch Accuracy') plt.xlabel('Generation') plt.ylabel('Accuracy') plt.legend(loc='lower right') plt.show() # Plot loss over time plt.plot(loss_vec, 'k-') plt.title('Loss per Generation') plt.xlabel('Generation') plt.ylabel('Loss') plt.show()

輸出:

Step #75
Loss = -110.332
Step #150
Loss = -222.832
Step #225
Loss = -335.332
Step #300
Loss = -447.832

四種不同的gamma值(1,10,25,100):
1
10
25
100
不同gamma值的山鳶尾花(I.setosa)的分類器結果圖,採用高斯核函式的SVM。
gamma值越大,每個資料點對分類邊界的影響就越大。

相關推薦

TensorFlow實現非線性支援向量

這裡將載入iris資料集,建立一個山鳶尾花(I.setosa)的分類器。 # Nonlinear SVM Example #---------------------------------- # # This function wll illustrate

TensorFlow深度學習框架學習(二):TensorFlow實現線性支援向量(SVM)

SVM的原理可以參考李航的《統計學習方法》 具體程式碼如下,程式碼都有註釋的 #1、匯入必要的庫 import matplotlib.pyplot as plt import numpy as np import tensorflow as tf fro

SVM支援向量系列理論(三) 非線性支援向量與核函式技巧

3.1 核技巧解決非線性SVM 3.1.1 非線性SVM解決思路 3.1.2 核技巧下SVM 3.2 Mercer核

非線性支援向量

首先來看看核函式的概念:如果我們把SVM看作是一個導彈,如果這個導彈運載核彈的話那麼它就可以取得很大的威力,而核函式就類似於這樣可以取得很大的威力。 我們知道線上性可分支援向量機中它主要是構造了這樣一個目標函式:           &nbs

詳解SVM系列(五):非線性支援向量與核函式

對解線性分類問題,線性分類支援向量機是一種有效的方法。但是,有時分類問題是非線性的,這時可以使用非線性支援向量機。 核技巧 **非線性分類問題:**如上面左圖所示,能用 R

支援向量學習筆記(三):非線性支援向量與SMO演算法

非線性問題 在之前學了線性支援向量機,通過訓練集學習到分離超平面 w x +

支援向量原理小結(3)——核方法和非線性支援向量

  前面兩篇部落格對線性支援向量機進行了詳細的講解,但線性SVM對於非線性的資料是無可奈何的。這篇部落格將講一下非線性支援向量機。 1. 核方法   對SVM有過一定耳聞的人,一定聽說過“核技巧”、“核方法”這些名詞,其實核方法並不是只能應用於SVM,還

【機器學習】支援向量(4)——非線性支援向量(核函式)

前言 當訓練資料集線性可分或者近似線性可分時,前面我們在文一以及文二已經介紹了線性可分支援向量機和線性支援向量機。但是有時訓練資料集是非線性的,這時就可以使用非線性支援向量機。 非線性支援向量機的主要特點就是利用了核技巧。 非線性分類問題 如

機器學習(7)——支援向量(二):線性可分支援向量非線性支援向量

線性可分支援向量機 回顧 前面總結了線性可分支援向量機,知道了支援向量機的最終目的就是通過“間隔最大化” 得到最優分類器,能夠使最難區分的樣本點得到最大的分類確信度,而這些難區分的樣本就是支援向量。 還是如下圖所示,超平面H1 和 H2 支撐著中間的決

支援向量非線性支援向量(四)

非線性支援向量機與核函式 核技巧 對於非線性分類問題,可以轉換成線性問題求解。 首先,將原始特徵空間資料對映到新的空間 然後,在新的空間利用線性可分支援向量機方法求解 核函式 設X是輸入空間,設H是特徵空間,如果存在一個從X−>H的

tensorflow實現支持向量

size end des lac clas del p s 加載 optimize 支持向量機用於二分類問題。對要分類的數據,找到一個線形可分的直線或平面。 超平面的公式為Ax-b=0 對於損失函數,我們的公式為 1/n∑ni=1 max(0,1-yi(Axi

【機器學習】演算法原理詳細推導與實現(四):支援向量(上)

【機器學習】演算法原理詳細推導與實現(四):支援向量機(上) 在之前的文章中,包括線性迴歸和邏輯迴歸,都是以線性分界線進行分割劃分種類的。而本次介紹一種很強的分類器【支援向量機】,它適用於線性和非線性分界線的分類方法。 函式間隔概念 為了更好的理解非線性分界線,區別兩種分界線對於分類的直觀理解,第一種直觀理解

【機器學習】演算法原理詳細推導與實現(五):支援向量(下)

【機器學習】演算法原理詳細推導與實現(五):支援向量機(下) 上一章節介紹了支援向量機的生成和求解方式,能夠根據訓練集依次得出\(\omega\)、\(b\)的計算方式,但是如何求解需要用到核函式,將在這一章詳細推導實現。 核函式 在講核函式之前,要對上一章節得到的結果列舉出來。之前需要優化的凸函式為: \[

《機器學習_07_03_svm_核函式與非線性支援向量

### 一.簡介 前兩節分別實現了硬間隔支援向量機與軟間隔支援向量機,它們本質上都是線性分類器,只是軟間隔對“異常點”更加寬容,它們對形如如下的螺旋資料都沒法進行良好分類,因為沒法找到一個直線(超平面)能將其分隔開,必須使用曲線(超曲面)才能將其分隔,而核技巧便是處理這類問題的一種常用手段。 ```pyt

基於Tensorflow實現多分類支援向量

1、匯入必要的程式設計庫; import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from sklearn import datasets sess = tf.Se

SVM支援向量Tensorflow實現

一、tensorflow實現SVM # -- coding: utf-8 -- import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from sklearn import

線性支援向量TensorFlow實現

#載入庫 import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from sklearn import datasets from tensorflow.python.fram

支援向量(Python實現

這篇文章是《機器學習實戰》(Machine Learning in Action)第六章 支援向量機演算法的Python實現程式碼。 1 參考連結 (1)支援向量機通俗導論(理解SVM的三層境界) (2)支援向量機—SMO論文詳解(序列最小最優化演算法) 2 實現程式

機器學習實戰——SVM支援向量 實現記錄

問題:TypeError: data type not understood alphas = mat(zeros(m,1)) 原因是zeros(())格式不對,更改後: alphas = mat(zeros((m,1))) 問題:關於IDLE中換行,回車前面出現很多空格的情況

《機器學習》 周志華學習筆記第六章 支援向量(課後習題)python 實現

一、 1.間隔與支援向量 2.對偶問題 3.核函式 xi與xj在特徵空間的內積等於他們在原始yangben空間中通過函式k(.,.)計算的結果。 核矩陣K總是半正定的。 4.軟間隔與正則化 軟間隔允許某些samples不滿足約束  鬆弛變數 5.支援