gpt4 book ai didi

python - tensorflow 无法初始化某些变量

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:41 24 4
gpt4 key购买 nike

我使用以下代码来初始化 tensorflow 中的某些变量。令我惊讶的是,我得到的变量“V”是一个空列表,而其他变量是合理的数字。仅当我注释 weights_W 的代码时,我才能获取“V”的值。

我是 tensorflow 新手。我搞砸了什么吗?

代码:

import math
import tensorflow as tf

layer_sizes = [4, 5, 3]
shapes = zip(layer_sizes[:-1], layer_sizes[1:])
L = len(layer_sizes)-1

def bi(inits, size, name):
return tf.Variable(inits * tf.ones([size]), name=name)

def wi(shape, name):
return tf.Variable(tf.random_normal(shape, name=name)) / math.sqrt(shape[0])

weights_W = {'W': [wi(s, "W") for s in shapes]}
weights_V = {'V': [wi(s[::-1], "V") for s in shapes]}
bias_b = {'beta': [bi(0.0, layer_sizes[l+1], "beta") for l in range(L)]}
bias_g = {'gamma': [bi(1.0, layer_sizes[l+1], "gamma") for l in range(L)]}

init = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init)
print(sess.run(weights_W))
print(sess.run(weights_V))
print(sess.run(bias_b))
print(sess.run(bias_g))

输出:

{'W': [array([[ 0.87929118, -1.52028453, -0.25481933, -0.0707642 ,  0.21771625],
[-0.46657208, -0.08346261, 0.18036443, -0.75888193, 0.41950777],
[-0.7241388 , 0.08610565, -0.6172654 , -0.40768555, 0.24912448],
[ 0.38304791, -0.16632535, 1.0700382 , -0.06679908, -0.68657762]], dtype=float32), array([[-0.37793589, -0.14964254, -0.56092912],
[-0.18630502, -0.31269881, 0.25770813],
[-0.12167504, -0.20703614, -0.06239036],
[ 0.35287923, -0.67617333, -0.01133266],
[ 0.24189886, -0.34389392, 0.0007165 ]], dtype=float32)]}
{'V': []}
{'beta': [array([ 0., 0., 0., 0., 0.], dtype=float32), array([ 0., 0., 0.], dtype=float32)]}
{'gamma': [array([ 1., 1., 1., 1., 1.], dtype=float32), array([ 1., 1., 1.], dtype=float32)]}

我在 python 3.5.4 中使用 tensorflow 1.2.1,没有 GPU。

感谢您的帮助。

最佳答案

这是因为 zip 返回一个迭代器,并且您只能迭代它一次。

您可以制作一个 zip 列表并使用它。

shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))

关于python - tensorflow 无法初始化某些变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47650542/

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