python - 如何创建一个层来反转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 = ...
如果您需要更多我的代码或其他信息,请询问我。
解决方案
试试这个:
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())
推荐阅读
- javascript - 由于函数的执行顺序,重定向不起作用
- ruby-on-rails - cookie-http-only 会话应该如何在具有单独 API 服务器的 SPA 上工作?
- java - 应用程序在带有 Java 11 的 Ubuntu 19 上引发错误
- ios - 在 Swift 中将 webVTT 用于 AVPlayer 的一些示例,包括标题?
- javascript - 使 Chrome 扩展程序在后台运行
- ios - 浏览文件并希望在服务器上上传
- flutter - Flutter- Drawer 和 Listview.Builder() 出错
- python - 在匹配到列表后使用正则表达式(Python)循环
- javascript - 关闭和重置模态对话框
- html - CSS居中div在其他