首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >仅对张量的正元素应用tf.nn.softmax()

仅对张量的正元素应用tf.nn.softmax()
EN

Stack Overflow用户
提问于 2018-06-20 00:31:48
回答 2查看 677关注 0票数 1

我花了很长时间来解决这个问题,但在互联网上找不到任何有用的东西,所以我不得不问:

给定一个张量T,假设是T = tf.random_normal([100]),我只想将softmax()应用于张量的正元素。像T = tf.nn.softmax(T[T>0])这样的东西,当然不能在Tensorflow中工作。

简而言之:我想计算softmax,并且只应用于元素T > 0

我如何在Tensorflow中做到这一点?

EN

回答 2

Stack Overflow用户

发布于 2018-06-20 00:39:31

一个想法可能是基于您的条件(T > 0)创建2个分区,将操作(softmax)应用于目标分区,然后将它们缝合在一起。

如下所示,使用tf.dynamic_partitiontf.dynamic_stitch

代码语言:javascript
复制
import tensorflow as tf

T = tf.random_normal(shape=(2, 3, 4))

# Creating partition based on condition:
condition_mask = tf.cast(tf.greater(T, 0.), tf.int32)
partitioned_T = tf.dynamic_partition(T, condition_mask, 2)
# Applying the operation to the target partition:
partitioned_T[1] = tf.nn.softmax(partitioned_T[1])

# Stitching back together, flattening T and its indices to make things easier::
condition_indices = tf.dynamic_partition(tf.range(tf.size(T)), tf.reshape(condition_mask, [-1]), 2)
res_T = tf.dynamic_stitch(condition_indices, partitioned_T)
res_T = tf.reshape(res_T, tf.shape(T))

with tf.Session() as sess:
    t, res = sess.run([T, res_T])
    print(t)
    # [[[-1.92647386  0.7442674   1.86053932 -0.95315439]
    #  [-0.38296485  1.19349718 -1.27562618 -0.73016083]
    #  [-0.36333972 -0.90614134 -0.15798278 -0.38928652]]
    # 
    # [[-0.42384467  0.69428021  1.94177043 -0.13672788]
    #  [-0.53473723  0.94478583 -0.52320045  0.36250541]
    #  [ 0.59011376 -0.77091616 -0.12464728  1.49722672]]]
    print(res)
    # [[[-1.92647386  0.06771058  0.20675084 -0.95315439]
    #  [-0.38296485  0.10610957 -1.27562618 -0.73016083]
    #  [-0.36333972 -0.90614134 -0.15798278 -0.38928652]]
    # 
    # [[-0.42384467  0.06440912  0.22424641 -0.13672788]
    #  [-0.53473723  0.08274478 -0.52320045  0.04622314]
    #  [ 0.05803747 -0.77091616 -0.12464728  0.14376813]]]

上一个答案

仅当您希望对T的所有元素计算softmax,但仅适用于大于0的元素时,此答案才有效。

使用tf.where()

代码语言:javascript
复制
T = tf.where(tf.greater(T, 0.), tf.nn.softmax(T), T)
票数 4
EN

Stack Overflow用户

发布于 2018-06-20 04:15:43

我是Tensorflow的新手,但这是我的尝试,基于数学公式:

代码语言:javascript
复制
def softmax_positiv(T):
    # softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)
    Tsign = tf.greater(T, 0.)
    Tpos = tf.gather(T, tf.where(Tsign))
    _reduce_sum = tf.reduce_sum(tf.exp(Tpos))
    Tsign = tf.cast(Tsign, tf.float32)    
    Tpos = (tf.exp(T) / _reduce_sum) * Tsign
    Tneg = (Tsign - 1) * -1 * T

  return Tpos+Tneg

更新版本(使用@Aldream建议):

代码语言:javascript
复制
def softmax_positiv(T):
    #softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)
    Tsign=tf.greater(T,0)
    _reduce_sum=tf.reduce_sum(tf.exp(tf.where(Tsign,T,tf.zeros(T.shape))))
    return  tf.where(Tsign, tf.exp(T) / _reduce_sum, T)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50933075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档