Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inference for classification or segmentation #8

Open
kail85 opened this issue Jan 21, 2024 · 1 comment
Open

Inference for classification or segmentation #8

kail85 opened this issue Jan 21, 2024 · 1 comment

Comments

@kail85
Copy link

kail85 commented Jan 21, 2024

If feasible, could you provide the inference code for classification or segmentation using a trained model, please?

@Zian-Xu
Copy link
Owner

Zian-Xu commented Jan 22, 2024

The method of using the trained Swin MAE model is consistent with the usual use of other pre-trained models. Downstream tasks can be performed directly using the official Swin-Unet code.

Here I show the function that loads the pre-trained model, and you'll see that it's basically the same as what's done in Swin-Unet.

def load_weight(model, device, path):
    if path == '':
        print('No pre-training weights are used.')
        return model
    assert os.path.exists(path)
    full_dict = torch.load(path, map_location=device)['model']
    model_dict = model.state_dict()

    for key in list(full_dict):
        if key.startswith('layers_up'):
            del full_dict[key]

    for key in list(full_dict):
        if key.startswith('layers'):
            current_layer_index = 2 - int(key[7:8])
            if current_layer_index >= 0:
                current_key = "layers_up." + str(current_layer_index) + key[8:]
                full_dict[current_key] = full_dict[key]

    for k in list(full_dict.keys()):
        if k in model_dict:
            if full_dict[k].shape != model_dict[k].shape:
                print(f"Delete: '{k}'; "
                      f"Weight shape: {full_dict[k].shape}; Model shape: {model_dict[k].shape}")
                del full_dict[k]

    result = model.load_state_dict(full_dict, strict=False)
    print(result)
    return model

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants