【问题标题】:How to turn entire keras model into theano function如何将整个keras模型变成theano函数
【发布时间】:2016-09-10 08:04:35
【问题描述】:

我想把我的 keras 模型变成一个 theano 函数,这样我就可以计算输入的梯度。我认为这对于可视化网络可能很酷。我想根据神经网络认为的这些梯度来增强原始图像中的特征。我不明白我在下面的代码中做错了什么。

model = Sequential()
model.add(InputLayer((3, H, W)))
model.add(GaussianNoise(0.03))

model.add(Flatten())
model.add(Dense(512, activation = 'relu', name = 'dense'))
model.add(Dropout(0.2))
model.add(Dense(20, activation = 'relu'))
model.add(Dense(C, activation = 'softmax', W_regularizer = l2()))
...
f = theano.function([model.input], model.output)

我得到以下异常。

theano.gof.fg.MissingInputError: A variable that is an input to the graph was neither provided as an input to the function nor given a value. A chain of variables leading from this input to an output is [keras_learning_phase, DimShuffle{x,x}.0, Elemwise{switch,no_inplace}.0, dot.0, Elemwise{add,no_inplace}.0, Elemwise{add,no_inplace}.0, Elemwise{mul,no_inplace}.0, dot.0, Elemwise{add,no_inplace}.0, Softmax.0]. This chain may not be unique
Backtrace when the variable is created:
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/usr/local/lib/python3.5/dist-packages/keras/backend/__init__.py", line 51, in <module>
    from .theano_backend import *
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 662, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/usr/local/lib/python3.5/dist-packages/keras/backend/theano_backend.py", line 13, in <module>
    _LEARNING_PHASE = T.scalar(dtype='uint8', name='keras_learning_phase')  # 0 = test, 1 = train

【问题讨论】:

    标签: python theano keras


    【解决方案1】:

    对于“旧”的 keras(例如 0.3.x):

    我不使用这个版本,但像 this one 这样的例子应该可以工作。

    对于“新”keras(1.0+):

    由于您使用Dropout 层,您需要添加另一个输入K.learning_phase() 并将其值设为 0(0 用于测试,1 用于训练。)

    代码:

    from keras import backend as K
    K.function([model.layers[0].input, K.learning_phase()], [model.layers[-1].output])
    

    参考:keras FAQ

    【讨论】:

      【解决方案2】:

      按照FAQ,试试:

      from keras import backend as K
      get_last_layer_output = K.function([model.layers[0].input],
                                         [model.layers[-1].output])
      

      对于最新版本的 Keras (1.0),请使用

      from keras import backend as K
      get_last_layer_output = K.function([model.layers[0].input],
                                         [model.layers[-1].get_output(train=False)])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-11
        • 1970-01-01
        • 2016-03-11
        • 2015-10-24
        • 1970-01-01
        • 2017-03-16
        • 2017-12-19
        相关资源
        最近更新 更多