利用TensorFlow訓練簡單的二分類神經網路模型的方法,tensorflow神經網路

來源:互聯網
上載者:User

利用TensorFlow訓練簡單的二分類神經網路模型的方法,tensorflow神經網路

利用TensorFlow實現《神經網路與機器學習》一書中4.7模式分類練習

具體問題是將如所示雙月牙資料集分類。

使用到的工具:

python3.5    tensorflow1.2.1   numpy   matplotlib

1.產生雙月環資料集

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) #類別標籤為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) #類別標籤為-1,注意:由於採取雙曲正切函數作為啟用函數,類別標籤不能為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為月環半徑,w為月環寬度,d為上下月環距離(與書中一致)

2.利用TensorFlow搭建神經網路模型

2.1 神經網路層添加

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建立神經網路模型

輸入層大小:2

隱藏層大小:20

輸出層大小:1

啟用函數:雙曲正切函數

學習率: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])) ###最佳化器選取 學習率設定 此處學習率置為0.1 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) ###tensorflow變數初始化,開啟會話 init = tf.global_variables_initializer()#tensorflow更新後初始化所有變數不再用tf.initialize_all_variables() sess = tf.Session() sess.run(init) 

2.3 訓練模型

###訓練2000次 for i in range(2000):   sess.run(train_step, feed_dict={xs: x_data, ys: y_label}) 

3.利用訓練好的網路模型尋找分類決策邊界

3.1 產生二維空間隨機點

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 用訓練好的模型採集決策邊界附近的點

向網路輸入一個二維空間隨機點,計算輸出值大於-0.5小於0.5即認為該點落在決策邊界附近(雙曲正切函數)

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工具將採集到的邊界附近點擬合成決策邊界曲線,用matplotlib.pyplot畫圖

###產生空間隨機資料   X_NUM = produce_random_data(10, 6, -4, 5000)   ###邊界資料採樣   X_b = collect_boundary_data(X_NUM)   ###畫出資料   fig = plt.figure()   ax = fig.add_subplot(1, 1, 1)   ###設定座標軸名稱   plt.xlabel('x1')   plt.ylabel('x2')   ax.scatter(x_data[:, 0], x_data[:, 1], marker='x')   ###用採樣的邊界資料擬合邊界曲線 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去做吧.....我只是用這做書上的練習而已。

(初學者水平有限,有問題請指出,各位大佬輕噴)

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.