【发布时间】:2019-08-02 23:30:17
【问题描述】:
获取输出相对于输入的梯度, 可以使用
grads = tf.gradients(model.output, model.input)
毕业生 =
[<tf.Tensor 'gradients_81/dense/MatMul_grad/MatMul:0' shape=(?, 18) dtype=float32>]
这是一个模型,其中有 18 个连续输入和 1 个连续输出。
我假设,这是一个符号表达式,需要一个包含 18 个条目的列表才能将其提供给张量,以便它以浮点数形式给出导数。
我会用
Test =[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]
with tf.Session() as sess:
alpha = sess.run(grads, feed_dict = {model.input : Test})
print(alpha)
但我得到了错误
FailedPreconditionError (see above for traceback): Error while reading resource variable dense_2/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense_2/bias)
[[Node: dense_2/BiasAdd/ReadVariableOp = ReadVariableOp[dtype=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dense_2/bias)]]
怎么了?
编辑: 这是,以前发生过的事情:
def build_model():
model = keras.Sequential([
...])
optimizer = ...
model.compile(loss='mse'... )
return model
model = build_model()
history= model.fit(data_train,train_labels,...)
loss, mae, mse = model.evaluate(data_eval,...)
目前的进展:
Test =[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]
with tf.Session() as sess:
tf.keras.backend.set_session(sess)
tf.initializers.variables(model.output)
alpha = sess.run(grads, feed_dict = {model.input : Test})
也不行,报错:
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
【问题讨论】:
-
如果你运行
out = sess.run(model.output, feed_dict = {model.input : Test})会发生什么?我猜这个错误与梯度无关,但模型本身不知何故丢失了。 -
如果你让它在“with tf.Session() as sess:”中运行,你会得到“FailedPreconditionError(参见上面的回溯):从容器读取资源变量dense_26/bias时出错:localhost。这可能意味着变量未初始化。未找到:容器 localhost 不存在。(找不到资源:localhost/dense_26/bias)[[节点:dense_26/BiasAdd/ReadVariableOp = ReadVariableOp[dtype=DT_FLOAT, _device="/作业:localhost/replica:0/task:0/device:CPU:0"](dense_26/bias)]]"
标签: tensorflow tensorboard tensorflow-datasets tensorflow-estimator