为什么我不能 运行 张量并得到错误 "the variable was uninitialized"

Why I cannot run a tensor and got error "the variable was uninitialized"

我正在使用 tensorflow 1.15.0。

我正在尝试使用 sess.run() 获取 keras 层输出值。而且我确定我已经指定了层输入形状,并且我可以看到具有正确形状的输出张量。但是当我尝试获取张量值时,出现了错误。

代码如下:

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

sess = tf.Session()
layer = layers.Dense(3)
x = tf.ones((1, 4))
y = layer(x)
layer.weights # I want to get weights value, print it first

结果符合预期:

[<tf.Variable 'dense/kernel:0' shape=(4, 3) dtype=float32>,
<tf.Variable 'dense/bias:0' shape=(3,) dtype=float32>]

但是当我试图获取张量值时:

sess.run(layer.weights[0])

弹出很长的错误信息:(以下为核心信息)

FailedPreconditionError: Error while reading resource variable dense/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense/kernel)

有人可以帮我解决这个问题吗?谢谢。

您可能需要先初始化变量(在密集层中),然后再使用它们,例如 tf.global_variables_initializer。尝试在声明变量之后但在使用它们之前添加以下行:

sess.run(tf.global_variables_initializer())

您也可以调用 tf.variables_initializer 从列表中初始化变量。