首页 文章

张量流量梯度

提问于
浏览
4

我正在尝试调整tf DeepDream教程代码以使用其他模型 . 现在我打电话给tf.gradients()时:

t_grad = tf.gradients(t_score, t_input)[0]
g      = sess.run(t_grad, {t_input:img0})

我收到类型错误:

TypeError: Fetch argument None of None has invalid type <type 'NoneType'>,     
must be a string or Tensor. (Can not convert a NoneType into a Tensor or 
Operation.)

我应该在哪里开始寻找修复此错误?

是否可以将tf.gradients()与其中包含Optimizer的模型一起使用?

2 回答

  • 5

    我猜你的 t_grad 有一些 None . None 在数学上等效于0渐变,但是当成本没有't depend on the argument it is differentiated against. There are various reasons why we don' t只返回0而不是 None 时会返回特殊情况,您可以在讨论中看到here

    因为 None 在上面的情况下可能很烦人,或者在计算二阶导数时,我使用下面的辅助函数

    def replace_none_with_zero(l):
      return [0 if i==None else i for i in l]
    
  • 2

    以下是调试 tf.gradients() 的有用提示

    对于一对无效的张量:

    grads = tf.gradients(<a tensor>, <another tensor that doesn't depend on the first>)
    

    甚至在您尝试在会话中运行 tf.gradients 之前,您可以使用 print 看到它无效

    print grads
    

    它将返回 [None] 一个列表,其中包含一个 None .

    如果您尝试在会话中运行它:

    results = sess.run(grads)
    

    您不会再次获得 None ,而是会收到问题中描述的错误消息 .

    对于一对有效的张量:

    grads = tf.gradients(<a tensor>, <a related tensor>)
    print grads
    

    你会得到类似的东西:

    Tensor("gradients_1/sub_grad/Reshape:0", dtype=float32)
    

    在有效的情况下:

    results = sess.run(grads, {<appropriate feeds>})
    print results
    

    你会得到类似的东西

    [array([[ 4.97156498e-06, 7.87349381e-06, 9.25197037e-06, ..., 8.72526925e-06, 6.78442757e-06, 3.85240173e-06], [ 7.72772819e-06, 9.26370740e-06, 1.19129227e-05, ..., 1.27088233e-05, 8.76379818e-06, 6.00637532e-06], [ 9.46506498e-06, 1.10620931e-05, 1.43903117e-05, ..., 1.40718612e-05, 1.08670165e-05, 7.12365863e-06], ..., [ 1.03536004e-05, 1.03090524e-05, 1.32107480e-05, ..., 1.40605653e-05, 1.25974075e-05, 8.90011415e-06], [ 9.69486427e-06, 8.18045282e-06, 1.12702282e-05, ..., 1.32554378e-05, 1.13317501e-05, 7.74569162e-06], [ 5.61043908e-06, 4.93397192e-06, 6.33513537e-06, ..., 6.26539259e-06, 4.52598442e-06, 4.10689108e-06]], dtype=float32)]

相关问题