神經網絡基本結構:輸入層,隱含層和輸出層
上圖說明:在輸入層輸入數據,然後數據飛到隱藏層,最後飛到輸出層,用梯度下降處理,梯度下降會對幾個參數進行更新和完善,更新後的參數再次跑到隱藏層去學習,一直循環至結果收斂。
神經網絡內部結構參數:
激勵函數:這些函數與其他層的輸出聯合使用可生成特徵途。用於對某些運算的結果進行平滑(或微分),目標是爲神經網絡引入非線性。激勵函數種類:tf.nn.relu、tf.nn.relu6、tf.nn.crelu、tf.nn.elu、tf.nn.selu、tf.nn.softplus、tf.nn.softsign、tf.nn.dropout、tf.nn.bias_add、tf.sigmoid、tf.tanh。
**函數特性:
滿足此類條件均可作爲**函數。
神經層:
定義神經網絡參數有inputs,in_size,out_size,和activation_function,其內部定義變量包含:權值weights、偏差biases、計算公式。若爲分類問題,需要添加交叉熵函數cross_entropy。
def add_layer(inputs,in_size,out_size,activation_function=None):
weights=tf.Variable(tf.random_normal([in_size,out_size]))
biases=tf.Variable(tf.zeros([1,out_size])+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
cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),
reduction_indices=[1]))
train_step=tf.train.GradientDescentOptimize(0.5).minimize(cross_entropy)
overfitting過擬合:
採用Tensorflow中的dropout,用來降低cnn網絡中過擬合現象的工具。
dropout是指在深度學習網絡的訓練中,針對神經網絡單元,按照一定的概率將其暫時從網絡中丟棄。對於隨機梯度下降來說,由於是隨機丟棄,故而每一個mini-batch都在訓練不同的網絡。
代碼實現:在add layer函數里加上dropout,keep_prob是一個概率,保持多少的概率不被丟棄,在迭代時繼續執行sess.run,當某個特徵被丟棄時,其值設爲0.0。
#here to dropout
#在wx_plus_b上drop掉一定比例
#keep_prob保持多少不被drop,在迭代時在sess.run中feed
wx_plus_b=tf.nn.dropout(wx_plus_b,keep_prob)
1.使用import導入需要的庫信息
2.定義添加神經層的函數(定義出參數Weights,biases,擬合公式y,誤差公式loss)
def add_layer(inputs,in_size,out_size,activation=None):
3.訓練數據的準備(導入或者隨機定義訓練的數據)
4.使用tf.placeholder()定義節點準備接收數據
5.定義神經層:隱藏層和預測層 (上一層的輸出即爲下一層的輸入)
l1=add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction=add_layer(l1,10,1,activation_function=None)
6.定義 loss 表達式
loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys_prediction),reduction_indices=[1]))
7.選擇 optimizer 使 loss 達到最小
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)
#採用的優化方法是GradientDescentOptimizer(),即梯度下降法
#學習率爲0.1
8.所有變量進行初始化
tf14.0版初始化變量:init=tf.global_variables_initialize()
sess=tf.Session()
sess.run(init) #開始運算
9.通過 sess.run optimizer,迭代 1000 次進行學習。
完整代碼例子:
import tensorflow as tf
import numpy as np
#2.添加層
def add_layer(inputs,in_size,out_size,activation_function=None):
#add one more layer and return the output of this layer
weights=tf.Variable(tf.random_normal([in_size,out_size]))
biases=tf.Variable(tf.zeros([1,out_size])+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
#### 3.訓練的數據
#### Make up some real data
x_data = np.linspace(-1,1,300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
#### 4.定義節點準備接收數據
#### define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
#### 5.定義神經層:隱藏層和預測層
#### add hidden layer 輸入值是 xs,在隱藏層有 10 個神經元
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
#### add output layer 輸入值是隱藏層 l1,在預測層輸出 1 個結果
prediction = add_layer(l1, 10, 1, activation_function=None)
#### 6.定義 loss 表達式
#### the error between prediciton and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
#### 7.選擇 optimizer 使 loss 達到最小
#### 這一行定義了用什麼方式去減少 loss,學習率是 0.1
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
#### 8. important step 對所有變量進行初始化
init = tf.global_variables_initializer()
sess = tf.Session()
#### 上面定義的都沒有運算,直到 sess.run 纔會開始運算
sess.run(init)
#### 9. 迭代 1000 次學習,sess.run optimizer
for i in range(1000):
# training train_step 和 loss 都是由 placeholder 定義的運算,所以這裏要用 feed 傳入參數
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
# to see the step improvement
print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
運行完代碼結果如下圖:
出現Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2這個提示,不影響最後結果。在網上查了其原因,大致意思是說:這是個編譯問題,tensorflow覺得你的電腦CPU還行,支持AVX(Advanced Vector Extensions),但CPU沒有得到充分的利用,不能使用SSE4.1 SSE4.2 AVX AVX2 FMA這些指令集進行編譯,運行速度還可提升,可開啓更好更快的模式。從官網下載源碼不會出現這種問題,如果用GPU可以忽略此警告,
添加代碼:import os
os.environ['TF_CPP_MIN_LOG_LEVER']='2'