当前位置: 首页 > news >正文

做运营需要知道素材网站外贸假发网站

做运营需要知道素材网站,外贸假发网站,wordpress生成了太多图片,网站建设评审会的通知香橙派 AIpro 昇腾 Ascend C 分类模型适配 flyfish 文章目录 香橙派 AIpro 昇腾 Ascend C 分类模型适配前言一、PyTorch官网resnet模型处理方式1、PyTorch模型 导出 onnx格式2、完整测试 输出top1结果3、完整测试 输出top5结果 二、YOLOv8官网resnet模型Python处理方式三、昇腾…香橙派 AIpro 昇腾 Ascend C 分类模型适配 flyfish 文章目录 香橙派 AIpro 昇腾 Ascend C 分类模型适配前言一、PyTorch官网resnet模型处理方式1、PyTorch模型 导出 onnx格式2、完整测试 输出top1结果3、完整测试 输出top5结果 二、YOLOv8官网resnet模型Python处理方式三、昇腾resnet原始的C预处理方式四、香橙派 AIpro 分类模型 自带Python示例的预处理方式五、对比不同1、Normalize2、CenterCrop 六、香橙派 AIpro 分类模型resnet C 适配方式1 代码如下方式2 代码如下 七、可以这样处理的原因 模型可以从多个地方获取这里说明两个地方 从PyTorch官网获取到的resnet模型 从YOLOv8官网获取到的resnet模型 前言 模型的处理 查看香橙派 AIpro SoC版本 根据上面查看到SoC版本是 310B4在转换模型时选择Ascend310B4 在硬件上可以加装一块固态盘装上之后开机自动识别 一、PyTorch官网resnet模型处理方式 1、PyTorch模型 导出 onnx格式 从PyTorch官网获取到的resnet模型 # -*- coding: utf-8 -*- import torch import torchvision import onnx import onnxruntime import torch.nn as nn # 创建 PyTorch ResNet50 模型实例#在线下载 #model torchvision.models.resnet50(pretrainedTrue)#本地加载 checkpoint_path /home/model/resnet50-19c8e357.pth model torchvision.models.resnet50().to(cpu) checkpoint torch.load(checkpoint_path,map_locationtorch.device(cpu))model.load_state_dict(checkpoint) model.eval()batch_size 1 input_shape (batch_size, 3, 224, 224) input_data torch.randn(input_shape)# 将模型转换为 ONNX 格式 output_path_static resnet_static.onnx output_path_dynamic resnet_dynamic.onnx# dynamic torch.onnx.export(model, input_data, output_path_dynamic,input_names[input], output_names[output],dynamic_axes{input: {0: batch_size}, output: {0: batch_size}})#static torch.onnx.export(model, input_data, output_path_static,input_names[input], output_names[output])# 简单测试 session onnxruntime.InferenceSession(output_path_dynamic) new_batch_size 2 new_input_shape (new_batch_size, 3, 224, 224) new_input_data torch.randn(new_input_shape) outputs session.run([output], {input: new_input_data.numpy()}) print(outputs)2、完整测试 输出top1结果 # -*- coding: utf-8 -*- import onnxruntime import numpy as np from torchvision import datasets, models, transforms from PIL import Image import torch.nn as nn import torchdef postprocess(outputs):res list()outputs_exp np.exp(outputs)outputs outputs_exp / np.sum(outputs_exp, axis1)[:,None]predictions np.argmax(outputs, axis 1)for pred, output in zip(predictions, outputs):score output[pred]res.append((pred.tolist(),float(score)))return resonnx_model_path /home/model/resnet50_static.onnxort_session onnxruntime.InferenceSession(onnx_model_path)transform transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),transforms.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225]), ])image Image.open(/home/dog1_1024_683.jpg) image transform(image).unsqueeze(0) # 增加批处理维度input_data image.detach().numpy()outputs_np ort_session.run(None, {input: input_data}) outputs outputs_np[0]res postprocess(outputs) print(res)[(162, 0.9634788632392883)] 3、完整测试 输出top5结果 先把标签文件imagenet_classes.txt下载下来 curl -o imagenet_classes.txt https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt# -*- coding: utf-8 -*- import onnxruntime import numpy as np from torchvision import datasets, models, transforms from PIL import Image import torch.nn as nn import torch from onnx import numpy_helper import timewith open(imagenet_classes.txt, r) as f:categories [s.strip() for s in f.readlines()]def softmax(x):e_x np.exp(x - np.max(x))return e_x / e_x.sum()onnx_model_path /home/model/resnet50_static.onnxort_session onnxruntime.InferenceSession(onnx_model_path)transform transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),transforms.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225]), ])image Image.open(/home/dog1_1024_683.jpg) image transform(image).unsqueeze(0) # 增加批处理维度session onnxruntime.InferenceSession(onnx_model_path, providers[CPUExecutionProvider])latency []start time.time() input_arr image.detach().numpy()output session.run([], {input:input_arr})[0] latency.append(time.time() - start) output output.flatten()output softmax(output) top5_catid np.argsort(-output)[:5] for catid in top5_catid:print(catid, categories[catid], output[catid])print(ONNX Runtime CPU Inference time {} ms.format(format(sum(latency) * 1000 / len(latency), .2f)))162 beagle 0.963479 167 English foxhound 0.020814817 166 Walker hound 0.011742038 161 basset 0.0024754668 164 bluetick 0.0004774033 ONNX Runtime CPU Inference time 20.01 ms预处理方式 在计算机视觉领域很多预训练模型例如ResNet、VGG等都是基于ImageNet数据集训练的。因此使用相同的均值和标准差对数据进行标准化处理可以确保输入数据与预训练模型的输入分布一致有助于充分利用预训练模型的优势。 transforms.Normalize函数通过减去均值并除以标准差将输入图像的每个通道进行标准化处理。 ImageNet数据集的结构 训练集包含超过120万张图像用于训练模型。 验证集包含50,000张图像用于模型验证和调整超参数。 测试集包含100,000张图像用于评估模型的最终性能。 使用ImageNet数据集的注意事项 预处理在使用ImageNet数据集进行训练时通常需要对图像进行标准化处理常用的均值和标准差为 均值0.485,0.456,0.406 标准差0.229,0.224,0.225 数据增强为了提升模型的泛化能力通常会对训练图像进行数据增强处理例如随机裁剪、水平翻转等 transforms.Resize 处理方式不同有的地方是256有的地方用的是224 二、YOLOv8官网resnet模型Python处理方式 从YOLOv8官网获取到的resnet模型 YOLOv8由Ultralytics 提供YOLOv8 支持全方位的视觉 AI 任务包括检测、分割、姿态估计、跟踪和分类。 yolov8-cls-resnet50配置 # Parameters nc: 1000 # number of classes scales: # model compound scaling constants, i.e. modelyolov8n-cls.yaml will call yolov8-cls.yaml with scale n# [depth, width, max_channels]n: [0.33, 0.25, 1024]s: [0.33, 0.50, 1024]m: [0.67, 0.75, 1024]l: [1.00, 1.00, 1024]x: [1.00, 1.25, 1024]# YOLOv8.0n backbone backbone:# [from, repeats, module, args]- [-1, 1, ResNetLayer, [3, 64, 1, True, 1]] # 0-P1/2- [-1, 1, ResNetLayer, [64, 64, 1, False, 3]] # 1-P2/4- [-1, 1, ResNetLayer, [256, 128, 2, False, 4]] # 2-P3/8- [-1, 1, ResNetLayer, [512, 256, 2, False, 6]] # 3-P4/16- [-1, 1, ResNetLayer, [1024, 512, 2, False, 3]] # 4-P5/32# YOLOv8.0n head head:- [-1, 1, Classify, [nc]] # Classify该分类模型的预处理方式如下 IMAGENET_MEAN 0.485, 0.456, 0.406 # RGB mean IMAGENET_STD 0.229, 0.224, 0.225 # RGB standard deviation def classify_transforms(size224,meanDEFAULT_MEAN,stdDEFAULT_STD,interpolationImage.BILINEAR,crop_fraction: float DEFAULT_CROP_FRACTION, ):Classification transforms for evaluation/inference. Inspired by timm/data/transforms_factory.py.Args:size (int): image sizemean (tuple): mean values of RGB channelsstd (tuple): std values of RGB channelsinterpolation (T.InterpolationMode): interpolation mode. default is T.InterpolationMode.BILINEAR.crop_fraction (float): fraction of image to crop. default is 1.0.Returns:(T.Compose): torchvision transformsimport torchvision.transforms as T # scope for faster import ultralyticsif isinstance(size, (tuple, list)):assert len(size) 2scale_size tuple(math.floor(x / crop_fraction) for x in size)else:scale_size math.floor(size / crop_fraction)scale_size (scale_size, scale_size)# Aspect ratio is preserved, crops center within image, no borders are added, image is lostif scale_size[0] scale_size[1]:# Simple case, use torchvision built-in Resize with the shortest edge mode (scalar size arg)tfl [T.Resize(scale_size[0], interpolationinterpolation)]else:# Resize the shortest edge to matching target dim for non-square targettfl [T.Resize(scale_size)]tfl [T.CenterCrop(size)]tfl [T.ToTensor(),T.Normalize(meantorch.tensor(mean),stdtorch.tensor(std),),]return T.Compose(tfl) 标准化数据分布深度学习模型通常在训练过程中受益于输入数据的标准化即将输入数据的分布调整为零均值和单位方差。这样可以确保所有特征具有相似的尺度从而提高学习效率。对于图像数据而言这意味着将像素值从原始范围通常是0-255转换到一个更统一的范围。 加速收敛通过减去平均值并除以标准差可以使梯度下降等优化算法在训练初期更快地收敛。这是因为这样的预处理减少了输入数据的方差使得学习过程更加稳定和高效。 网络权重初始化的匹配很多预训练模型尤其是基于ImageNet训练的模型在设计和训练时就假设了输入数据经过了这样的标准化处理。因此在微调这些模型或使用它们作为特征提取器时继续使用相同的预处理步骤能保证数据分布与模型预期的一致性有助于保持模型性能。 泛化能力ImageNet是一个大规模、多样化的图像数据集其统计特性如颜色分布在很大程度上代表了自然图像的普遍特征。因此使用ImageNet的统计量进行归一化有助于模型学习到更广泛适用的特征增强模型在新数据上的泛化能力。 如果任务或数据集与ImageNet有显著不同直接使用ImageNet的均值和标准差可能不是最佳选择。在这种情况下根据自己数据集的统计特性来计算并使用均值和标准差进行归一化可能会得到更好的效果。 原始代码 三、昇腾resnet原始的C预处理方式 namespace {const float min_chn_0 123.675;const float min_chn_1 116.28;const float min_chn_2 103.53;const float var_reci_chn_0 0.0171247538316637;const float var_reci_chn_1 0.0175070028011204;const float var_reci_chn_2 0.0174291938997821; }Result SampleResnetQuickStart::ProcessInput(const string testImgPath) {// read image from file by cvimagePath testImgPath;srcImage imread(testImgPath);Mat resizedImage;// zoom image to modelWidth_ * modelHeight_resize(srcImage, resizedImage, Size(modelWidth_, modelHeight_));// get properties of imageint32_t channel resizedImage.channels();int32_t resizeHeight resizedImage.rows;int32_t resizeWeight resizedImage.cols;// data standardizationfloat meanRgb[3] {min_chn_2, min_chn_1, min_chn_0};float stdRgb[3] {var_reci_chn_2, var_reci_chn_1, var_reci_chn_0};// create malloc of image, which is shape with NCHWimageBytes (float*)malloc(channel * resizeHeight * resizeWeight * sizeof(float));memset(imageBytes, 0, channel * resizeHeight * resizeWeight * sizeof(float));uint8_t bgrToRgb2;// image to bytes with shape HWC to CHW, and switch channel BGR to RGBfor (int c 0; c channel; c){for (int h 0; h resizeHeight; h){for (int w 0; w resizeWeight; w){int dstIdx (bgrToRgb - c) * resizeHeight * resizeWeight h * resizeWeight w;imageBytes[dstIdx] static_castfloat((resizedImage.atcv::Vec3b(h, w)[c] -1.0f*meanRgb[c]) * 1.0f*stdRgb[c] );}}}return SUCCESS; }四、香橙派 AIpro 分类模型 自带Python示例的预处理方式 img_origin Image.open(pic_path).convert(RGB) from torchvision import transforms normalize transforms.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225]) trans_list transforms.Compose([transforms.Resize(256),transforms.CenterCrop(224),transforms.ToTensor(),normalize]) img trans_list(img_origin)运行 (base) HwHiAiUserorangepiaipro:~/samples/model-adapter-models/cls/edge_infer$ ./run.sh set env successfully!! start exec atc [Sample] init resource stage: Init resource success load model mobilenetv3_100_bs1.om Init model resource [Model] create model output dataset: [Model] create model output dataset success [Model] class Model init resource stage success acl.mdl.execute exhaust 0:00:00.004750 class result : cat pic name: cat pre cost:7050.8ms forward cost:6.8ms post cost:0.0ms total cost:7057.6ms FPS:0.1 image name :./data/cat/cat.23.jpg, infer result: cat acl.mdl.execute exhaust 0:00:00.004660 class result : cat pic name: cat pre cost:14.0ms forward cost:5.2ms post cost:0.0ms total cost:19.2ms FPS:52.2 image name :./data/cat/cat.76.jpg, infer result: cat五、对比不同 经过比对有以下不同处 1、Normalize Normalize 数值的不同YOLOv8和PyTorch 是IMAGENET_MEAN 和 IMAGENET_STD transforms.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225])昇腾的是 namespace {const float min_chn_0 123.675;const float min_chn_1 116.28;const float min_chn_2 103.53;const float var_reci_chn_0 0.0171247538316637;const float var_reci_chn_1 0.0175070028011204;const float var_reci_chn_2 0.0174291938997821; }2、CenterCrop YOLOv8和PyTorch都有 CenterCrop 中心剪裁处理 六、香橙派 AIpro 分类模型resnet C 适配 根据对比的结果所以我们只要处理IMAGENET_MEAN 和 IMAGENET_STD 在加上CenterCrop 中心剪裁处理 所以我们可以增加centercrop_and_resize函数然后在ProcessInput调用即可。 方式1 代码如下 static const float IMAGENET_MEAN[3] { 0.485, 0.456, 0.406 }; static const float IMAGENET_STD[3] { 0.229, 0.224, 0.225 };void centercrop_and_resize(const cv::Mat src_img, cv::Mat dst_img,int target_size) {int height src_img.rows;int width src_img.cols;if(height width)// hw{cv::resize(src_img, dst_img, cv::Size(target_size,target_size * height / width), 0, 0, cv::INTER_AREA);}else{cv::resize(src_img, dst_img, cv::Size(target_size * width / height,target_size), 0, 0, cv::INTER_AREA);}height dst_img.rows;width dst_img.cols;cv::Point center(width/2, height/2);cv::Size size(target_size, target_size);cv::getRectSubPix(dst_img, size, center, dst_img); } Result SampleResnetQuickStart::ProcessInput(const string testImgPath) {// read image from file by cvimagePath testImgPath;srcImage imread(testImgPath);cv::cvtColor(srcImage, srcImage, cv::COLOR_BGR2RGB);Mat resizedImage;centercrop_and_resize(srcImage,resizedImage,224);// get properties of imageint32_t channel resizedImage.channels();int32_t resizeHeight resizedImage.rows;int32_t resizeWeight resizedImage.cols;std::vectorcv::Mat rgbChannels(3);cv::split(resizedImage, rgbChannels);for (size_t i 0; i rgbChannels.size(); i) // resizedImage resizedImage / 255.0;{rgbChannels[i].convertTo(rgbChannels[i], CV_32FC1, 1.0 / ( 255.0* IMAGENET_STD[i]), (0.0 - IMAGENET_MEAN[i]) / IMAGENET_STD[i]);}int len channel * resizeHeight * resizeWeight * sizeof(float);imageBytes (float *)malloc(len);memset(imageBytes, 0, len);int index 0;for (int c 0; c 3; c){ // R,G,Bfor (int h 0; h modelHeight_; h){for (int w 0; w modelWidth_; w){imageBytes[index] rgbChannels[c].atfloat(h, w); // R-G-Bindex;}}}return SUCCESS; }方式2 代码如下 CenterCrop类似如下的写法 char* centercrop_and_resize(cv::Mat iImg, std::vectorint iImgSize, cv::Mat oImg) {if (iImg.channels() 3){oImg iImg.clone();cv::cvtColor(oImg, oImg, cv::COLOR_BGR2RGB);}else{cv::cvtColor(iImg, oImg, cv::COLOR_GRAY2RGB);}int h iImg.rows;int w iImg.cols;int m min(h, w);int top (h - m) / 2;int left (w - m) / 2;cv::resize(oImg(cv::Rect(left, top, m, m)), oImg, cv::Size(iImgSize.at(0), iImgSize.at(1)));return RET_OK; }使用方式 cv::Mat img cv::imread(img_path); std::vectorint imgSize { 640, 640 }; cv::Mat processedImg; centercrop_and_resize(iImg, imgSize, processedImg);processedImg就是我们要得到的cv::Mat 。图像经过centercrop最后大小是640, 640通道顺序是RGB 七、可以这样处理的原因 不同的Normalize数值之间的转换关系 # namespace { # const float min_chn_0 123.675; # const float min_chn_1 116.28; # const float min_chn_2 103.53; # const float var_reci_chn_0 0.0171247538316637; # const float var_reci_chn_1 0.0175070028011204; # const float var_reci_chn_2 0.0174291938997821; # }import numpy as np mean np.array([0.485, 0.456, 0.406]) std np.array([0.229, 0.224, 0.225])print(mean * 255)# [123.675 116.28 103.53 ] print(1/(std*255))#[0.01712475 0.017507 0.01742919]两者是可以相互转换的 # 0.485 × 255 123.675 # 0.456 × 255 116.28 # 0.406 × 255 103.53# 0.229 × 255 58.395 # 0.224 × 255 57.12 # 0.225 × 255 57.375# 1 ÷ 58.395 0.017124754 # 1 ÷ 57.12 0.017507003 # 1 ÷ 57.375 0.017429194原始整个流程如下 适配后的处理就在上面第3步ProcessInput加上了 CenterCrop 链接地址 https://www.hiascend.com/zh/ https://gitee.com/ascend 华为原版的resnet图片分类有C版本和Python版本 https://gitee.com/ascend/samples/tree/master/inference/modelInference/sampleResnetQuickStart/
http://www.dnsts.com.cn/news/225954.html

相关文章:

  • 网站建设 金手指 下拉22建设网站你认为需要注意
  • 哪个网站可以做水果销售代理免费下载模板的网站有哪些
  • 创新的菏泽网站建设wordpress媒体库里文件
  • 娄底市住房和城乡建设局网站微信如何做积分商城网站
  • 北京造价信息网深圳seo优化培训
  • 苏州市网站建设苏州网站建设哪个比较牛
  • 平面设计好的网站做采购 通常在什么网站看
  • 电子商城网站建设的实训内容记述网站源码怎么弄
  • 沈阳专业做网站方案重庆住建部官网
  • 网站做301的坏处移动网站优化排名
  • 怎么建网站?宁波最专业的seo公司
  • 医院网站建设运营方案wordpress插件开发教程 pdf
  • 做国外网站 国外人能看到吗wordpress主题高仿雷锋网
  • 在西安建设工程交易中心网站企业网站建设方案 完整版
  • 天津网站建设工具商丘网站公司电话号码
  • 云建站步骤山东城市建设职业学院图书馆网站
  • 电子商务网站建设文献wordpress主题无法发布
  • 合肥php网站开发运城百姓网免费发布信息网
  • 建设银行 成都 招聘网站wordpress 防火墙
  • 高端网站建设企业网站建站小程序开发教程pdf
  • 观音桥网站建设手机管理网站模板下载软件
  • wp网站如何做文件的付费下载唐山建设集团下岗职工网站
  • 网站后台制作表格简单的h5制作开发
  • 网站建设销售还能做吗湖北网站制作公司
  • 有很多长尾怎么做网站内容珠海快速网站建设
  • 专做机械类毕业设计的网站做网站用c语言可以吗
  • 襄阳做网站价格无锡大型网站建设公司
  • 东莞设计兼职网站建设网站系统建设方案
  • 学校html网站模板湖北网页设计师培训
  • 网站推广策划报告航空航天wordpress 开通json