61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
"""
|
||
一键导出 MobileNetV3-Large embedding ONNX 模型。
|
||
自动下载预训练权重,不需要手动装 torch。
|
||
|
||
用法:
|
||
python export_embedding_model.py
|
||
|
||
输出:mobilenetv3_large_embedding.onnx(约 20MB)
|
||
"""
|
||
|
||
import subprocess, sys, os
|
||
|
||
def run(cmd):
|
||
print(f"$ {cmd}")
|
||
subprocess.check_call(cmd, shell=True)
|
||
|
||
def main():
|
||
# 1. 自动装依赖(如果缺的话)
|
||
try:
|
||
import torch
|
||
import torchvision
|
||
except ImportError:
|
||
print("正在安装 torch + torchvision(首次需要,等待下载~200MB)...")
|
||
run(f"{sys.executable} -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu")
|
||
|
||
import torch
|
||
import torchvision.models as models
|
||
|
||
# 2. 加载预训练权重(自动下载 ~20MB)
|
||
print("正在下载 MobileNetV3-Large 预训练权重...")
|
||
model = models.mobilenet_v3_large(weights='DEFAULT')
|
||
|
||
# 3. 去掉分类头,只保留特征提取部分
|
||
# 输出 960 维特征向量
|
||
model.classifier = torch.nn.Identity()
|
||
model.eval()
|
||
|
||
# 4. 导出 ONNX
|
||
dummy = torch.randn(1, 3, 224, 224)
|
||
output_path = "mobilenetv3_large_embedding.onnx"
|
||
torch.onnx.export(
|
||
model, dummy, output_path,
|
||
input_names=["input"],
|
||
output_names=["output"],
|
||
opset_version=17,
|
||
dynamic_axes={"input": {0: "batch_size"}, "output": {0: "batch_size"}}
|
||
)
|
||
print(f"导出成功:{output_path} ({os.path.getsize(output_path)/1024/1024:.0f}MB)")
|
||
|
||
# 5. 验证
|
||
try:
|
||
import onnxruntime
|
||
session = onnxruntime.InferenceSession(output_path)
|
||
result = session.run(None, {"input": dummy.numpy()})
|
||
print(f"验证通过:输出形状 {result[0].shape},特征维度 {result[0].shape[1]}")
|
||
except ImportError:
|
||
print("验证跳过(未安装 onnxruntime)")
|
||
|
||
if __name__ == "__main__":
|
||
main()
|