【已解决】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')
相关推荐
码农垦荒笔记2 小时前
Claude Code 2026 年 3 月全面进化:Auto 模式、Computer Use 与云端持续执行重塑 AI 编程工作流
人工智能·ai 编程·claude code·agentic coding·computer use
threerocks2 小时前
【Claude Code 系列课程】01 | Claude Code 架构全览
人工智能·ai编程·claude
熊猫代跑得快2 小时前
Agent 通用架构入门学习
人工智能·agent·智能体
格林威2 小时前
Baumer相机锂电池极片裁切毛刺检测:防止内部短路的 5 个核心方法,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
codeの诱惑2 小时前
推荐算法(三):余弦定理和余弦相似度的关系及公式推导
人工智能·机器学习·推荐算法
三枪一个麻辣烫3 小时前
gemini Adobe Illustrator visio draw.io画图
图像处理·人工智能·甘特图
HIT_Weston3 小时前
32、【Agent】【OpenCode】模型配置(配置 Qwen 模型)
人工智能·agent·opencode
丝斯20113 小时前
AI学习笔记整理(79)——Python学习8
人工智能·笔记·学习
鹧鸪云光伏3 小时前
微电网设计系统及经济收益计算
大数据·人工智能·光伏·储能设计方案
飞哥数智坊3 小时前
地铁上的30分钟,我用龙虾搞定了一份PPT
人工智能