具有不同形状的张量流批处理张量



我正在研究神经网络,我遇到了一个我无法弄清楚的愚蠢问题。对于我的第一个网络,我必须使用TensorFlow Hub的oxford_flowers102和MobileNet预训练模型在Keras和TensorFlow中创建花朵图像分类器。

问题似乎是图像没有重新调整为(224,224,3(,但它们保留了彼此不同的原始形状。但是,根据我的课程材料,我的重新调整大小代码是正确的,所以我不明白发生了什么以及我做错了什么。

非常感谢您的帮助。

# LOADING 
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)
training_set, testing_set, validation_set = dataset['train'], dataset['test'],dataset['validation']
# PROCESSING AND BATCHES 
def normalize(img, lbl):
img = tf.cast(img, tf.float32)
img = tf.image.resize(img, size=(224,224))
img /= 255
return img, lbl

batch_size = 64

training_batches = training_set.cache().shuffle(train_examples//4).batch(batch_size).map(normalize).prefetch(1)
validation_batches = validation_set.cache().batch(batch_size).map(normalize).prefetch(1)
testing_batches = testing_set.cache().batch(batch_size).map(normalize).prefetch(1)
# BUILDING THE NETWORK
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
mobile_net = hub.KerasLayer(URL, input_shape=(224, 224,3))
mobile_net.trainable = False
skynet = tf.keras.Sequential([
mobile_net,
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_classes, activation= 'softmax')
])
# TRAINING THE NETWORK
skynet.compile(optimizer='adam', loss= 'sparse_categorical_crossentropy', metrics=['accuracy'])
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
Epochss = 25
history = skynet.fit(training_batches,
epochs= Epochss,
validation_data=validation_set,
callbacks=[early_stopping])

ERROR:
InvalidArgumentError:  Cannot batch tensors with different shapes in component 0. First element had shape [590,501,3] and element 1 had shape [500,752,3].
[[node IteratorGetNext (defined at /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:1751) ]] [Op:__inference_distributed_function_18246]
Function call stack:
distributed_function

问题在于,在输入管道中,在使图像大小相等之前,您正在对数据集进行批处理。您def normalize(img, lbl)只能处理单个图像,而不是完整的批处理。

因此,为了使代码运行,您必须进行以下更改,您必须在batchAPI 之前调用mapAPI,如下所示。

batch_size = 64
training_batches = training_set.cache().map(normalize).batch(batch_size).prefetch(1)
validation_batches = validation_set.cache().map(normalize).batch(batch_size).prefetch(1)
testing_batches = testing_set.cache().map(normalize).batch(batch_size).prefetch(1)

最新更新