在使用Conv2D和其他层之前,我想在第一层中调整图像的形状并调整其大小。输入将是一个展平的数组。这是我的代码:
#Create flat example image:
img_test = np.zeros((120,160))
img_test_flat = img_test.flatten()
reshape_model = Sequential()
reshape_model.add(tf.keras.layers.InputLayer(input_shape=(img_test_flat.shape)))
reshape_model.add(tf.keras.layers.Reshape((120, 160,1)))
reshape_model.add(tf.keras.layers.experimental.preprocessing.Resizing(28, 28, interpolation='nearest'))
result = reshape_model(img_test_flat)
result.shape
不幸的是,这段代码导致我在下面添加的错误。问题是什么?如何正确调整扁平数组的大小和大小?
WARNING:tensorflow:Model was constructed with shape (None, 19200) for input Tensor("input_13:0", shape=(None, 19200), dtype=float32), but it was called on an input with incompatible shape (19200,).
InvalidArgumentError: Input to reshape is a tensor with 19200 values, but the requested shape has 368640000 [Op:Reshape]
编辑: 我尝试过:
reshape_model = Sequential()
reshape_model.add(tf.keras.layers.InputLayer(input_shape=(None, img_test_flat.shape[0])))
reshape_model.add(tf.keras.layers.Reshape((120, 160,1)))
reshape_model.add(tf.keras.layers.experimental.preprocessing.Resizing(28, 28, interpolation='nearest'))
哪位给了我
WARNING:tensorflow:Model was constructed with shape (None, None, 19200) for input Tensor("input_19:0", shape=(None, None, 19200), dtype=float32), but it was called on an input with incompatible shape (19200,).
EDIT2: 我从一维数组中接收C ++中的输入,并将其传递给
// Copy value to input buffer (tensor)
for (size_t i = 0; i < fb->len; i++){
model_input->data.i32[i] = (int32_t) (fb->buf[i]);
所以我传递给模型的是平面数组。
答案 0 :(得分:1)
您对形状的使用在这里根本没有意义。输入的第一维应为样本数。应该是19,200还是1个样本?
input_shape
应该省略样本数,因此,如果要1个样本,输入形状应为19,200。如果您有19,200个样本,则形状应为1。
重塑层也省略了样本数量,因此Keras感到困惑。您到底想做什么?
这似乎是您要实现的目标,但我个人将调整神经网络之外图像的大小:
import numpy as np
import tensorflow as tf
img_test = np.zeros((120,160)).astype(np.float32)
img_test_flat = img_test.reshape(1, -1)
reshape_model = tf.keras.Sequential()
reshape_model.add(tf.keras.layers.InputLayer(input_shape=(img_test_flat.shape[1:])))
reshape_model.add(tf.keras.layers.Reshape((120, 160,1)))
reshape_model.add(tf.keras.layers.Lambda(lambda x: tf.image.resize(x, (28, 28))))
result = reshape_model(img_test_flat)
print(result.shape)
TensorShape([1, 28, 28, 1])
可以随意使用Resizing
层而不是Lambda
层,由于我的Tensorflow版本,我不能使用它。