参数:即计算图中的权重,用变量表示,随机给初值
其中Variable有4种:zeros,ones,fill,constant
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.zeros([3,2,1]) 生成[3,2,1]
eg.生产一批零件将体积想x1和重量x2为特征的输入NN,通过NN后输出一个数值
使用TensorFlow表示上例
计算结果要用到会话
# coding:utf-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 tf05前向传播 is:\n", sess.run(y))
# 结果:
# [[3.0904665]]
# coding:utf-8
# 前向传播
# 两层简单神经网络(全连接)
import tensorflow as tf
# 定义输入和参数
# 用placeholder实现输入自定义(sess.run中喂1组数据)
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("y in tf05forward2 is:\n", sess.run(y, feed_dict={x:[[0.7,0.5]]}))
# 结果:
# [[3.0904665]]
# coding:utf-8
# 前向传播
# 两层简单神经网络(全连接)
# 向神经网络喂入n组特征
import tensorflow as tf
# 定义输入和参数
# 用placeholder实现输入自定义(sess.run中喂多组数据)None表示未知
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("y in tf05forward2 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:", sess.run(w1))
print("w2:", sess.run(w2))
前向传播就到这里了
TensorFlow笔记-04-神经网络的实现过程,前向传播
原文:https://www.cnblogs.com/xpwi/p/9609119.html