我只是想添加一些不適合評論的內容。看來,predict
檢查仔細輸出形狀:
class ExtractShape(keras.engine.topology.Layer):
def call(self, x):
return keras.backend.sum(x, axis=0)
def compute_output_shape(self, input_shape):
return input_shape
a = keras.layers.Input((None, None))
b = ExtractShape()(a)
m = keras.Model(a, b)
m.compile(optimizer=keras.optimizers.Adam(), loss='binary_crossentropy')
A = np.ones((5,4,3))
然後:
In [163]: m.predict_on_batch(A)
Out[163]:
array([[5., 5., 5.],
[5., 5., 5.],
[5., 5., 5.],
[5., 5., 5.]], dtype=float32)
In [164]: m.predict_on_batch(A).shape
Out[164]: (4, 3)
但是:
In [165]: m.predict(A)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-165-c5ba5fc88b6e> in <module>()
----> 1 m.predict(A)
~/miniconda3/envs/ccia/lib/python3.6/site-packages/keras/engine/training.py in predict(self, x, batch_size, verbose, steps)
1746 f = self.predict_function
1747 return self._predict_loop(f, ins, batch_size=batch_size,
-> 1748 verbose=verbose, steps=steps)
1749
1750 def train_on_batch(self, x, y,
~/miniconda3/envs/ccia/lib/python3.6/site-packages/keras/engine/training.py in _predict_loop(self, f, ins, batch_size, verbose, steps)
1306 outs.append(np.zeros(shape, dtype=batch_out.dtype))
1307 for i, batch_out in enumerate(batch_outs):
-> 1308 outs[i][batch_start:batch_end] = batch_out
1309 if verbose == 1:
1310 progbar.update(batch_end)
ValueError: could not broadcast input array from shape (4,3) into shape (5,3)
我不知道這是否是一個bug真的。
數組的大小是多少? 'predict'採用'batch_size'參數,如果未設置,則默認爲32。如果n <= 32,那麼這兩個函數調用應該是相同的。 – Toterich