简体   繁体   English

“sequential_1 层的输入 0 与层不兼容”与 tf.data.Dataset

[英]"Input 0 of layer sequential_1 is incompatible with the layer" with tf.data.Dataset

I am getting我正进入(状态

ValueError: Input 0 of layer sequential_1 is incompatible with the layer: : expected min_ndim=4, found ndim=3. ValueError:层 sequential_1 的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。 Full shape received: [300, 300, 3].收到完整形状:[300, 300, 3]。 Model Summary shows 4 inputs but it says 3. Model 摘要显示 4 个输入,但它说的是 3 个。

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import tensorflow_datasets as tfds
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
from tensorflow.keras.preprocessing.image import ImageDataGenerator

(train_dataset, test_dataset), metadata = tfds.load('rock_paper_scissors',split=['train', 'test'], as_supervised=True, with_info=True)

class_names = ['rock','paper','scissors']

num_train_examples = metadata.splits['train'].num_examples
num_test_examples = metadata.splits['test'].num_examples
print("Number of training examples: {}".format(num_train_examples))
print("Number of test examples:     {}".format(num_test_examples))

get_label_name = metadata.features['label'].int2str
print(get_label_name(0))
print(get_label_name(1))
print(get_label_name(2))

def format_example(image, label):
    # Make image color values to be float.
    image = tf.cast(image, tf.float32)
    # Make image color values to be in [0..1] range.
    image = image / 255.
    return image, label

dataset_train = train_dataset.map(format_example)
dataset_test =test_dataset.map(format_example)

l1 = tf.keras.layers.Conv2D(32, (3,3), activation = 'relu', input_shape=(300,300,3))
l2 = tf.keras.layers.MaxPooling2D(2,2)

l3 = tf.keras.layers.Conv2D(64, (3,3), activation='relu')
l4 = tf.keras.layers.MaxPooling2D(2,2)

l5 = tf.keras.layers.Conv2D(128, (3,3), activation='relu')
l6 = tf.keras.layers.MaxPooling2D(2,2)

l7 = tf.keras.layers.Flatten()
l8 = tf.keras.layers.Dense(512, activation='relu')
l9 = tf.keras.layers.Dense(3, activation='softmax')

model = tf.keras.Sequential([l1,l2,l3,l4,l5,l6,l7,l8,l9])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy,
              metrics=['accuracy'])

model.summary()

epochs = 10
batch_size = 32

history = model.fit(
    dataset_train,
    validation_data = dataset_test,
    steps_per_epoch = int(np.ceil(num_train_examples/float(batch_size))),
    validation_steps = int(np.ceil(num_test_examples/float(batch_size))),
    epochs = epochs
)

Where am I going wrong?我哪里错了? I have not encountered this error with cats and dogs dataset.我没有遇到猫狗数据集的这个错误。

You need to batch your dataset in order to get the right shape:您需要对数据集进行批处理以获得正确的形状:

dataset_train = train_dataset.map(format_example).batch(1)
dataset_test =test_dataset.map(format_example).batch(1)

When you don't batch,a picture with shape (h, w, c) will be returned.不批处理时返回一张shape为(h, w, c)的图片。 If you batch, you will get (n, h, w, c) , which is what Keras expects.如果你批处理,你会得到(n, h, w, c) ,这是 Keras 所期望的。 Do the test yourself:自己做测试:

import tensorflow as tf

images = tf.random.uniform(shape=(10, 224, 224, 3), maxval=256, dtype=tf.int32)

ds = tf.data.Dataset.from_tensor_slices(images)

for pic in ds:
    print(pic.shape)
    break
(224, 224, 3)

With batching:使用批处理:

for pic in ds.batch(4):
    print(pic.shape)
    break
(4, 224, 224, 3)

暂无
暂无

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

相关问题 ValueError: 层序列 1 的输入 0 与层不兼容 - ValueError: Input 0 of layer sequential_1 is incompatible with the layer 无法解决 ValueError: 层序贯_1 的输入 0 与层不兼容 - Cannot solve ValueError: Input 0 of layer sequential_1 is incompatible with the layer 在Tensorflow 2.0上将tf.data.Dataset与Keras输入层一起使用 - Use of tf.data.Dataset with Keras input layer on Tensorflow 2.0 tf.data.Dataset 的规范化层 - Normalisation layer for tf.data.Dataset Keras:ValueError:输入 0 层序列_1 与层不兼容:预期 ndim=3,发现 ndim=2 - Keras: ValueError: Input 0 of layer sequential_1 is incompatible with the layer: expected ndim=3, found ndim=2 ValueError: 层“sequential_1”的输入 0 与层不兼容:预期形状=(None, 60, 1),发现形状=(None, 59, 1) - ValueError: Input 0 of layer "sequential_1" is incompatible with the layer: expected shape=(None, 60, 1), found shape=(None, 59, 1) 层序的输入0与层不兼容 - Input 0 of layer sequential is incompatible with the layer 层顺序的输入 0 与层不兼容: - Input 0 of layer sequential is incompatible with the layer: ValueError:layersequential_1 的输入 0 与 layer 不兼容::预期 min_ndim=4,发现 ndim=3。 收到的完整形状:[无、256、256] - ValueError: Input 0 of layer sequential_1 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [None, 256, 256] ValueError: 层序贯_1 的输入 0 与层不兼容: : 预期 min_ndim=4,发现 ndim=2。 收到的完整形状:(32768, 1) - ValueError: Input 0 of layer sequential_1 is incompatible with the layer: : expected min_ndim=4, found ndim=2. Full shape received: (32768, 1)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM