在学习TensorFlow实战Google深度学习框架(第2版)3.4.2节时,想自己演示下前向传播过程
代码如下:
import tensorflow as tf
x = tf.constant([0.7, 0.9], name = "x", dtype = tf.float32)
w1 = tf.constant([[0.2, 0.1, 0.4], [0.3, -0.5, 0.2]], name = "w1",
dtype = tf.float32)
w2 = tf.constant([[0.6], [0.1], [-0.2]], name = "w2", dtype = tf.float32)
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
with tf.Session() as sess:
print(sess.run(a))
print(sess.run(y))
出现错误:ValueError: Shape must be rank 2 but is rank 1 for ‘MatMul_5’ (op: ‘MatMul’) with input shapes: [2], [2,3].
将a和b的那两句注释掉,打印x,w1,w2看看,输出为
[0.7 0.9]
[[ 0.2 0.1 0.4]
[ 0.3 -0.5 0.2]]
[[ 0.6]
[ 0.1]
[-0.2]]
好像又没有问题,百度后修改代码如下
import tensorflow as tf
import numpy as np
x = tf.constant(np.array([0.7, 0.9]).reshape(1, 2), name = "x",
dtype = tf.float32)
w1 = tf.constant(np.array([[0.2, 0.1, 0.4], [0.3, -0.5, 0.2]]).reshape(2, 3),
name = "w1", dtype = tf.float32)
w2 = tf.constant(np.array([[0.6], [0.1], [-0.2]]).reshape(3, 1), name = "w2",
dtype = tf.float32)
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
with tf.Session() as sess:
print(sess.run(a))
print(sess.run(y))
正确输出了,输出结果为:
[[ 0.41000003 -0.38 0.45999998]]
[[0.11600002]]