AttributeError: 'dict' object has no attribute 'n_channels'

I am getting this error after loading the model and when the model is called. Below is my code:

def main(hparams):
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    net = Unet.load_from_checkpoint(hparams.checkpoint)

    for fn in tqdm(os.listdir(hparams.img_dir)):
        fp = os.path.join(hparams.img_dir, fn)

        img =
        mask = predict(net, img, device=device)

        mask_img = mask_to_image(mask), fn))

if __name__ == '__main__':
    parent_parser = ArgumentParser(add_help=False)
    parent_parser.add_argument('--checkpoint', required=True)
    parent_parser.add_argument('--img_dir', required=True)
    parent_parser.add_argument('--out_dir', required=True)

    parser = Unet.add_model_specific_args(parent_parser)
    hparams = parser.parse_args()


getting the error at the last line “main(hparams)”. Can someone help me with this, please

Could you post a minimal, executable code snippet so that we could have a look, please? :slight_smile:

Hello @Varun_Tirupathi did you solve the problem? I am also getting the same problem!

hi, @akib62 I got this error when I am testing the model from a separate file called As I didn’t find a solution I have changed the methodology to do the testing. I don’t have a solution to this I’m sorry :frowning:

Hi, @ptrblck I am writing the UNet code using PyTorch Lightning.

I am taking help from a repo

The unet and is working fine. But at the time of, it is showing the error (question title and description) is the same for me.

In my understanding, when, we are running here and any images going through the pre-trained unet model here which requires n_channels!

But from the we are not passing any arguments like n_channels because it is already defined! Most probably for that reason, the error is showing.

Any idea to solve the issue?

Problem solved

Hi @akib62 please post the code snippet also for better understanding of the issue i mean where the problem is arising

@Varun_Tirupathi same as your!

You already gave the code snippet and already described the problem

Hi @Varun_Tirupathi I solved the problem.

You have to use self.save_hyperparameters() in your Unet model to store the hyperparameters

I found the solution in this post here

Hi, @akib62 Thanks a lot for the solution. I will implement it.

Hi @akib62 How you are running the what arguments you are passing is the same one im getting init() missing 1 required positional argument: ‘hparams’ this error now

python --checkpoint lightning_logs/version_0/checkpoints/_ckpt_epoch_1.ckpt --img_dir dataset/carvana/test --out_dir result/carvana

After changing the code for saving parameters you have to train the model.
Yes, I used the same command