【问题标题】:How to use activation function on part neurons from one layer in Tensorflow如何在Tensorflow中的一层中对部分神经元使用激活函数
【发布时间】:2017-08-16 05:35:15
【问题描述】:

比如有一个张量

a=[[1,2,3,4,5],
  [2,3,4,5,6]]

indices =[[1, 0, 1, 0, 0],
       [0, 1, 0, 0, 0]]

我只想对索引值为 1(来自 b)的元素(来自 a)使用激活。例如,我只想对 a 中索引为 [0,0]、[0,2]、[1,1] 的元素使用激活函数。

谢谢!

【问题讨论】:

  • indices [0,0], [0,1], [1,1] 有错字吗?我想你想要indices [0,0], [0,2], [1,1] ,对吧?
  • 你是对的,我已经修改了这个错字。谢谢。你有我的问题的答案吗?谢谢!
  • 非常感谢,这些功能我都试过了,确实有效。但是非常难用。我认为下面的答案会更有效率。再次感谢您。
  • 是的!!!这个我没试过,但是我觉得如果你编码indices_true = tf.where(a, indices)val = tf.gather_nd(a, indices_true),那么val就会成为你可以在激活函数中使用的张量。

标签: tensorflow


【解决方案1】:

你可以使用tf.where:

tf.where(tf.cast(indices, dtype=tf.bool), tf.nn.sigmoid(a), a)

你的例子:

import tensorflow as tf

a = tf.constant([[1,2,3,4,5], [2,3,4,5,6]], dtype=tf.float32)
indices = tf.constant([[1, 0, 1, 0, 0], [0, 1, 0, 0, 0]], 
dtype = tf.int32)
result = tf.where(tf.cast(indices, dtype=tf.bool), tf.nn.sigmoid(a), a)

with tf.Session() as sess:
  print(sess.run(result))

打印出来:

[[ 0.7310586   2.          0.95257413  4.  5. ]
 [ 2.          0.95257413  4.          5.  6 ]]

【讨论】:

  • 完美解决我的问题的好方法,非常感谢。
猜你喜欢
  • 2018-07-14
  • 2018-03-24
  • 2023-04-03
  • 2020-04-15
  • 2019-12-27
  • 2014-01-18
  • 2017-12-08
  • 1970-01-01
相关资源
最近更新 更多