####### 随机变量初始化
#正态分布,去掉种子点后,每次产生的随机数不一样
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))