如何创建一个层来反转softmaxTensforFlow,python?

问题描述

我正在建立一个反卷积网络。我想在上面添加一层,这是softmax的反面。我试图编写一个基本的python函数,该函数返回给定矩阵的softmax的逆并将其放在tensorflow Lambda中并将其添加到我的模型中。 我没有错误,但是在进行预测时,出口处只有0。当我不将此层添加到我的网络时,我输出的不是零。因此,这证明它们归因于我的inv_softmax函数错误的。 您能启发我如何进行吗?

我将函数定义为:

def inv_softmax(x):
   C=0
   S = np.zeros((1,1,10)) #(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,j])
      for i in range(np.max(np.shape(x))):
         S[0,i] = np.log(x[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,10])(x)
x = ...

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

解决方法

尝试一下:

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())
,

谢谢! 我放了:

import keras.backend as K

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