【问题标题】:IndexError when trying to get output of layer in Keras model尝试在 Keras 模型中获取层的输出时出现 IndexError
【发布时间】:2018-05-16 00:43:51
【问题描述】:

我试图查看我的数据在通过 Keras 模型中的卷积层后的样子。我正在使用 Theano 后端。我的代码是从 Keras Github 拼凑而成的:

def get_layer0_outputs(model, test_data):
    output = model.layers[0].output
    inputs = [K.learning_phase()] + model.inputs
    func = K.function(inputs, [output])
    return func([0] + [test_data])

我在这里要做的是为我的网络中的第一层(Conv2D 层)编译一个函数。 test_data 参数是 np.ndarray。我的模型已正确加载,并且我已经对其进行了相当准确的训练。

但是,当我调用这个函数时,我得到一个神秘的堆栈跟踪:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 884, in __call__
    self.fn() if output_subset is None else\
  File "/usr/local/lib/python3.5/dist-packages/theano/gof/op.py", line 872, in rval
    r = p(n, [x[0] for x in i], o)
  File "/usr/local/lib/python3.5/dist-packages/theano/tensor/nnet/abstract_conv.py", line 1626, in perform
    conv_out = self.conv(img, kern, mode="valid", dilation=self.filter_dilation)
  File "/usr/local/lib/python3.5/dist-packages/theano/tensor/nnet/abstract_conv.py", line 1531, in conv
    dilated_kern[n, im0, ...],
IndexError: index 1 is out of bounds for axis 1 with size 1

这是什么意思?我是否错误地调用了我的函数?

【问题讨论】:

    标签: python numpy keras


    【解决方案1】:

    您的功能适用于我使用以下模型:

    a = Input(shape=(224,224,3))
    b = Conv2D(8, 3, strides=(2,2))(a)
    model = Model(inputs=a, outputs=b)
    model.compile(optimizer='sgd', loss='mse')
    
    def get_layer0_outputs(model, test_data):
        output = model.layers[0].output
        inputs = [K.learning_phase()] + model.inputs
        func = K.function(inputs, [output])
        return func([0] + [test_data])
    
    print get_layer0_outputs(model, np.zeros((1, 224, 224, 3)))[0].shape
    

    请注意,第 0 层是输入层而不是 Conv2D,但代码也适用于第 1 层。我使用的是 tensorflow 后端,所以我不知道区别是你的模型还是 theano 后端。

    【讨论】:

    • 有趣。我会尝试使用 tensorflow。
    • 您使用的是什么版本的 Keras 和 TensorFlow?您使用的是 Python 2 还是 3?
    • Keraas 2.0.5、TensorFlow 1.2.1、Python 2
    猜你喜欢
    • 2017-05-25
    • 1970-01-01
    • 2017-11-21
    • 2019-01-27
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-24
    相关资源
    最近更新 更多