如何创建一个层来反转 softmax (TensorFlow,python)?
How to create a layer to invert a softmax (TensforFlow,python)?
我正在构建一个反卷积网络。我想给它添加一个与 softmax 相反的层。我尝试编写一个基本 python 函数,该函数 returns 给定矩阵的 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 = ...
如果您需要我的更多代码或其他信息,请问我。
试试这个:
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)
我正在构建一个反卷积网络。我想给它添加一个与 softmax 相反的层。我尝试编写一个基本 python 函数,该函数 returns 给定矩阵的 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 = ...
如果您需要我的更多代码或其他信息,请问我。
试试这个:
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)