How to create a layer to invert a softmax (TensforFlow,python)?

谁都会走 提交于 2021-02-05 12:08:26

问题


I am building a deconvolution network. I would like to add a layer to it which is the reverse of a softmax. I tried to write a basic python function that returns the inverse of a softmax for a given matrix and put that in a tensorflow Lambda and add it to my model. I have no error but when I doing a predict I only have 0 at the exit. When I don't add this layer to my network I have output something other than zeros. This therefore justifies that they are due to my inv_softmax function which is bad. Can you enlighten me how to proceed?

I define my funct as this :

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

I add it to my network as :

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

If you need more of my code or others informations ask me please.


回答1:


Try this:

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



回答2:


Thanks it works ! I put :

import keras.backend as K

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


来源:https://stackoverflow.com/questions/64663867/how-to-create-a-layer-to-invert-a-softmax-tensforflow-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!