TensorFlow实战Google深度学习框架(第2版)学习3.4.2前向传播算法简介:

在学习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]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值