无法使用Keras在CNN中添加SPP层

时间:2018-05-29 05:22:05

标签: python tensorflow keras

我想在CNN中的密集层之前应用空间金字塔池。

我用Keras来实现。

Tensorflow用作后端。

然而,我收到了一个错误。

我的代码出了什么问题?谢谢。

Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> model.add(SpatialPyramidPooling(pooling_regions, input_shape=Input(shape = (None,None,None,3)))) File "C:\Program Files\Python36\lib\site-packages\spp\SpatialPyramidPooling.py", line 33, in __init__ super(SpatialPyramidPooling, self).__init__(**kwargs) File "C:\Program Files\Python36\lib\site-packages\keras\engine\topology.py", line 311, in __init__ batch_input_shape = (batch_size,) + tuple(kwargs['input_shape']) File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 439, in __iter__ "Tensor objects are not iterable when eager execution is not " TypeError: Tensor objects are not iterable when eager execution is not enabled. To iterate over this tensor use tf.map_fn.

以下是代码:

from keras.engine.topology import Layer
from keras.models import Sequential
import keras.backend as K
import numpy as np

model = Sequential()
model.add(SpatialPyramidPooling((1,2,4), Input(shape=(None, None, None, 3))))

class SpatialPyramidPooling(Layer):
    def __init__(self, pool_list, **kwargs):

        self.dim_ordering = K.image_dim_ordering()
        assert self.dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}'

        self.pool_list = pool_list

        self.num_outputs_per_channel = sum([i * i for i in pool_list])

        super(SpatialPyramidPooling, self).__init__(**kwargs)

    def call(self, x, mask=None):

        input_shape = K.shape(x)
        print(input_shape)
        print(K.eval(input_shape))
        outputs = K.variable(value=np.random.random((3,4)))

        return outputs

1 个答案:

答案 0 :(得分:0)

我很确定你应该使用input_shape=(None,None,None,3)代替input_shape=Input(shape = (None,None,None,3))

此外,您不能使用任何要求call方法中存在数据的函数。您正在使用K.shapeK.eval,两者都会在编译时带来错误。

如果您需要有关输入形状的信息,则必须使用def build(self, input_shape):方法执行此操作。