inceptionnext icon indicating copy to clipboard operation
inceptionnext copied to clipboard

Why do I report an error parameter mismatch when I predict with saved parameters?And the accuracy of the prediction is very low, is it a problem with the import parameters?

Open kairenchen123 opened this issue 1 year ago • 3 comments

Parameter not found in model: epoch Parameter not found in model: arch Parameter not found in model: state_dict Parameter not found in model: optimizer Parameter not found in model: version Parameter not found in model: args Parameter not found in model: metric

---------------------my code----------------------------- def test(args): model = create_model( args.model, pretrained=args.pretrained, num_classes=args.num_classes, in_chans=3, global_pool=args.gp, scriptable=args.torchscript) # 文件夹路径 folder_path = '../apple/test'

# 加载.pth文件
pretrained_path = './model_best.pth.tar'
pretrained_dict = torch.load(pretrained_path)

# 检查模型参数形状并进行匹配
model_dict = model.state_dict()
for name, param in pretrained_dict.items():
    if name in model_dict:
        if param.shape == model_dict[name].shape:
            model_dict[name] = param
        else:
            print(f'Parameter shape mismatch: {name}')
    else:
        print(f'Parameter not found in model: {name}')
# 创建模型实例并加载权重
device = torch.device('cuda')
model.load_state_dict(model_dict, strict=False)
model.to(device)
model.eval()
transform = transforms.Compose([transforms.ToTensor(), transforms.Resize((224, 224))])
vector = []
out = []
for i in range(9):
    vector.append(torch.full((1,), i, dtype=torch.int))
# 进行预测
# 遍历文件夹中的文件
for file_name in os.listdir(folder_path):
    file_path = os.path.join(folder_path, file_name)
    # 确保是图片文件
    if file_path.endswith('.jpg') or file_path.endswith('.png'):
        # 使用PIL库读取图片
        image = Image.open(file_path)
        image = transform(image)
        image = image.to(device)
        image = image.unsqueeze(0)
        output = model(image)
        # 将预测值保存为.csv文件
        for i in range(9):
            output_argmax = output.argmax(1)
            vector_i = vector[i].to(output_argmax.device)
            if output_argmax == vector_i:
                out.append('d{}'.format(i + 1))

df = pd.DataFrame()
df['uuid'] = [file_name for file_name in os.listdir(folder_path) if file_name.endswith('.jpg') or file_name.endswith('.png')]
df['label'] = [i for i in out]
df.to_csv('predictions.csv', index=False)

kairenchen123 avatar Jun 03 '23 08:06 kairenchen123