ValueError:“顺序”的输入0;与该层不兼容:预期形状=(无,160、160、3),发现形状=(160、160、3)

发布于 2025-01-24 10:22:48 字数 2891 浏览 0 评论 0原文

我需要一些我的机器学习代码的帮助。 我正在使用Google验证的模型的基础,并添加了自己的最后一个扁平和输出层。

训练模型并保存模型后,我评论了代码的培训部分,并加载并使用了保存的模型。

我的代码:

import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

import tensorflow_datasets as tfds
tfds.disable_progress_bar()

class_names = ['cat','dog']

#load the images
(raw_train, raw_validation, raw_test), metadata = tfds.load(
    'cats_vs_dogs',
    split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],
    with_info=True,
    as_supervised=True,
)

get_label_name = metadata.features['label'].int2str

#function to resize image
IMG_SIZE=160
def format_example(image, label):
    image = tf.cast(image, tf.float32) #cast to convert integer values in pixels to float32
    image = (image/127.5) - 1
    image = tf.image.resize(image,  (IMG_SIZE, IMG_SIZE))
    return image,label

#.map is to apply a function to all raw images
train = raw_train.map(format_example)
validation = raw_validation.map(format_example)
test = raw_test.map(format_example)

BATCH_SIZE = 32
SHUFFLE_BUFFER_SIZE = 1000

train_batches = train.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)
validation_batches = validation.batch(BATCH_SIZE)
test_batches = test.batch(BATCH_SIZE)

IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)
#Create base model from pretrained model MobileNetV2
base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
                                                include_top=False,
                                                weights='imagenet')

#freezing the base (preventing any more training)
base_model.trainable = False

#Flattening it down
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
#Adding dense layer of only 1 neuron as only 2 possibilities(cat/dog)
prediction_layer = keras.layers.Dense(1)

model = tf.keras.Sequential([
    base_model,
    global_average_layer,
    prediction_layer
])

#slow learning rate since it is a pretrained model
base_learning_rate = 0.0001
#Compiling the model
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),
              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              metrics=['accuracy'])

initial_epochs = 3
validation_steps=20

loss0,accuracy0 = model.evaluate(validation_batches, steps = validation_steps)

print('training...')
history = model.fit(train_batches,
                    epochs=initial_epochs,
                    validation_data = validation_batches)

acc = history.history['accuracy']
print(acc)

model.save("dogs_vs_cats.h5")

model = tf.keras.models.load_model('dogs_vs_cats.h5', compile=True)
print('predicting... ')
prediction = model.predict(test, verbose=1)
print(prediction)

我收到以下错误:

ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 160, 160, 3), found shape=(160, 160, 3)

I need help with some Machine Learning code of mine.
I am using the base of a pretrained model by google and adding the last flattening and output layers of my own.

After training the model and saving it, I commented out the training part of the code and loaded and used the saved model.

my code:

import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

import tensorflow_datasets as tfds
tfds.disable_progress_bar()

class_names = ['cat','dog']

#load the images
(raw_train, raw_validation, raw_test), metadata = tfds.load(
    'cats_vs_dogs',
    split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],
    with_info=True,
    as_supervised=True,
)

get_label_name = metadata.features['label'].int2str

#function to resize image
IMG_SIZE=160
def format_example(image, label):
    image = tf.cast(image, tf.float32) #cast to convert integer values in pixels to float32
    image = (image/127.5) - 1
    image = tf.image.resize(image,  (IMG_SIZE, IMG_SIZE))
    return image,label

#.map is to apply a function to all raw images
train = raw_train.map(format_example)
validation = raw_validation.map(format_example)
test = raw_test.map(format_example)

BATCH_SIZE = 32
SHUFFLE_BUFFER_SIZE = 1000

train_batches = train.shuffle(SHUFFLE_BUFFER_SIZE).batch(BATCH_SIZE)
validation_batches = validation.batch(BATCH_SIZE)
test_batches = test.batch(BATCH_SIZE)

IMG_SHAPE = (IMG_SIZE, IMG_SIZE, 3)
#Create base model from pretrained model MobileNetV2
base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
                                                include_top=False,
                                                weights='imagenet')

#freezing the base (preventing any more training)
base_model.trainable = False

#Flattening it down
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
#Adding dense layer of only 1 neuron as only 2 possibilities(cat/dog)
prediction_layer = keras.layers.Dense(1)

model = tf.keras.Sequential([
    base_model,
    global_average_layer,
    prediction_layer
])

#slow learning rate since it is a pretrained model
base_learning_rate = 0.0001
#Compiling the model
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),
              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              metrics=['accuracy'])

initial_epochs = 3
validation_steps=20

loss0,accuracy0 = model.evaluate(validation_batches, steps = validation_steps)

print('training...')
history = model.fit(train_batches,
                    epochs=initial_epochs,
                    validation_data = validation_batches)

acc = history.history['accuracy']
print(acc)

model.save("dogs_vs_cats.h5")

model = tf.keras.models.load_model('dogs_vs_cats.h5', compile=True)
print('predicting... ')
prediction = model.predict(test, verbose=1)
print(prediction)

I am getting the following error:

ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 160, 160, 3), found shape=(160, 160, 3)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野の 2025-01-31 10:22:48

我是否正确理解您只有在您评论训练代码并从模型开始运行行之后才能获得此错误,从= tf.keras.models.load_model('dogd_vs_cats.h5',compile = true)?如果是的,我认为您在这一行中有一个错误:

prediction = model.predict(test, verbose=1)

您使用测试带有3D图像,但不使用4D图像批次test_batches,这就是为什么您获得的原因3D/4D形状的错误。

Do I understand correctly that you get this error only after you comment training code and run lines starting from model = tf.keras.models.load_model('dogs_vs_cats.h5', compile=True)? If yes, I think that you have a mistake in this line:

prediction = model.predict(test, verbose=1)

You use test with 3D-images, but not batched test_batches with 4D-images, this is why you obtain an error with 3D/4D shapes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文