首页 > 解决方案 > 如何创建一个层来反转softmax(TensforFlow,python)?

问题描述

我正在建立一个反卷积网络。我想添加一个与softmax相反的层。我尝试编写一个基本的 Python 函数,该函数返回给定矩阵的 softmax 的倒数,并将其放入 tensorflow Lambda 中并将其添加到我的模型中。我没有错误,但是当我进行预测时,出口处只有 0。当我不将此层添加到我的网络时,我输出的不是零。因此,这证明它们是由于我的 inv_softmax 函数不好。你能告诉我如何进行吗?

我将我的功能定义为:

def inv_softmax(x):
   C=0
   S = np.zeros((1,1,10)) #(1,1,10) is the shape of the datas that my layer will receive
   try:
      for j in range(np.max(np.shape(x))):
         C+=np.exp(x[0,0,j])
      for i in range(np.max(np.shape(x))):
         S[0,0,i] = np.log(x[0,0,i]+C
   except ValueError:
      print("ValueError in inv_softmax")
      pass
   S = tf.convert_to_tensor(S,dtype=tf.float32)
   return S

我将它添加到我的网络中:

x = ...
x = layers.Lambda(lambda x : inv_softmax(x),name='inv_softmax',output_shape=[1,1,10])(x)
x = ...

如果您需要更多我的代码或其他信息,请询问我。

标签: pythontensorflowdeep-learningsoftmaxdeconvolution

解决方案


试试这个:

import tensorflow as tf

def inv_softmax(x, C):
   return tf.math.log(x) + C

import math
input = tf.keras.layers.Input(shape=(1,10))
x = tf.keras.layers.Lambda(lambda x : inv_softmax(x, math.log(10.)),name='inv_softmax')(input)
model = tf.keras.Model(inputs=input, outputs=x)

a = tf.zeros([1, 1, 10])
a = tf.nn.softmax(a)
a = model(a)
print(a.numpy())

推荐阅读