利用TensorFlow訓(xùn)練簡(jiǎn)單的二分類神經(jīng)網(wǎng)絡(luò)模型的方法
利用TensorFlow實(shí)現(xiàn)《神經(jīng)網(wǎng)絡(luò)與機(jī)器學(xué)習(xí)》一書中4.7模式分類練習(xí)
具體問題是將如下圖所示雙月牙數(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)距離(與書中一致)
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
隱藏層大小:20
輸出層大?。?
激活函數(shù):雙曲正切函數(shù)
學(xué)習(xí)率:0.1(與書中略有不同)
(具體的搭建過程可參考莫煩的視頻,鏈接就不附上了自行搜索吧......)
###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變量初始化,打開會(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畫圖
###產(chǎn)生空間隨機(jī)數(shù)據(jù) X_NUM = produce_random_data(10, 6, -4, 5000) ###邊界數(shù)據(jù)采樣 X_b = collect_boundary_data(X_NUM) ###畫出數(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文件
另注:分類問題還是用softmax去做吧.....我只是用這做書上的練習(xí)而已。
(初學(xué)者水平有限,有問題請(qǐng)指出,各位大佬輕噴)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python NumPy實(shí)現(xiàn)數(shù)組排序與過濾示例分析講解
NumPy是Python的一種開源的數(shù)值計(jì)算擴(kuò)展,它支持大量的維度數(shù)組與矩陣運(yùn)算,這篇文章主要介紹了使用NumPy實(shí)現(xiàn)數(shù)組排序與過濾的方法,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-05-05Python?lambda函數(shù)保姆級(jí)使用教程
本文和你一起探索Python中的lambda函數(shù),讓你以最短的時(shí)間明白這個(gè)函數(shù)的原理。也可以利用碎片化的時(shí)間鞏固這個(gè)函數(shù),讓你在處理工作過程中更高效2022-06-06用Python進(jìn)行行為驅(qū)動(dòng)開發(fā)的入門教程
這篇文章主要介紹了用Python進(jìn)行行為驅(qū)動(dòng)開發(fā)的入門教程,本文也對(duì)BDD的概念做了詳細(xì)的解釋,需要的朋友可以參考下2015-04-04NumPy實(shí)現(xiàn)從已有的數(shù)組創(chuàng)建數(shù)組
本文介紹了NumPy中如何從已有的數(shù)組創(chuàng)建數(shù)組,包括使用numpy.asarray,numpy.frombuffer和numpy.fromiter方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-10-10