不能给变量赋值:形状不匹配。变量形状 (1, 1, 256, 512) 和赋值形状 (512, 128, 1, 1) 不兼容

问题描述 投票:0回答:0

我的 resnet 模型有问题,我尝试使用它来创建和训练自定义人脸识别模型,如下所示,但我收到错误,我可以在其中获得帮助吗?我将同时输入代码和错误

def resnet50tl(input_shape, outclass, sigma='sigmoid'):
    
    base_model = None
    base_model = keras.applications.resnet50.ResNet50(weights='imagenet', include_top=False, input_shape=input_shape)
    base_model.load_weights(resnet50weight)
    
    for layer in base_model.layers:
        layer.trainable = False
    
    top_model = Sequential()
    top_model.add(Flatten(input_shape=base_model.output_shape[1:]))
    for i in range(2):
        top_model.add(Dense(4096, activation='relu'))
        top_model.add(Dropout(0.5))
    top_model.add(Dense(outclass, activation=sigma))

   
    model = Model(inputs=base_model.input, outputs=top_model(base_model.output))
    if resnet50weight is not None:
        # Load the weights with by_name=True, and using specific weight names
        model.load_weights(resnet50weight, by_name=True,
                           skip_mismatch=True, reshape=True)

    return model
input_shape = (224, 224, 3)  # Change this to your input image shape
numclasses = 6 
model = resnet50tl(input_shape, numclasses, 'softmax')
lr = 1e-5
decay = 1e-7 #0.0
optimizer = RMSprop(lr=lr, decay=decay)
model.compile(loss='categorical_crossentropy',
              optimizer=optimizer,
              metrics=['accuracy'])

错误如下:

File "c:\Users\mahmo\Downloads\test\VGG model.py", line 109, in <module>
        model = resnet50tl(input_shape, numclasses, 'softmax')
      File "c:\Users\mahmo\Downloads\test\VGG model.py", line 87, in resnet50tl
        base_model.load_weights(resnet50weight)
      File "C:\Users\mahmo\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\utils\traceback_utils.py", line 70, in error_handler
        raise e.with_traceback(filtered_tb) from None
      File "C:\Users\mahmo\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\backend.py", line 4361, in _assign_value_to_variable
        variable.assign(value)
    ValueError: Cannot assign value to variable ' conv3_block1_0_conv/kernel:0': Shape mismatch.The variable shape (1, 1, 256, 512), and the assigned value shape (512, 128, 1, 1) are incompatible
python keras deep-learning resnet
© www.soinside.com 2019 - 2024. All rights reserved.