[RuntimeError: File ./LEVIR_CD_best_f1score_model/best_f1score_epoch1_Sat Jun 22 13:20:09 2024.pth ]

完整报错:

RuntimeError: File ./LEVIR_CD_best_f1score_model/best_f1score_epoch1_Sat Jun 22 13:20:09 2024.pth cannot be opened.

在跑深度学习验证的时候,保存模型时遇到了问题。

注意:该报错位于windows11系统环境中

尝试了两种思路解决:

原因1:代码文件夹的权限不够,不能够对文件进行读写
解决方法1:

按 Win + R,输入 cmd,然后按 Enter,打开命令提示符。
执行 icacls 命令: 在命令提示符中输入以下命令,然后按 Enter:

icacls "yourpath" /grant Everyone:(OI)(CI)F /T

发现问题仍然没有解决。继续查找原因:

    # ipdb.set_trace()
    localtime = time.asctime(time.localtime(time.time()))
    if mode == 'checkpoint':
        state_dict = {'net': model.state_dict(), 'optimizer': optimizer.state_dict()}
        torch.save(state_dict,
                   str(path + f'checkpoint_epoch{epoch}_{localtime}.pth'))
    else:
        torch.save(model.state_dict(), str(path + f'best_{mode}_epoch{epoch}_{localtime}.pth'))
    logging.info(f'best {mode} model {epoch} saved at {localtime}!')
原因2:Windows 文件系统不允许某些字符出现在文件名中,例如 ':' 我们可以通过替换这些字符来确保文件名合法。
解决方法2:

原代码:

    Path(path).mkdir(parents=True,
                     exist_ok=True)  # create a dictionary
    # ipdb.set_trace()
    localtime = time.asctime(time.localtime(time.time()))
    if mode == 'checkpoint':
        state_dict = {'net': model.state_dict(), 'optimizer': optimizer.state_dict()}
        torch.save(state_dict,
                   str(path + f'checkpoint_epoch{epoch}_{localtime}.pth'))
    else:
        torch.save(model.state_dict(), str(path + f'best_{mode}_epoch{epoch}_{localtime}.pth'))
    logging.info(f'best {mode} model {epoch} saved at {localtime}!')

修改后的代码:

    try:
        # mode should be checkpoint or loss or f1score
        Path(path).mkdir(parents=True, exist_ok=True)  # create directory if not exists
        localtime = time.asctime(time.localtime(time.time()))
        safe_time = localtime.replace(':', '_')  # Replace colons with underscores

        if mode == 'checkpoint':
            state_dict = {'net': model.state_dict(), 'optimizer': optimizer.state_dict()}
            save_path = Path(path) / f'checkpoint_epoch{epoch}_{safe_time}.pth'
            torch.save(state_dict, save_path)
        else:
            save_path = Path(path) / f'best_{mode}_epoch{epoch}_{safe_time}.pth'
            torch.save(model.state_dict(), save_path)

        logging.info(f'best {mode} model {epoch} saved at {localtime} in {save_path}!')
    except Exception as e:
        logging.error(f'Error saving model at {path}: {e}')
        raise

至此问题得到解决。

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值