我输入的是:
[batch_size, number_of_images, img_size_x, img_size_y]
例如[24, 51, 28,28]
现在,我想通过Conv2d-Layer处理该批次项目的每个图像并收集输出。
我想使用一层来改变输入的形状
tf.keras.layer.Reshape(1,28,28)
得到类似[1224, 1, 28, 28]
我可以处理。
这是重现该错误的最小示例
import numpy as np
import tensorflow as tf
tf.enable_eager_execution()
input_data = np.ones((24, 51, 28, 28))
input_label = np.ones((24, 51, 10))
output_data = np.ones((24, 10))
inp_layer = tf.keras.layers.Input(shape=(51, 28, 28))
input_batch_label = tf.keras.layers.Input(shape=(51, 10))
res1 = tf.keras.layers.Reshape((1, 28, 28), name="reshape1")(inp_layer)
perm1 = tf.keras.layers.Permute((2, 3, 1))(res1)
cnn1 = tf.keras.layers.Conv2D(64, 3, padding="same", activation='relu')(perm1)
max1 = tf.keras.layers.MaxPooling2D(16, 16, padding="valid")(cnn1)
res2 = tf.keras.layers.Reshape((51, 64))(max1)
combined_input = tf.keras.layers.concatenate([res2, input_batch_label], axis=-1, )
flat = tf.keras.layers.Flatten()(combined_input)
fc1 = tf.keras.layers.Dense(10)(flat)
model = tf.keras.Model(inputs=[inp_layer, input_batch_label], outputs=fc1)
model.compile(optimizer=tf.train.AdamOptimizer(0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
model.fit([input_data, input_label], output_data, batch_size=24, verbose=1)
我从以下错误中假定,此重塑层以[24, 1, 28, 28]
的形式请求输入,但我需要传递[24, 51, 1, 28, 28]
tensorflow.python.framework.errors_impl.InvalidArgumentError:
Input to reshape is a tensor with 959616 values, but the requested shape has 18816
[[{{node Reshape}}]] [Op:StatefulPartitionedCall]
您有任何建议或发现构建我的模型的另一种可能性吗?
如果我使用tf.reshape可以正常工作,但是使用Keras功能API会遇到麻烦,因为tf.reshape的输出没有适当Layer的输出。
预先感谢
答案 0 :(得分:2)
@Berriel非常感谢您的回答。 如果我将代码更改为以下内容,则一切正常。
def reshape1():
def func(x):
ret = tf.reshape(x, [-1, 1, 28, 28])
return ret
return tf.keras.layers.Lambda(func)
def reshape2():
def func(x):
ret = tf.reshape(x, [-1, 51, 64])
return ret
return tf.keras.layers.Lambda(func)
res1 = reshape1()(inp_layer)
perm1 = tf.keras.layers.Permute((2, 3, 1))(res1)
cnn1 = tf.keras.layers.Conv2D(64, 3, padding="same", activation='relu')(perm1)
max1 = tf.keras.layers.MaxPooling2D(16, 16, padding="valid")(cnn1)
#res2 = tf.keras.layers.Reshape((51, 64))(max1)
res2 = reshape2()(max1)
combined_input = tf.keras.layers.concatenate([res2, input_batch_label], axis=-1, )
flat = tf.keras.layers.Flatten()(combined_input)
fc1 = tf.keras.layers.Dense(10)(flat)