類別 | 解釋 | 樣例 |
---|---|---|
tf.truncated_normal() | 去掉過大偏離點的正態分布 | |
tf.random_uniform() | 平均分布 | |
tf.zeros | 全0數組 | tf.zeros([3,2],int32)生成[[0,0],[0,0],[0,0]] |
tf.ones | 全1數組 | tf.ones([3,2],int32)生成[[1,1],[1,1],[1,1]] |
tf.fill | 全定值數組 | tf.fill([3,2],6)生成[[6,6],[6,6],[6,6]] |
tf.constant | 直接給值 | tf.constant([3,2,1])生成[3,2,1] |
神經網絡實現過程:
1.準備數據集,提取特征,作為輸入,傳給神經網絡
2.搭建NN結構,從輸入到輸出(先搭建計算圖,再用會話執行)(NN前向傳播算法——計算輸出)
3.大量特征數據傳給NN,迭代優化NN參數(NN反向傳播算法——優化參數訓練模型)
4.使用訓練好的模型預測和分類
前向傳播 搭建模型,實現推理
變量初始化、計算圖節點運算都要用會話(with結構)實現
with tf.Session() as sess:
sess.run()
變量初始化:在sess.run函數中用tf.global_variables_initializer()
init_op = tf.global_variables_initializer()
sess.run(init_op)
計算圖節點運算:在sess.run函數中寫入待運算的節點
\sess.run()
用tf.placeholder占位,在sess.run函數中用feed_dict喂數據
喂一組數據
x = tf.placeholder(tf.float32,shape=(1,2))
sess.run(y,feed_dict={x:[[0.5,0.6]]})
喂多組數據
x = tf.placeholder(tf.float32,shape=(1,2))
sess.run(y,feed_dict = {x:[[0.5,0.6]]})
#兩層簡單神經網絡(全連接)
#定義輸入和參數
x = tf.constant([[0.7,0.5]])
w1 = tf.Variable(tf.random_normal([2,3], stddev=1, seed=1 ))
w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))
#定義前向傳播過程
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
#用會話計算結果
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(y))
# 用placeholder實現輸入定義(sess.run中喂一組數據)
x = tf.placeholder(tf.float32, shape=(1,2))
w1 = tf.Variable(tf.random_normal([2,3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))
#定義前向傳播過程
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
#用會話計算結果
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(y, feed_dict={x:[[0.7,0.5]]}))
# 用placeholder實現輸入定義(sess.run中喂多組數據)
x = tf.placeholder(tf.float32, shape=(None,2))
w1 = tf.Variable(tf.random_normal([2,3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3,1], stddev=1, seed=1))
#定義前向傳播過程
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
#用會話計算結果
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(y, feed_dict={x:[[0.7,0.5],[0.2,0.3],[0.3,0.4],[0.4,0.5]]}))
print(sess.run(w1))
print(sess.run(w2))