1. 程式人生 > >python神經網路前向傳播

python神經網路前向傳播

####### 隨機變數初始化

#正態分佈,去掉種子點後,每次產生的隨機數不一樣
w = tf.Variable(tf.random_normal([2.3], stddev = 2, mean = 0, seed = 1))

#去掉過大偏離點的正態分佈
w = tf.Variable(tf.truncated_normal([2.3], stddev = 2, mean = 0, seed = 1))

#平均分佈
w = tf.Variable(tf.random_uniform([2.3], stddev = 2, mean = 0, seed = 1))

#全0,3行2列
tf.
zeros([3,2], int 32) #全1,3行2列 tf.ones([3,2], int 32) #全6,3行2列 tf.fill([3,2], 6) #常數張量,直接給值 tf.constant([3,2,1])

######神經網路前向傳播流程

# 變數初始化、計算圖節點運算,用會話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(y) #喂一組/多組資料給sess.run函式 #tf.placeholder佔位 #feed_dict喂資料 #1.喂一組 x = tf.placeholder(tf.float32, shape = (1,2)) sess.run(y,feed_dict = {x:[[0.5, 0.6]]}) #2.喂多組 x = tf.placeholder(tf.float32, shape = (None, 2)) #未知資料數目 sess.run(y,
feed_dict = {x:[[0.1, 0.2], [0.2, 0.3], [0.3, 0.4]]})

##########完整程式碼之輸入一組資料x

# coding:uft-8
# 兩層全連線神經網路
import tensorflow as tf

# 定義輸入和引數
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("y in test.py is:\n",sess.run(y))

###########完整程式碼二之輸入未知的一組資料x

# coding:utf-8 

import tensorflow as tf

# 用placeholder實現輸入定義
x = tf.placeholder(tf.float32, shape = (1, 2)) #多組時改shape中1為None
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("y in test.py is:\n",sess.run(y, feed_dict = {x: [[0.7, 0.5]]}))

##############完整程式碼之輸入未知的若干組資料x

# coding:utf-8 

import tensorflow as tf

# 用placeholder實現輸入定義
x = tf.placeholder(tf.float32, shape = (None, 2)) #多組時改shape中1為None
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("y in test.py is:\n",sess.run(y, feed_dict = {x: [[0.7, 0.5], [0.2, 0.3], [0.3, 0.4], [0.4,0.5]]}))
	print("w1:\n", sess.run(w1))
	print("w2:\n", sess.run(w2))