gpt4 book ai didi

python - 尽管我提供的形状看起来正确,但尝试进行预测时,TensorFlow/Keras模型错误,原因是形状不匹配

转载 作者:行者123 更新时间:2023-12-02 17:26:42 24 4
gpt4 key购买 nike

我不确定我是否对输入张量概念不太了解,或者我是否使用错误的输入形状训练了模型,或者是否需要以某种方式指定图像。

该模型的构建如下:

... import all the usual libraries - TF, Keras, Numpy, OpenCV etc. ...
_MODEL_DIMENSION = 128

def create_model_for_dimension(dimension):
model = Sequential()
if dimension >= 256:
model.add(Conv2D(256, kernel_size=(5, 5), input_shape=(dimension, dimension, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
if dimension >= 128:
model.add(Conv2D(128, kernel_size=(3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
…… more convolution layers ……..
…………………………………………..
……………………………………………..
model.add(Flatten())
……… More layers …………………
……………………………………………..
……………………………………………..

model.add(Dense(2))
model.add(Activation('sigmoid'))

model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
return model

train_datagen = ImageDataGenerator(
rotation_range=10,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
zoom_range=1.2,
horizontal_flip=True,
vertical_flip=True,
fill_mode='nearest')

train_generator = train_datagen.flow_from_directory(
train_data_directory,
target_size=(_MODEL_DIMENSION, _MODEL_DIMENSION),
batch_size=_BATCH_SIZE,
class_mode='categorical')

……… validate_generator …………………
……………………………………………………
………………………………………………………
……… test_generator ………………………
………………………………………………………
………………………………………………………

……… train and save the model ……

当我训练并使用它来预测目录中的图像时,一切正常(至少看起来如此)。但是,然后我尝试通过以下方式不使用ImageDataGenerator来提供图像:

首先,我使用OpenCV读取图像(我希望使用OpenCV进行其他处理,因此不使用PIL)
ml_model = … read the model back from the saved model ……
snapshot = cv.imread(file_name)
snapshot = cv.cvtColor(snapshot, cv.COLOR_BGR2RGB)

然后我使用范围裁剪图像
cropped_area = snapshot[y[0]:y[1], x[0]:x[1]]

然后,我使用模型评分如下。除np.array转换外,我还尝试了其他变体。
score_val = model.predict(np.array(cropped_area/255.0))

这是当它出现以下错误时:
ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [32, 128, 3]

我的图像形状为(128、128、3),我所做的所有检查似乎都确认那就是我一直在喂食的图像。

任何指针将不胜感激,因为我花了大部分时间尝试解决此问题!谢谢!

最佳答案

您设置_MODEL_DIMENSION = 128这导致

if dimension >= 128:
model.add(Conv2D(128, kernel_size=(3, 3)))
您没有设置输入形状,因此根据 documentation,预期的输入将是:

Input shape

4D tensor with shape: (batch, channels, rows, cols) if data_format is "channels_first" or 4D tensor with shape: (batch, rows, cols, channels) if data_format is "channels_last".


您的输入不正确,因此出现错误

expected ndim=4, found ndim=3


解决方案是定义代码中已经存在的输入形状:
if dimension >= 256:
model.add(Conv2D(256, kernel_size=(5, 5), input_shape=(dimension, dimension, 3)))

关于python - 尽管我提供的形状看起来正确,但尝试进行预测时,TensorFlow/Keras模型错误,原因是形状不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com