繁体   English   中英

ValueError: 层序号_9 的输入 0 与层不兼容:预期 ndim=4,发现 ndim=0。 收到的完整形状:[]

[英]ValueError: Input 0 of layer sequential_9 is incompatible with the layer: expected ndim=4, found ndim=0. Full shape received: []

这是输入管道的代码。 它将图像大小调整为 (224,224,3) 作为输入,将 (224,224,2) 作为 output。

image_path_list = glob.glob('/content/drive/My Drive/datasets/imagenette/*')
data = tf.data.Dataset.list_files(image_path_list)

def tf_rgb2lab(image):
  im_shape = image.shape
  [image,] = tf.py_function(color.rgb2lab, [image], [tf.float32])
  image.set_shape(im_shape)
  return image

def preprocess(path):
  image = tf.io.read_file(path)
  image = tf.image.decode_jpeg(image, channels=3)
  image = tf.image.convert_image_dtype(image, tf.float32)
  image = tf.image.resize(image, [224, 224])
  image = tf_rgb2lab(image)
  L = image[:,:,0]/100.
  ab = image[:,:,1:]/128.
  input = tf.stack([L,L,L], axis=2)
  return input, ab

train_ds = data.map(preprocess, tf.data.experimental.AUTOTUNE).batch(64).repeat()
train_ds = data.prefetch(tf.data.experimental.AUTOTUNE)

以下是 model 的代码。 我认为 model 没有任何问题,因为当我在图像上调用 model.predict() 时它可以工作。 所以我假设输入管道有问题,但自从我第一次使用 tf.data 以来,我无法弄清楚是什么。

vggmodel = tf.keras.applications.VGG16(include_top=False, weights='imagenet')
model = tf.keras.Sequential()
for i,layer in enumerate(vggmodel.layers):
  model.add(layer)
for layer in model.layers:
  layer.trainable=False

model.add(tf.keras.layers.Conv2D(256, (3,3), padding='same', activation='relu'))
model.add(tf.keras.layers.UpSampling2D((2,2)))
model.add(tf.keras.layers.Conv2D(128, (3,3), padding='same', activation='relu'))
model.add(tf.keras.layers.UpSampling2D((2,2)))
model.add(tf.keras.layers.Conv2D(64, (3,3), padding='same', activation='relu'))
model.add(tf.keras.layers.UpSampling2D((2,2)))
model.add(tf.keras.layers.Conv2D(16, (3,3), padding='same', activation='relu'))
model.add(tf.keras.layers.UpSampling2D((2,2)))
model.add(tf.keras.layers.Conv2D(8, (3,3), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(2, (3,3), padding='same', activation='tanh'))
model.add(tf.keras.layers.UpSampling2D((2,2)))

无论如何,当我 print(train_ds) 我得到:

<PrefetchDataset shapes: (), types: tf.string>

我尝试了以下代码:

path = next(iter(train_ds))
L,ab = preprocess(path)
L.shape

我得到了

TensorShape([224, 224, 3])

这意味着它正在返回一个 3 维张量。 那为什么我打电话时会收到错误消息:

model.fit(train_ds, epochs=1, steps_per_epoch=steps, callbacks=[model_checkpoint_callback, early_stopping_callback])

layer.trainable=False & model.fit 是相反的。 虽然前者说设置 model 仅用于推理并关闭反向传播,但 model.fit 用于训练。 可能您正在寻找 model.predict?

所以,是的,这花了一些时间,但我想通了。 这是一个非常愚蠢的错误。

train_ds = data.map(preprocess, tf.data.experimental.AUTOTUNE).batch(64).repeat()
train_ds = data.prefetch(tf.data.experimental.AUTOTUNE)

它实际上应该是:

train_ds = data.map(preprocess, tf.data.experimental.AUTOTUNE).batch(64).repeat().prefetch(tf.data.experimental.AUTOTUNE)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM