【发布时间】:2018-03-24 12:23:09
【问题描述】:
我试图在不替换整个层的情况下更改 keras 模型最后一层的激活函数。在这种情况下,只有softmax函数
import keras.backend as K
from keras.models import load_model
from keras.preprocessing.image import load_img, img_to_array
import numpy as np
model = load_model(model_path) # Load any model
img = load_img(img_path, target_size=(224, 224))
img = img_to_array(img)
print(model.predict(img))
我的输出:
array([[1.53172877e-07, 7.13159451e-08, 6.18941920e-09, 8.52070968e-07,
1.25813088e-07, 9.98970985e-01, 1.48254022e-08, 6.09538893e-06,
1.16236095e-07, 3.91888688e-10, 6.29304608e-08, 1.79565995e-09,
1.75571788e-08, 1.02110009e-03, 2.14380114e-09, 9.54465733e-08,
1.05938483e-07, 2.20544337e-07]], dtype=float32)
然后我这样做是为了改变激活:
model.layers[-1].activation = custom_softmax
print(model.predict(test_img))
我得到的输出是完全一样的。任何想法如何解决?谢谢!
您可以尝试使用下面的custom_softmax:
def custom_softmax(x, axis=-1):
"""Softmax activation function.
# Arguments
x : Tensor.
axis: Integer, axis along which the softmax normalization is applied.
# Returns
Tensor, output of softmax transformation.
# Raises
ValueError: In case `dim(x) == 1`.
"""
ndim = K.ndim(x)
if ndim >= 2:
return K.zeros_like(x)
else:
raise ValueError('Cannot apply softmax to a tensor that is 1D')
【问题讨论】:
-
您确定原始模型还没有以 softmax 结尾吗?那些现有的输出已经非常接近于
1的总和(它们加起来是1.00000002685) -
@DennisSoemers 我正在尝试实现一个自定义的 softmax,所以它会与普通的有点不同。
-
可以分享这个定制的softmax的代码吗?只是为了确保它不会发生与原始输出相同的输出?或者,或者,将打印语句粘贴到您的自定义激活函数的代码中。如果您看到这些打印出现,您就知道您的激活函数正在被调用。
-
@DennisSoemers 我已经添加了这个功能。如果您调用
predict方法,我希望它输出zeros。 -
问题是Tensorflow图没有更新,不管keras层更新了。即使使用新模型重新编译,更改也不会生效。我见过的唯一成功的解决方案是github.com/raghakot/keras-vis/blob/master/vis/utils/utils.py
utils.apply_modifications,这有点笨拙。
标签: python tensorflow machine-learning keras