gpt4 book ai didi

python - Tensorflow 变量不初始化

转载 作者:太空宇宙 更新时间:2023-11-04 05:01:48 24 4
gpt4 key购买 nike

我正在尝试找出为什么在下面的两种方法中,方法 2 在我尝试初始化 Tensorflow 中的变量时抛出错误

import tensorflow as tf
sess = tf.InteractiveSession()

方法一

这个方法工作正常返回正确的输出

with tf.variable_scope('layer_1'):
W1 = tf.get_variable(name="weights1", shape=[3, 10], initializer=tf.zeros_initializer())

sess.run(tf.global_variables_initializer())

print(sess.run(W1))

方法二

此方法会引发错误。

with tf.variable_scope('layer_2'):
W2 = tf.get_variable(tf.zeros(shape=[3, 10], name="weights2"))

sess.run(tf.global_variables_initializer())

print(sess.run(W2))

我收到的方法 2 的错误消息是:

TypeError: Expected float32, got 'layer_2/' of type 'str' instead.

最佳答案

tf.get_variable 的第一个(位置)参数是变量的名称。所以你的第二个代码等同于

tf.get_variable(name=tf.zeros(shape=[3, 10], name="weights2"))

尝试使用 tf.Tensor 作为变量名是行不通的(我很惊讶它之前没有给出错误)。

你也许想做

tf.Variable(tf.zeros(shape=[3, 10]), name="weights2")

关于python - Tensorflow 变量不初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45537257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com