如何在 Tensorflow 的一层中对部分神经元使用激活函数 [英] How to use activation function on part neurons from one layer in Tensorflow

查看:27
本文介绍了如何在 Tensorflow 的一层中对部分神经元使用激活函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,有一个张量

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] 的元素使用激活函数.

I would only like to use activation on the elements (from a) whose index are with value 1 (from b). For example, I only want to use activation function on the elements from a with the indices [0,0], [0,2], [1,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 ]]

这篇关于如何在 Tensorflow 的一层中对部分神经元使用激活函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆