keras自定义层K.reshape无法将输入数组从形状(15,4)广播到形状(1,4)

时间:2018-09-21 10:23:11

标签: python-3.x keras

from keras.layers import Input
from keras.models import Model
import keras.engine as KE
import keras.backend as K
import tensorflow as tf
import numpy as np 
inputs = Input(shape = [3,5,4])
class GetBox(KE.Layer):
    def __init__(self, **kwargs):
        super(GetBox, self).__init__(**kwargs)
    def call(self, inputs):
        out_boxes = K.reshape(inputs, [-1, 4])
        return out_boxes
    def compute_output_shape(self, input_shape):
        return (None, 4) 
mmoutputs = GetBox()(inputs)
model = Model(inputs, mmoutputs)
print(model.output)
model.compile(optimizer='rmsprop',loss='categorical_crossentropy',
              metrics=['accuracy'])
a = np.zeros([1,3,5,4])
model.predict(a, batch_size = 1, verbose = 0)

错误

error: ValueError                                Traceback (most
recent call last) <ipython-input-19-6d37dae515cd> in <module>()
     26 a = np.zeros([1,3,5,4])
     27 
---> 28 model.predict(a, batch_size = 1, verbose = 0)

~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in
predict(self, x, batch_size, verbose, steps)    1833         f =
self.predict_function    1834         return self._predict_loop(f,
ins, batch_size=batch_size,
-> 1835                                   verbose=verbose, steps=steps)    1836     1837     def train_on_batch(self, x, y,

~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in
_predict_loop(self, f, ins, batch_size, verbose, steps)    1337                         outs.append(np.zeros(shape, dtype=batch_out.dtype))    1338         
for i, batch_out in enumerate(batch_outs):
-> 1339                     outs[i][batch_start:batch_end] = batch_out    1340                 if verbose == 1:    1341          
progbar.update(batch_end)

ValueError: could not broadcast input array from shape (15,4) into
shape (1,4)

1 个答案:

答案 0 :(得分:0)

据我所知,keras的Model.predict期望输出的形状与输入的一样,为零轴。即您不能使用样本数量= 1的模型输入并将其转换为形状15的预测。

这是model.summary()的输出:

Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 3, 5, 4)           0         
_________________________________________________________________
get_box_1 (GetBox)           (None, 4)                 0         
=================================================================
Total params: 0
Trainable params: 0
Non-trainable params: 0
_________________________________________________________________

Model.predict尝试使输出中的样本数等于1(输入中的样本数),但是获得15个样本并且无法对其进行处理,因此发生以下错误:

ValueError: could not broadcast input array from shape (15,4) into
shape (1,4)

我想,outs [i]的形状等于(1,4),并且您不能更改它,因为它是内部keras代码:

outs[i][batch_start:batch_end] = batch_out    

因此,您应该在将模型的输入传递给model.predict之前重塑模型的输入,或者将该层用作内部层并在模型的输出层之前重塑其输出。例如,用另一层将输出重塑为(1、15、4)。但是解决方案取决于您的代码的目的,现在我还不清楚。您能解释一下您的目标吗?依赖于此,也许您只需要张量流代码即可。