【已解决】YOLO11模型转wts时报错:PytorchStreamReader failed reading zip archive

问题:在把训练好的新YOLO11s模型转wts文件时报错,具体信息如下图(PytorchStreamReader failed reading zip archive: failed finding central directory)

解决:新老版本pytorch之间的兼容问题,改动一下生成wts文件即可。代码帖在下面。

python 复制代码
import sys  # noqa: F401
import argparse
import os
import struct
import torch


def parse_args():
    parser = argparse.ArgumentParser(description='Convert .pt file to .wts')
    parser.add_argument('-w', '--weights', required=True,
                        help='Input weights (.pt) file path (required)')
    parser.add_argument(
        '-o', '--output', help='Output (.wts) file path (optional)')
    parser.add_argument(
        '-t', '--type', type=str, default='detect', choices=['detect', 'cls', 'seg', 'pose', 'obb'],
        help='determines the model is detection/classification')
    args = parser.parse_args()
    if not os.path.isfile(args.weights):
        raise SystemExit('Invalid input file')
    if not args.output:
        args.output = os.path.splitext(args.weights)[0] + '.wts'
    elif os.path.isdir(args.output):
        args.output = os.path.join(
            args.output,
            os.path.splitext(os.path.basename(args.weights))[0] + '.wts')
    return args.weights, args.output, args.type


pt_file, wts_file, m_type = parse_args()

print(f'Generating .wts for {m_type} model')

# Load model
print(f'Loading {pt_file}')

# Initialize
device = 'cpu'

# Load model
model = torch.load(pt_file, map_location=device, weights_only=False)  # Load FP32 weights
model = model['ema' if model.get('ema') else 'model'].float()

if m_type in ['detect', 'seg', 'pose', 'obb']:
    anchor_grid = model.model[-1].anchors * model.model[-1].stride[..., None, None]

    delattr(model.model[-1], 'anchors')

model.to(device).eval()

with open(wts_file, 'w') as f:
    f.write('{}\n'.format(len(model.state_dict().keys())))
    for k, v in model.state_dict().items():
        vr = v.reshape(-1).cpu().numpy()
        f.write('{} {} '.format(k, len(vr)))
        for vv in vr:
            f.write(' ')
            f.write(struct.pack('>f', float(vv)).hex())
        f.write('\n')
相关推荐
java1234_小锋5 分钟前
一周学会Matplotlib3 Python 数据可视化-绘制热力图(Heatmap)
开发语言·python·信息可视化·matplotlib·matplotlib3
一车小面包11 分钟前
机器学习中数据集的划分难点及实现
人工智能·深度学习·机器学习
程序员岳焱42 分钟前
Java 调用 Python 脚本:实现 HelloWorld
java·后端·python
R-G-B1 小时前
【P27 4-8】OpenCV Python——Mat类、深拷贝(clone、copyTo、copy)、浅拷贝,原理讲解与示例代码
人工智能·python·opencv·浅拷贝·深拷贝·opencv python·mat类
ABCDnnie1 小时前
机器学习03-sklearn模型评估指标与knn算法
人工智能·机器学习·sklearn
黎燃2 小时前
智能制造中的AI预测性维护:从理论到实战的深度解析
人工智能
zskj_zhyl2 小时前
银发经济时代:科技赋能养老,温情守护晚年,让老人不再孤独无助
大数据·人工智能·科技·生活
Qforepost2 小时前
智汇河套,量子“风暴”:量子科技未来产业发展论坛深度研讨加速产业成果转化
人工智能·量子计算·量子
coding者在努力2 小时前
从零开始:用PyTorch实现线性回归模型
人工智能·pytorch·线性回归
Giser探索家2 小时前
低空智航平台技术架构深度解析:如何用AI +空域网格破解黑飞与安全管控难题
大数据·服务器·前端·数据库·人工智能·安全·架构