agent
和prior
是根据存储的图形和权重初始化的两个预先设置的Keras功能模型。
然后我定义一个损失函数:
agent_logits = K.cast(K.max(agent_output, axis = 2), dtype = tf.float32)
prior_logits = K.cast(K.min(prior_output, axis = 2), dtype = tf.float32)
p_a_prior = K.sum(K.log(prior_logits), axis = 1)
p_a_agent = K.sum(K.log(agent_logits), axis = 1)
loss = K.mean(K.square(p_a_agent - p_a_prior))
然后我尝试计算梯度:
grads = tf.gradients(loss, agent.trainable_weights)
我收到此错误:
AttributeError Traceback (most recent call last)
<ipython-input-28-435dabc8f049> in <module>()
40 # return grad, tf.negative(grad)
41
---> 42 grads = tf.gradients(loss, agent.trainable_weights)
43 # grads = _compute_gradients(loss, agent.trainable_weights)
44 print('[agent.inputs] = ', agent.inputs)
~/anaconda3/envs/hw3/lib/python3.5/site-packages/tensorflow/python/ops/gradients_impl.py in gradients(ys, xs, grad_ys, name, colocate_gradients_with_ops, gate_gradients, aggregation_method, stop_gradients)
488 pending_count, loop_state = _PendingCount(ops.get_default_graph(), to_ops,
489 from_ops,
--> 490 colocate_gradients_with_ops)
491
492 # Iterate over the collected ops.
~/anaconda3/envs/hw3/lib/python3.5/site-packages/tensorflow/python/ops/gradients_impl.py in _PendingCount(graph, to_ops, from_ops, colocate_gradients_with_ops)
169 for op in to_ops:
170 reached_ops[op._id] = True
--> 171 _MarkReachedOps(from_ops, reached_ops)
172
173 # Mark between ops.
~/anaconda3/envs/hw3/lib/python3.5/site-packages/tensorflow/python/ops/gradients_impl.py in _MarkReachedOps(from_ops, reached_ops)
115 while queue:
116 op = queue.popleft()
--> 117 if not reached_ops[op._id]:
118 reached_ops[op._id] = True
119 for output in op.outputs:
~/anaconda3/envs/hw3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py in _id(self)
1635 def _id(self):
1636 """The unique integer id of this operation."""
-> 1637 return self._id_value
1638
1639 @property
AttributeError: 'Operation' object has no attribute '_id_value'
有人可以给我一些建议吗?
答案 0 :(得分:1)
由于您是直接使用后端的,所以我认为您还需要从后端使用gradients
方法:
grads = K.gradients(...)