c++ 部署模型

将模型转为onnx

选用pytorch框架,训练resnet18二分类,将二分类模型转为onnx模型

from typing_extensions import dataclass_transform
import torch
import torch.nn as nn
from torchvision import models, transforms

import cv2 as cv
import numpy as np
from PIL import Image

class_name = ['ant', 'bee']
# device = torch.device('cuda' if torch.cuda.is_available else 'cpu')
img = Image.open(r'D:\Projects\PythonProjects\ResnetClassifier\data\hymenoptera_data\val\ants\800px-Meat_eater_ant_qeen_excavating_hole.jpg')
img = img.convert('RGB')
img = img.resize((224, 224))

img = np.array(img, np.float32)
preprocess_img = img/255.0
img_data = np.expand_dims(np.transpose(preprocess_img, (2, 0, 1)), 0)


device = torch.device('cpu')
model = models.resnet18()
model_l = model.fc.in_features
model.fc = nn.Linear(model_l, 2)
model_x = model.to(device)
model_x.eval()

model_x.load_state_dict(torch.load("D:\\Projects\\PythonProjects\\Datasets\\resnet18_bee_and_ant.pth", map_location=torch.device('cpu')))

tensor_img = torch.from_numpy(img_data)
out = model_x(tensor_img)
_, pred = torch.max(out<
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
部署 TensorFlow 模型,可以按照以下步骤进行操作: 1. 准备模型:首先,需要训练和保存 TensorFlow 模型。可以使用 TensorFlow 提供的高级 API,如 Keras,或使用原生 TensorFlow API 进行模型训练。在训练完成后,保存模型的权重和结构。 2. 导出模型:将模型导出为 TensorFlow 支持的格式,如 SavedModel 或 TensorFlow 格式(.pb)。这样做可以确保在部署过程中可以轻松加载模型。导出模型时,记得保存模型的元数据和签名。 3. 安装 TensorFlow 和相关库:在部署 TensorFlow 模型之前,需要在目标环境中安装 TensorFlow 和其他必要的软件库。可以使用 pip 或 conda 进行安装,并确保使用与训练时相同的 TensorFlow 版本。 4. 加载和推理:在部署环境中,导入 TensorFlow 和相关库,并加载导出的模型。使用输入数据对模型进行推理,并获取输出结果。可以通过 TensorFlow 提供的预测函数直接进行推理,或使用 TensorFlow Serving 等工具进行更高级的模型部署。 5. 部署到服务器或云平台:如果要在服务器或云平台上部署 TensorFlow 模型,可以使用诸如 Docker 和 Kubernetes 的容器化技术。这样可以将模型包装为容器,并提供可扩展的部署解决方案。 6. 性能优化:在部署期间,可以进行一些性能优化以提高模型的推理速度和效率。例如,使用 TensorFlow Lite 将模型转换为适用于移动设备或嵌入式设备的优化版本,或使用 TensorFlow GPU 支持利用 GPU 加速模型推理。 总之,部署 TensorFlow 模型需要准备模型、导出模型、安装所需库、加载和推理模型,并根据实际需求选择合适的部署方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值