【问题标题】:Changing activation function of a keras layer w/o replacing whole layer在不替换整个层的情况下更改 keras 层的激活函数
【发布时间】: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.pyutils.apply_modifications,这有点笨拙。

标签: python tensorflow machine-learning keras


【解决方案1】:

在目前的情况下,没有正式的、干净的方法可以做到这一点。正如 cmets 中的@layser 所指出的,Tensorflow 图没有被更新——这导致你的输出没有变化。一种选择是使用keras-vis' utils。我的建议是将其隔离在您自己的 utils.py 中,如下所示:

from vis.utils.utils import apply_modifications

def update_layer_activation(model, activation, index=-1):
    model.layers[index].activation = activation
    return apply_modifications(model)

这会导致类似的用途:

model = update_layer_activation(model, custom_softmax)

如果您点击给定的链接,您会发现他们所做的事情非常简单:他们将 model 保存到临时路径,然后加载并返回,最后删除临时文件。

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    相关资源
    最近更新 更多