利用TensorFlow訓(xùn)練簡(jiǎn)單的二分類神經(jīng)網(wǎng)絡(luò)模型的方法
利用TensorFlow實(shí)現(xiàn)《神經(jīng)網(wǎng)絡(luò)與機(jī)器學(xué)習(xí)》一書(shū)中4.7模式分類練習(xí)
具體問(wèn)題是將如下圖所示雙月牙數(shù)據(jù)集分類。

使用到的工具:
python3.5 tensorflow1.2.1 numpy matplotlib
1.產(chǎn)生雙月環(huán)數(shù)據(jù)集
def produceData(r,w,d,num): r1 = r-w/2 r2 = r+w/2 #上半圓 theta1 = np.random.uniform(0, np.pi ,num) X_Col1 = np.random.uniform( r1*np.cos(theta1),r2*np.cos(theta1),num)[:, np.newaxis] X_Row1 = np.random.uniform(r1*np.sin(theta1),r2*np.sin(theta1),num)[:, np.newaxis] Y_label1 = np.ones(num) #類別標(biāo)簽為1 #下半圓 theta2 = np.random.uniform(-np.pi, 0 ,num) X_Col2 = (np.random.uniform( r1*np.cos(theta2),r2*np.cos(theta2),num) + r)[:, np.newaxis] X_Row2 = (np.random.uniform(r1 * np.sin(theta2), r2 * np.sin(theta2), num) -d)[:,np.newaxis] Y_label2 = -np.ones(num) #類別標(biāo)簽為-1,注意:由于采取雙曲正切函數(shù)作為激活函數(shù),類別標(biāo)簽不能為0 #合并 X_Col = np.vstack((X_Col1, X_Col2)) X_Row = np.vstack((X_Row1, X_Row2)) X = np.hstack((X_Col, X_Row)) Y_label = np.hstack((Y_label1,Y_label2)) Y_label.shape = (num*2 , 1) return X,Y_label
其中r為月環(huán)半徑,w為月環(huán)寬度,d為上下月環(huán)距離(與書(shū)中一致)
2.利用TensorFlow搭建神經(jīng)網(wǎng)絡(luò)模型
2.1 神經(jīng)網(wǎng)絡(luò)層添加
def add_layer(layername,inputs, in_size, out_size, activation_function=None):
# add one more layer and return the output of this layer
with tf.variable_scope(layername,reuse=None):
Weights = tf.get_variable("weights",shape=[in_size, out_size],
initializer=tf.truncated_normal_initializer(stddev=0.1))
biases = tf.get_variable("biases", shape=[1, out_size],
initializer=tf.truncated_normal_initializer(stddev=0.1))
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
2.2 利用tensorflow建立神經(jīng)網(wǎng)絡(luò)模型
輸入層大小:2
隱藏層大?。?0
輸出層大?。?
激活函數(shù):雙曲正切函數(shù)
學(xué)習(xí)率:0.1(與書(shū)中略有不同)
(具體的搭建過(guò)程可參考莫煩的視頻,鏈接就不附上了自行搜索吧......)
###define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 2])
ys = tf.placeholder(tf.float32, [None, 1])
###添加隱藏層
l1 = add_layer("layer1",xs, 2, 20, activation_function=tf.tanh)
###添加輸出層
prediction = add_layer("layer2",l1, 20, 1, activation_function=tf.tanh)
###MSE 均方誤差
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1]))
###優(yōu)化器選取 學(xué)習(xí)率設(shè)置 此處學(xué)習(xí)率置為0.1
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
###tensorflow變量初始化,打開(kāi)會(huì)話
init = tf.global_variables_initializer()#tensorflow更新后初始化所有變量不再用tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
2.3 訓(xùn)練模型
###訓(xùn)練2000次
for i in range(2000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_label})
3.利用訓(xùn)練好的網(wǎng)絡(luò)模型尋找分類決策邊界
3.1 產(chǎn)生二維空間隨機(jī)點(diǎn)
def produce_random_data(r,w,d,num): X1 = np.random.uniform(-r-w/2,2*r+w/2, num) X2 = np.random.uniform(-r - w / 2-d, r+w/2, num) X = np.vstack((X1, X2)) return X.transpose()
3.2 用訓(xùn)練好的模型采集決策邊界附近的點(diǎn)
向網(wǎng)絡(luò)輸入一個(gè)二維空間隨機(jī)點(diǎn),計(jì)算輸出值大于-0.5小于0.5即認(rèn)為該點(diǎn)落在決策邊界附近(雙曲正切函數(shù))
def collect_boundary_data(v_xs):
global prediction
X = np.empty([1,2])
X = list()
for i in range(len(v_xs)):
x_input = v_xs[i]
x_input.shape = [1,2]
y_pre = sess.run(prediction, feed_dict={xs: x_input})
if abs(y_pre - 0) < 0.5:
X.append(v_xs[i])
return np.array(X)
3.3 用numpy工具將采集到的邊界附近點(diǎn)擬合成決策邊界曲線,用matplotlib.pyplot畫(huà)圖
###產(chǎn)生空間隨機(jī)數(shù)據(jù)
X_NUM = produce_random_data(10, 6, -4, 5000)
###邊界數(shù)據(jù)采樣
X_b = collect_boundary_data(X_NUM)
###畫(huà)出數(shù)據(jù)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
###設(shè)置坐標(biāo)軸名稱
plt.xlabel('x1')
plt.ylabel('x2')
ax.scatter(x_data[:, 0], x_data[:, 1], marker='x')
###用采樣的邊界數(shù)據(jù)擬合邊界曲線 7次曲線最佳
z1 = np.polyfit(X_b[:, 0], X_b[:, 1], 7)
p1 = np.poly1d(z1)
x = X_b[:, 0]
x.sort()
yvals = p1(x)
plt.plot(x, yvals, 'r', label='boundray line')
plt.legend(loc=4)
#plt.ion()
plt.show()
4.效果

5.附上源碼Github鏈接
https://github.com/Peakulorain/Practices.git 里的PatternClassification.py文件
另注:分類問(wèn)題還是用softmax去做吧.....我只是用這做書(shū)上的練習(xí)而已。
(初學(xué)者水平有限,有問(wèn)題請(qǐng)指出,各位大佬輕噴)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)戰(zhàn)之夢(mèng)幻鋼琴小游戲的實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了如何利用Python語(yǔ)言編寫一款界面化的(Tkinter)電子鋼琴小程序,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-02-02
如何利用Python處理excel表格中的數(shù)據(jù)
Excel做為職場(chǎng)人最常用的辦公軟件,具有方便、快速、批量處理數(shù)據(jù)的特點(diǎn),下面這篇文章主要給大家介紹了關(guān)于如何利用Python處理excel表格中數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-03-03
Pytorch實(shí)現(xiàn)常用乘法算子TensorRT的示例代碼
pytorch 用于訓(xùn)練,TensorRT用于推理是很多AI應(yīng)用開(kāi)發(fā)的標(biāo)配。大家往往更加熟悉 pytorch 的算子,而不太熟悉TensorRT的算子。本文介紹了Pytorch中常用乘法的TensorRT實(shí)現(xiàn),感興趣的可以了解一下2022-06-06
linux系統(tǒng)使用python監(jiān)控apache服務(wù)器進(jìn)程腳本分享
這篇文章主要介紹了linux系統(tǒng)使用python監(jiān)控apache服務(wù)器進(jìn)程的腳本,大家參考使用吧2014-01-01
Python強(qiáng)大郵件處理庫(kù)Imbox安裝及用法示例
這篇文章主要給大家介紹了關(guān)于Python強(qiáng)大郵件處理庫(kù)Imbox安裝及用法的相關(guān)資料,Imbox是一個(gè)Python 庫(kù),用于從IMAP郵箱中讀取郵件,它提供了簡(jiǎn)單易用的接口,幫助開(kāi)發(fā)者處理郵件,需要的朋友可以參考下2024-03-03
Python安裝Selenium報(bào)錯(cuò)解決之全方位排錯(cuò)指南
pip是一個(gè)安裝Python包的管理工具,很多功能強(qiáng)大、使用方便的Python框架、插件、工具等,都是通過(guò)pip來(lái)進(jìn)行安裝的,這篇文章主要給大家介紹了關(guān)于Python安裝Selenium報(bào)錯(cuò)解決之全方位排錯(cuò)的相關(guān)資料,需要的朋友可以參考下2024-08-08

