问题描述
我正在建立一个反卷积网络.我想在上面添加一层,这是softmax的反面.我试图编写一个基本的python函数,该函数返回给定矩阵的softmax的逆并将其放在tensorflow Lambda中并将其添加到我的模型中.我没有错误,但是当我做一个预测时,我在出口处只有0.当我不将此层添加到我的网络时,我输出的不是零.因此,这证明它们归因于我的inv_softmax函数是错误的.您能启发我如何进行吗?
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?
我将函数定义为:
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 = ...
如果您需要更多我的代码或其他信息,请问我.
If you need more of my code or others informations ask me please.
推荐答案
尝试一下:
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())
这篇关于如何创建一个层来反转softmax(TensforFlow,python)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!