ValueError:尺寸必须相等,但对于 '{{node mean_squared_error/SquaredDifference}} = SquaredDifference[T=DT_FLOAT] 的尺寸为 428 和 3401

问题描述

我正在尝试使用 resnet50 端到端地映射图像。我没有要分类的课程。我只是在测试代码,这就是为什么我只使用 1 张图像进行测试。我放了 batch=1epochs=1
是这个原因吗?

我找不到错误发生的原因。

图像的形状为 (3401,3402,3)

import os
import numpy as np 
import matplotlib.pyplot as plt
import glob
import cv2
from keras.layers import Conv2D,MaxPooling2D
from keras.layers import Convolution2D
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import UpSampling2D
import tensorflow as tf
from keras.models import Sequential
from keras.models import Model
from tensorflow.keras.preprocessing import image_dataset_from_directory
from tensorflow.keras.layers import Batchnormalization,Flatten,Input
xtrain_images = []
for directory_path in glob.glob("Train\\in"):
    for img_path in glob.glob(os.path.join(directory_path,"*.tif")):
        img = cv2.imread(img_path)       
        xtrain_images.append(img)
        
xtrain_images = np.array(xtrain_images)
x_train= xtrain_images / 255.0
print(x_train.shape)
ytrain_images = []
for directory_path in glob.glob("Train\\out"):
    for img_path in glob.glob(os.path.join(directory_path,"*.tif")):
        img = cv2.imread(img_path)
        
        ytrain_images.append(img)
        
ytrain_images = np.array(ytrain_images)
y_train= ytrain_images / 255.0
print(y_train.shape)
train_images = []
for directory_path in glob.glob("D:Train\\Validation\\valid_in"):
    for img_path in glob.glob(os.path.join(directory_path,"*.tif")):
        img = cv2.imread(img_path)   
        img = cv2.resize(img,(3402,3401))
        train_images.append(img)
        
train_images = np.array(train_images)
x_val= train_images / 255.0
print(x_val.shape)

vtrain_images = []
for directory_path in glob.glob("D:Train\\Validation\\valid_out"):
    for img_path in glob.glob(os.path.join(directory_path,"*.tif")):
        img = cv2.imread(img_path)       
        vtrain_images.append(img)
        
vtrain_images = np.array(vtrain_images)
y_val= vtrain_images / 255.0
print(y_val.shape)

pixel_rows = 3402
pixel_cols = 3401

image_size = (pixel_cols,pixel_rows)
batch_size = 32

input_shape = x_train.shape
base_model = tf.keras.applications.resnet50(
    include_top=False,weights="imagenet",input_shape=(3401,3),pooling=None,)
for layer in base_model.layers[:]:
    layer.trainable = False
model = Sequential()
model.add(base_model)
model.add(Convolution2D(3,9,activation='relu',padding='same',input_shape = (pixel_cols,pixel_rows,3)))
model.add(UpSampling2D())
model.add(UpSampling2D())
model.add(Batchnormalization())
model.add(Convolution2D(3,padding='same'))
model.build(input_shape)
model.summary()
model.compile(optimizer="adam",loss='mean_squared_error',metrics=['mean_squared_error'])

model.fit(x_train,y_train,validation_data = (x_val,y_val),batch_size= 1,epochs = 1)

model.summary()

Model: "sequential_5"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
module_wrapper_10 (ModuleWra (1,107,2048)       23587712  
_________________________________________________________________
conv2d_10 (Conv2D)           (1,3)          497667    
_________________________________________________________________
up_sampling2d_10 (UpSampling (1,214,3)          0         
_________________________________________________________________
up_sampling2d_11 (UpSampling (1,428,3)          0         
_________________________________________________________________
module_wrapper_11 (ModuleWra (1,3)          12        
_________________________________________________________________
conv2d_11 (Conv2D)           (1,3)          732       
=================================================================
Total params: 24,086,123
Trainable params: 498,405
Non-trainable params: 23,587,718

错误

C:\Users\anaconda3\lib\site-packages\keras\engine\training.py:830 train_function  *
        return step_function(self,iterator)
    C:\Users\anaconda3\lib\site-packages\keras\engine\training.py:813 run_step  *
        outputs = model.train_step(data)
    C:\Users\anaconda3\lib\site-packages\keras\engine\training.py:771 train_step  *
        loss = self.compiled_loss(
    C:\Users\anaconda3\lib\site-packages\keras\engine\compile_utils.py:201 __call__  *
        loss_value = loss_obj(y_t,y_p,sample_weight=sw)
    C:\Users\anaconda3\lib\site-packages\keras\losses.py:142 __call__  *
        losses = call_fn(y_true,y_pred)
    C:\Users\anaconda3\lib\site-packages\keras\losses.py:246 call  *
        return ag_fn(y_true,y_pred,**self._fn_kwargs)
    C:\Users\AppData\Roaming\Python\python38\site-packages\tensorflow\python\util\dispatch.py:206 wrapper  **
        return target(*args,**kwargs)
    C:\Users\anaconda3\lib\site-packages\keras\losses.py:1202 mean_squared_error
        return backend.mean(tf.math.squared_difference(y_pred,y_true),axis=-1)
    C:\Users\AppData\Roaming\Python\python38\site-packages\tensorflow\python\ops\gen_math_ops.py:10421 squared_difference
        _,_,_op,_outputs = _op_def_library._apply_op_helper(
    C:\Users\AppData\Roaming\Python\python38\site-packages\tensorflow\python\framework\op_def_library.py:748 _apply_op_helper
        op = g._create_op_internal(op_type_name,inputs,dtypes=None,C:\Users\AppData\Roaming\Python\python38\site-packages\tensorflow\python\framework\func_graph.py:599 _create_op_internal
        return super(FuncGraph,self)._create_op_internal(  # pylint: disable=protected-access
    C:\Users\AppData\Roaming\Python\python38\site-packages\tensorflow\python\framework\ops.py:3557 _create_op_internal
        ret = Operation(
    C:\Users\AppData\Roaming\Python\python38\site-packages\tensorflow\python\framework\ops.py:2041 __init__
        self._c_op = _create_c_op(self._graph,node_def,C:\Users\AppData\Roaming\Python\python38\site-packages\tensorflow\python\framework\ops.py:1883 _create_c_op
        raise ValueError(str(e))

    ValueError: Dimensions must be equal,but are 428 and 3401 for '{{node mean_squared_error/SquaredDifference}} = SquaredDifference[T=DT_FLOAT](sequential/conv2d_1/Relu,IteratorGetNext:1)' with input shapes: [1,3],[1,3401,3].

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)