1.4激活函数-带隐层的神经网络tf实战
生活随笔
收集整理的這篇文章主要介紹了
1.4激活函数-带隐层的神经网络tf实战
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
激活函數
激活函數----日常不能用線性方程所概括的東西
左圖是線性方程,右圖是非線性方程
當男生增加到一定程度的時候,喜歡女生的數量不可能無限制增加,更加趨于平穩
在線性基礎上套了一個激活函數,使得最后能得到輸出結果
常用的三種激活函數:
取值不同時得到的結果也不同
常見激活函數圖形
?
?
tensorflow中自帶的激活函數舉例:
?
?添加隱層的神經網絡
?
#添加隱層的神經網絡結構 import tensorflow as tfdef add_layer(inputs,in_size,out_size,activation_function=None):#定義權重--隨機生成inside和outsize的矩陣Weights=tf.Variable(tf.random_normal([in_size,out_size]))#不是矩陣,而是類似列表biaes=tf.Variable(tf.zeros([1,out_size])+0.1)Wx_plus_b=tf.matmul(inputs,Weights)+biaesif activation_function is None: outputs=Wx_plus_b else: outputs=activation_function(Wx_plus_b) return outputs import numpy as np x_data=np.linspace(-1,1,300)[:,np.newaxis] #300行數據 noise=np.random.normal(0,0.05,x_data.shape) y_data=np.square(x_data)-0.5+noise #None指定sample個數,這里不限定--輸出屬性為1 xs=tf.placeholder(tf.float32,[None,1]) #這里需要指定tf.float32, ys=tf.placeholder(tf.float32,[None,1]) #建造第一層layer #輸入層(1) l1=add_layer(xs,1,10,activation_function=tf.nn.relu) #隱層(10) prediction=add_layer(l1,10,1,activation_function=None) #輸出層(1) #預測prediction loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1])) #平方誤差 train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss) init=tf.initialize_all_variables() sess=tf.Session() #直到執行run才執行上述操作 sess.run(init) for i in range(1000): #這里假定指定所有的x_data來指定運算結果 sess.run(train_step,feed_dict={xs:x_data,ys:y_data}) if i%50: print (sess.run(loss,feed_dict={xs:x_data,ys:y_data}))?
?顯示:
1.11593 0.26561 0.167872 0.114671 0.0835957 0.0645237 0.0524448 0.0446363 0.039476 0.0360211 0.0336599 0.0320134 0.0308378 0.0299828 0.029324 0.0287996 0.0283558 0.0279624 0.0276017 0.02726 0.0269316 0.0266103 0.026298 0.0259914 0.0256905 0.025395 0.0251055 0.0248204 0.024538 0.0242604 0.023988 0.0237211 0.0234583 0.0231979 0.0229418 0.0226901 0.0224427 0.0221994 0.0219589 0.0217222 0.0214888 0.0212535 0.0210244 0.0207988 0.0205749 0.0203548 0.0201381?
增加np.newaxis
np.newaxis 為 numpy.ndarray(多維數組)增加一個軸
>> type(np.newaxis) NoneType >> np.newaxis == None Truenp.newaxis 在使用和功能上等價于 None,其實就是 None 的一個別名。
1. np.newaxis 的實用
?
>> x = np.arange(3) >> x array([0, 1, 2]) >> x.shape (3,)>> x[:, np.newaxis] array([[0],[1],[2]])>> x[:, None] array([[0],[1],[2]])>> x[:, np.newaxis].shape(3, 1)2. 索引多維數組的某一列時返回的是一個行向量
>>> X = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) >>> X[:, 1] array([2, 6, 10]) % 這里是一個行 >>> X[:, 1].shape % X[:, 1] 的用法完全等同于一個行,而不是一個列, (3, )如果我們索引多維數組的某一列時,返回的仍然是列的結構,一種正確的索引方式是:
>>>X[:, 1][:, np.newaxis] array([[2],[6],[10]])如果想實現第二列和第四列的拼接(層疊):
>>>X_sub = np.hstack([X[:, 1][:, np.newaxis], X[:, 3][:, np.newaxis]]) % hstack:horizontal stack,水平方向上的層疊 >>>X_sub array([[2, 4][6, 8][10, 12]])當然更為簡單的方式還是使用切片:
>> X[:, [1, 3]] array([[ 2, 4],[ 6, 8],[10, 12]])?
轉載于:https://www.cnblogs.com/jackchen-Net/p/8082506.html
總結
以上是生活随笔為你收集整理的1.4激活函数-带隐层的神经网络tf实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bzoj4237稻草人
- 下一篇: 素数路(prime)