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

做商标网站c 网站开发的优点

做商标网站,c 网站开发的优点,深圳平湖网站开发,学做网站 空间 域名打卡 目录 打卡 实验1#xff1a;K近邻算法实现红酒聚类 数据准备 模型构建--计算距离 计算演示 模型预测 实验2#xff1a;基于MobileNetv2的垃圾分类 任务说明 数据集 参数配置#xff08;训练/验证/推理#xff09; 数据预处理 MobileNetV2模型搭建 Mobile…打卡 目录 打卡 实验1K近邻算法实现红酒聚类 数据准备 模型构建--计算距离 计算演示 模型预测 实验2基于MobileNetv2的垃圾分类 任务说明 数据集 参数配置训练/验证/推理 数据预处理 MobileNetV2模型搭建 MobileNetV2模型的训练与测试 模型训练与测试 训练过程 模型推理 导出AIR/GEIR/ONNX模型文件 此次两个分类实验中一个是经典的knn聚类算法一种是轻量级cnn网络都是基于较轻资源可以实现的任务。 可以在任务简单、逻辑清晰的任务中使用。 实验1K近邻算法实现红酒聚类 K近邻算法K-Nearest-Neighbor, KNN是一种用于分类和回归的非参数统计方法于1968年提出(Cover等人,1967)。 思想如何确定某个样本的类别计算 找出该样本与所有样本的中距离最近的K个样本统计这K个样本的类别并投票投票最多的类别即确定为该样本的类别。knn的3个要素 K值一个样本的分类是由K个邻居的“多数表决”确定的。K值越小容易受噪声影响反之会使类别之间的界限变得模糊。k的取值可以根据问题和数据特点来确定。在具体实现时可以考虑样本的权重即每个样本有不同的投票权重这种方法称为带权重的k近邻算法它是一种变种的k近邻算法。如带样本权重的回归预测函数为其中 为第个 样本的权重。 距离度量反映了特征空间中两个样本间的相似度距离越小越相似。常用的有Lp距离p2时即为欧式距离、曼哈顿距离、海明距离、切比雪夫距离等。 分类决策规则通常是多数表决或者基于距离加权的多数表决权值与距离成反比。 数据准备 Wine数据集是模式识别最著名的数据集之一Wine数据集的官网Wine Data Set。这些数据是对来自意大利同一地区但来自三个不同品种的葡萄酒进行化学分析的结果。数据集分析了三种葡萄酒中每种所含13种成分的量。这些13种属性是 Alcohol酒精Malic acid苹果酸Ash灰Alcalinity of ash灰的碱度Magnesium镁Total phenols总酚Flavanoids类黄酮Nonflavanoid phenols非黄酮酚Proanthocyanins原花青素Color intensity色彩强度Hue色调OD280/OD315 of diluted wines稀释酒的OD280/OD315Proline脯氨酸 方式一从Wine数据集官网下载wine.data文件。方式二从华为云OBS中下载wine.data文件。 部分数据如下图第1列为类别214列为13种化学成分数据。 共178条数据其中1类是1-59行2类是60-130行3类是131-178行。取两个属性观察样本分布情况和可区分性如下图。 共178条数据按照128:50划分为训练集和验证集样本。 import numpy as nptrain_idx np.random.choice(178, 128, replaceFalse) test_idx np.array(list(set(range(178)) - set(train_idx))) X_train, Y_train X[train_idx], Y[train_idx] X_test, Y_test X[test_idx], Y[test_idx]print(np.shape(X_train)) ### (128, 13) print(np.shape(X_test)) ### (50, 13) print(np.shape(Y_train)) ## (128,) print(np.shape(Y_test)) 模型构建--计算距离 同样地继承 nn.Cell 类构建模型使用 ops.tile, square, ReduceSum, sqrt, TopK等算子通过矩阵运算的方式同时计算输入样本x和已明确分类的其他样本X_train的距离欧式距离并计算出top k 近邻。 class KnnNet(nn.Cell):def __init__(self, k):super(KnnNet, self).__init__()self.k kdef construct(self, x, X_train):#平铺输入x以匹配X_train中的样本数即复制x到128份与X_train一样的维度方便计算。x_tile ops.tile(x, (128, 1))square_diff ops.square(x_tile - X_train)square_dist ops.sum(square_diff, 1)dist ops.sqrt(square_dist)#-dist表示值越大样本就越接近: 沿给定维度查找k个最大或最小元素和对应的索引需要排序的维度dimsNone,因为是1维。默认 sortedTrue 按值降序排序。### 负最大即正距离最小即最近邻的K个值values, indices ops.topk(-dist, self.k)return indicesdef knn(knn_net, x, X_train, Y_train):x, X_train ms.Tensor(x), ms.Tensor(X_train)indices knn_net(x, X_train)topk_cls [0]*len(indices.asnumpy())for idx in indices.asnumpy():topk_cls[Y_train[idx]] 1cls np.argmax(topk_cls)return cls 计算演示 如上图是针对一个验证样本筛选出来13个特征中计算knn 算法的5个距离最小的样本后拿到对应的分类类别 Y_train[idx]为k5个样本对应的类别进行统计取统计值最大的类别np.argmax(topk_cls)即为分类结果。 模型预测 下面是所有验证样本的统计计算验证精度。 acc 0 knn_net KnnNet(5) for x, y in zip(X_test, Y_test):pred knn(knn_net, x, X_train, Y_train)acc (pred y)print(label: %d, prediction: %s % (y, pred))print(Validation accuracy is %f % (acc/len(Y_test))) 根据下图演示说明KNN算法在该3分类任务上有效能根据酒的13种属性判断出酒的品种。多次改变k测试效果一般验证精度不超过80%。 实验2基于MobileNetv2的垃圾分类 MobileNet网络是由Google团队于2017年提出的专注于移动端、嵌入式或IoT设备的轻量级CNN网络相比于传统的卷积神经网络MobileNet网络使用深度可分离卷积Depthwise Separable Convolution的思想在准确率小幅度降低的前提下大大减小了模型参数与运算量。并引入宽度系数 α和分辨率系数 β使模型满足不同应用场景的需求。 由于MobileNet网络中Relu激活函数处理低维特征信息时会存在大量的丢失所以MobileNetV2网络提出使用倒残差结构Inverted residual block和 Linear Bottlenecks来设计网络以提高模型的准确率且优化后的模型更小。 如下图Inverted residual block结构是先使用1x1卷积进行升维然后使用3x3的DepthWise卷积最后使用1x1的卷积进行降维与Residual block结构相反。Residual block是先使用1x1的卷积进行降维然后使用3x3的卷积最后使用1x1的卷积进行升维。 说明 详细内容可参见MobileNetV2论文 任务说明 通过读取本地图像数据作为输入对图像中的垃圾物体进行检测并且将检测结果图片保存到文件中。 数据集 权重文件https://ascend-professional-construction-dataset.obs.cn-north-4.myhuaweicloud.com:443/ComputerVision/mobilenetV2-200_1067.zip数据文件https://ascend-professional-construction-dataset.obs.cn-north-4.myhuaweicloud.com:443/MindStudio-pc/data_en.zip环境添加pip install easydict import math import numpy as np import os import random from download import downloadfrom matplotlib import pyplot as plt from easydict import EasyDict from PIL import Image import numpy as np import mindspore.nn as nn from mindspore import ops as P from mindspore.ops import add from mindspore import Tensor import mindspore.common.dtype as mstype import mindspore.dataset as de import mindspore.dataset.vision as C import mindspore.dataset.transforms as C2 import mindspore as ms from mindspore import set_context, nn, Tensor, load_checkpoint, save_checkpoint, export from mindspore.train import Model from mindspore.train import Callback, LossMonitor, ModelCheckpoint, CheckpointConfigos.environ[GLOG_v] 3 # Log level includes 3(ERROR), 2(WARNING), 1(INFO), 0(DEBUG). os.environ[GLOG_logtostderr] 0 # 0输出到文件1输出到屏幕 os.environ[GLOG_log_dir] ../../log # 日志目录 os.environ[GLOG_stderrthreshold] 2 # 输出到目录也输出到屏幕3(ERROR), 2(WARNING), 1(INFO), 0(DEBUG). set_context(modems.GRAPH_MODE, device_targetCPU, device_id0) # 设置采用图模式执行设备为Ascend## 下载预训练权重文件 url https://ascend-professional-construction-dataset.obs.cn-north-4.myhuaweicloud.com:443/ComputerVision/mobilenetV2-200_1067.zip path download(url, ./, kindzip, replaceTrue) https://ascend-professional-construction-dataset.obs.cn-north-4.myhuaweicloud.com:443/MindStudio-pc/data_en.zip 参数配置训练/验证/推理 # 垃圾分类数据集标签以及用于标签映射的字典。 garbage_classes {干垃圾: [贝壳, 打火机, 旧镜子, 扫把, 陶瓷碗, 牙刷, 一次性筷子, 脏污衣服],可回收物: [报纸, 玻璃制品, 篮球, 塑料瓶, 硬纸板, 玻璃瓶, 金属制品, 帽子, 易拉罐, 纸张],湿垃圾: [菜叶, 橙皮, 蛋壳, 香蕉皮],有害垃圾: [电池, 药片胶囊, 荧光灯, 油漆桶] }class_cn [贝壳, 打火机, 旧镜子, 扫把, 陶瓷碗, 牙刷, 一次性筷子, 脏污衣服,报纸, 玻璃制品, 篮球, 塑料瓶, 硬纸板, 玻璃瓶, 金属制品, 帽子, 易拉罐, 纸张,菜叶, 橙皮, 蛋壳, 香蕉皮,电池, 药片胶囊, 荧光灯, 油漆桶] class_en [Seashell, Lighter,Old Mirror, Broom,Ceramic Bowl, Toothbrush,Disposable Chopsticks,Dirty Cloth,Newspaper, Glassware, Basketball, Plastic Bottle, Cardboard,Glass Bottle, Metalware, Hats, Cans, Paper,Vegetable Leaf,Orange Peel, Eggshell,Banana Peel,Battery, Tablet capsules,Fluorescent lamp, Paint bucket]index_en {Seashell: 0, Lighter: 1, Old Mirror: 2, Broom: 3, Ceramic Bowl: 4, Toothbrush: 5, Disposable Chopsticks: 6, Dirty Cloth: 7,Newspaper: 8, Glassware: 9, Basketball: 10, Plastic Bottle: 11, Cardboard: 12, Glass Bottle: 13, Metalware: 14, Hats: 15, Cans: 16, Paper: 17,Vegetable Leaf: 18, Orange Peel: 19, Eggshell: 20, Banana Peel: 21,Battery: 22, Tablet capsules: 23, Fluorescent lamp: 24, Paint bucket: 25}# 训练超参 config EasyDict({num_classes: 26,image_height: 224,image_width: 224,#data_split: [0.9, 0.1],backbone_out_channels:1280,batch_size: 16,eval_batch_size: 8,epochs: 10,lr_max: 0.05,momentum: 0.9,weight_decay: 1e-4,save_ckpt_epochs: 1,dataset_path: ./data_en,class_index: index_en,pretrained_ckpt: ./mobilenetV2-200_1067.ckpt # mobilenetV2-200_1067.ckpt }) 数据预处理 用ImageFolderDataset方法读取垃圾分类数据集并整体对数据集进行处理。 读取数据集时指定训练集和测试集首先对整个数据集进行归一化修改图像频道等预处理操作。然后对训练集的数据依次进行RandomCropDecodeResize、RandomHorizontalFlip、RandomColorAdjust、shuffle操作以增加训练数据的丰富度对测试集进行Decode、Resize、CenterCrop等预处理操作最后返回处理后的数据集。 def create_dataset(dataset_path, config, trainingTrue, buffer_size1000):create a train or eval datasetArgs:dataset_path(string): the path of dataset.config(struct): the config of train and eval in diffirent platform.Returns:train_dataset, val_datasetdata_path os.path.join(dataset_path, train if training else test)ds de.ImageFolderDataset(data_path, num_parallel_workers4, class_indexingconfig.class_index)resize_height config.image_heightresize_width config.image_widthnormalize_op C.Normalize(mean[0.485*255, 0.456*255, 0.406*255], std[0.229*255, 0.224*255, 0.225*255])change_swap_op C.HWC2CHW()type_cast_op C2.TypeCast(mstype.int32)if training:crop_decode_resize C.RandomCropDecodeResize(resize_height, scale(0.08, 1.0), ratio(0.75, 1.333))horizontal_flip_op C.RandomHorizontalFlip(prob0.5)color_adjust C.RandomColorAdjust(brightness0.4, contrast0.4, saturation0.4)train_trans [crop_decode_resize, horizontal_flip_op, color_adjust, normalize_op, change_swap_op]train_ds ds.map(input_columnsimage, operationstrain_trans, num_parallel_workers4)train_ds train_ds.map(input_columnslabel, operationstype_cast_op, num_parallel_workers4)train_ds train_ds.shuffle(buffer_sizebuffer_size)ds train_ds.batch(config.batch_size, drop_remainderTrue)else:decode_op C.Decode()resize_op C.Resize((int(resize_width/0.875), int(resize_width/0.875)))center_crop C.CenterCrop(resize_width)eval_trans [decode_op, resize_op, center_crop, normalize_op, change_swap_op]eval_ds ds.map(input_columnsimage, operationseval_trans, num_parallel_workers4)eval_ds eval_ds.map(input_columnslabel, operationstype_cast_op, num_parallel_workers4)ds eval_ds.batch(config.eval_batch_size, drop_remainderTrue)return dsds create_dataset(dataset_pathconfig.dataset_path, configconfig, trainingFalse) print(ds.get_dataset_size()) data ds.create_dict_iterator(output_numpyTrue)._get_next() images data[image] labels data[label]for i in range(1, 5):plt.subplot(2, 2, i)plt.imshow(np.transpose(images[i], (1,2,0)))plt.title(label: %s % class_en[labels[i]])plt.xticks([]) plt.show() 处理后的数据展示 MobileNetV2模型搭建 继承mindspore.nn.Cell基类搭建网络。 1各层需要预先在__init__方法中定义 2通过定义construct方法来完成神经网络的前向构造。原始模型激活函数为ReLU6池化模块采用是全局平均池化层。 __all__ [MobileNetV2, MobileNetV2Backbone, MobileNetV2Head, mobilenet_v2]def _make_divisible(v, divisor, min_valueNone):if min_value is None:min_value divisornew_v max(min_value, int(v divisor / 2) // divisor * divisor)if new_v 0.9 * v:new_v divisorreturn new_vclass GlobalAvgPooling(nn.Cell):Global avg pooling definition.Args:Returns:Tensor, output tensor.Examples: GlobalAvgPooling()def __init__(self):super(GlobalAvgPooling, self).__init__()def construct(self, x):x P.mean(x, (2, 3))return xclass ConvBNReLU(nn.Cell):Convolution/Depthwise fused with Batchnorm and ReLU block definition.Args:in_planes (int): Input channel.out_planes (int): Output channel.kernel_size (int): Input kernel size.stride (int): Stride size for the first convolutional layer. Default: 1.groups (int): channel group. Convolution is 1 while Depthiwse is input channel. Default: 1.Returns:Tensor, output tensor.Examples: ConvBNReLU(16, 256, kernel_size1, stride1, groups1)def __init__(self, in_planes, out_planes, kernel_size3, stride1, groups1):super(ConvBNReLU, self).__init__()padding (kernel_size - 1) // 2in_channels in_planesout_channels out_planesif groups 1:conv nn.Conv2d(in_channels, out_channels, kernel_size, stride, pad_modepad, paddingpadding)else:out_channels in_planesconv nn.Conv2d(in_channels, out_channels, kernel_size, stride, pad_modepad,paddingpadding, groupin_channels)layers [conv, nn.BatchNorm2d(out_planes), nn.ReLU6()]self.features nn.SequentialCell(layers)def construct(self, x):output self.features(x)return outputclass InvertedResidual(nn.Cell):Mobilenetv2 residual block definition.Args:inp (int): Input channel.oup (int): Output channel.stride (int): Stride size for the first convolutional layer. Default: 1.expand_ratio (int): expand ration of input channelReturns:Tensor, output tensor.Examples: ResidualBlock(3, 256, 1, 1)def __init__(self, inp, oup, stride, expand_ratio):super(InvertedResidual, self).__init__()assert stride in [1, 2]hidden_dim int(round(inp * expand_ratio))self.use_res_connect stride 1 and inp ouplayers []if expand_ratio ! 1:layers.append(ConvBNReLU(inp, hidden_dim, kernel_size1))layers.extend([ConvBNReLU(hidden_dim, hidden_dim,stridestride, groupshidden_dim),nn.Conv2d(hidden_dim, oup, kernel_size1,stride1, has_biasFalse),nn.BatchNorm2d(oup),])self.conv nn.SequentialCell(layers)self.cast P.Cast()def construct(self, x):identity xx self.conv(x)if self.use_res_connect:return P.add(identity, x)return xclass MobileNetV2Backbone(nn.Cell):MobileNetV2 architecture.Args:class_num (int): number of classes.width_mult (int): Channels multiplier for round to 8/16 and others. Default is 1.has_dropout (bool): Is dropout used. Default is falseinverted_residual_setting (list): Inverted residual settings. Default is Noneround_nearest (list): Channel round to . Default is 8Returns:Tensor, output tensor.Examples: MobileNetV2(num_classes1000)def __init__(self, width_mult1., inverted_residual_settingNone, round_nearest8,input_channel32, last_channel1280):super(MobileNetV2Backbone, self).__init__()block InvertedResidual# setting of inverted residual blocksself.cfgs inverted_residual_settingif inverted_residual_setting is None:self.cfgs [# t, c, n, s[1, 16, 1, 1],[6, 24, 2, 2],[6, 32, 3, 2],[6, 64, 4, 2],[6, 96, 3, 1],[6, 160, 3, 2],[6, 320, 1, 1],]# building first layerinput_channel _make_divisible(input_channel * width_mult, round_nearest)self.out_channels _make_divisible(last_channel * max(1.0, width_mult), round_nearest)features [ConvBNReLU(3, input_channel, stride2)]# building inverted residual blocksfor t, c, n, s in self.cfgs:output_channel _make_divisible(c * width_mult, round_nearest)for i in range(n):stride s if i 0 else 1features.append(block(input_channel, output_channel, stride, expand_ratiot))input_channel output_channelfeatures.append(ConvBNReLU(input_channel, self.out_channels, kernel_size1))self.features nn.SequentialCell(features)self._initialize_weights()def construct(self, x):x self.features(x)return xdef _initialize_weights(self):Initialize weights.Args:Returns:None.Examples: _initialize_weights()self.init_parameters_data()for _, m in self.cells_and_names():if isinstance(m, nn.Conv2d):n m.kernel_size[0] * m.kernel_size[1] * m.out_channelsm.weight.set_data(Tensor(np.random.normal(0, np.sqrt(2. / n),m.weight.data.shape).astype(float32)))if m.bias is not None:m.bias.set_data(Tensor(np.zeros(m.bias.data.shape, dtypefloat32)))elif isinstance(m, nn.BatchNorm2d):m.gamma.set_data(Tensor(np.ones(m.gamma.data.shape, dtypefloat32)))m.beta.set_data(Tensor(np.zeros(m.beta.data.shape, dtypefloat32)))propertydef get_features(self):return self.featuresclass MobileNetV2Head(nn.Cell):MobileNetV2 architecture.Args:class_num (int): Number of classes. Default is 1000.has_dropout (bool): Is dropout used. Default is falseReturns:Tensor, output tensor.Examples: MobileNetV2(num_classes1000)def __init__(self, input_channel1280, num_classes1000, has_dropoutFalse, activationNone):super(MobileNetV2Head, self).__init__()# mobilenet headhead ([GlobalAvgPooling(), nn.Dense(input_channel, num_classes, has_biasTrue)] if not has_dropout else[GlobalAvgPooling(), nn.Dropout(0.2), nn.Dense(input_channel, num_classes, has_biasTrue)])self.head nn.SequentialCell(head)self.need_activation Trueif activation Sigmoid:self.activation nn.Sigmoid()elif activation Softmax:self.activation nn.Softmax()else:self.need_activation Falseself._initialize_weights()def construct(self, x):x self.head(x)if self.need_activation:x self.activation(x)return xdef _initialize_weights(self):Initialize weights.Args:Returns:None.Examples: _initialize_weights()self.init_parameters_data()for _, m in self.cells_and_names():if isinstance(m, nn.Dense):m.weight.set_data(Tensor(np.random.normal(0, 0.01, m.weight.data.shape).astype(float32)))if m.bias is not None:m.bias.set_data(Tensor(np.zeros(m.bias.data.shape, dtypefloat32)))propertydef get_head(self):return self.headclass MobileNetV2(nn.Cell):MobileNetV2 architecture.Args:class_num (int): number of classes.width_mult (int): Channels multiplier for round to 8/16 and others. Default is 1.has_dropout (bool): Is dropout used. Default is falseinverted_residual_setting (list): Inverted residual settings. Default is Noneround_nearest (list): Channel round to . Default is 8Returns:Tensor, output tensor.Examples: MobileNetV2(backbone, head)def __init__(self, num_classes1000, width_mult1., has_dropoutFalse, inverted_residual_settingNone, \round_nearest8, input_channel32, last_channel1280):super(MobileNetV2, self).__init__()self.backbone MobileNetV2Backbone(width_multwidth_mult, \inverted_residual_settinginverted_residual_setting, \round_nearestround_nearest, input_channelinput_channel, last_channellast_channel).get_featuresself.head MobileNetV2Head(input_channelself.backbone.out_channel, num_classesnum_classes, \has_dropouthas_dropout).get_headdef construct(self, x):x self.backbone(x)x self.head(x)return xclass MobileNetV2Combine(nn.Cell):MobileNetV2Combine architecture.Args:backbone (Cell): the features extract layers.head (Cell): the fully connected layers.Returns:Tensor, output tensor.Examples: MobileNetV2(num_classes1000)def __init__(self, backbone, head):super(MobileNetV2Combine, self).__init__(auto_prefixFalse)self.backbone backboneself.head headdef construct(self, x):x self.backbone(x)x self.head(x)return xdef mobilenet_v2(backbone, head):return MobileNetV2Combine(backbone, head) MobileNetV2模型的训练与测试 一般情况下模型训练时采用静态学习率如0.01。随着训练步数的增加模型逐渐趋于收敛对权重参数的更新幅度应该逐渐降低以减小模型训练后期的抖动。所以模型训练时可以采用动态下降的学习率常见的学习率下降策略有 polynomial decay/square decay;cosine decay;exponential decay;stage decay. 本次使用cosine decay下降策略如下代码 def cosine_decay(total_steps, lr_init0.0, lr_end0.0, lr_max0.1, warmup_steps0):Applies cosine decay to generate learning rate array.Args:total_steps(int): all steps in training.lr_init(float): init learning rate.lr_end(float): end learning ratelr_max(float): max learning rate.warmup_steps(int): all steps in warmup epochs.Returns:list, learning rate array.lr_init, lr_end, lr_max float(lr_init), float(lr_end), float(lr_max)decay_steps total_steps - warmup_stepslr_all_steps []inc_per_step (lr_max - lr_init) / warmup_steps if warmup_steps else 0for i in range(total_steps):if i warmup_steps:lr lr_init inc_per_step * (i 1)else:cosine_decay 0.5 * (1 math.cos(math.pi * (i - warmup_steps) / decay_steps))lr (lr_max - lr_end) * cosine_decay lr_endlr_all_steps.append(lr)return lr_all_steps 模型训练过程中可以添加检查点Checkpoint用于保存模型的参数以便进行推理及中断后再训练使用。使用场景如下 训练后推理场景再训练场景防止长时间的训练任务异常退出 微调场景 这里加载ImageNet数据上预训练的MobileNetv2进行Fine-tuning只训练最后修改的FC层并在训练过程中保存Checkpoint。 def switch_precision(net, data_type):if ms.get_context(device_target) Ascend:net.to_float(data_type)for _, cell in net.cells_and_names():if isinstance(cell, nn.Dense):cell.to_float(ms.float32) 模型训练与测试 训练之前定义训练函数读取数据并对模型进行实例化定义优化器和损失函数。 在训练MobileNetV2之前对MobileNetV2Backbone层的参数进行了固定使其在训练过程中对该模块的权重参数不进行更新只对MobileNetV2Head模块的参数进行更新。 from mindspore.amp import FixedLossScaleManager import time LOSS_SCALE 1024train_dataset create_dataset(dataset_pathconfig.dataset_path, configconfig) eval_dataset create_dataset(dataset_pathconfig.dataset_path, configconfig) step_size train_dataset.get_dataset_size()backbone MobileNetV2Backbone() #last_channelconfig.backbone_out_channels # Freeze parameters of backbone. You can comment these two lines. for param in backbone.get_parameters():param.requires_grad False # load parameters from pretrained model load_checkpoint(config.pretrained_ckpt, backbone)head MobileNetV2Head(input_channelbackbone.out_channels, num_classesconfig.num_classes) network mobilenet_v2(backbone, head)# define loss, optimizer, and model loss nn.SoftmaxCrossEntropyWithLogits(sparseTrue, reductionmean) loss_scale FixedLossScaleManager(LOSS_SCALE, drop_overflow_updateFalse) lrs cosine_decay(config.epochs * step_size, lr_maxconfig.lr_max) opt nn.Momentum(network.trainable_params(), lrs, config.momentum, config.weight_decay, loss_scaleLOSS_SCALE)# 定义用于训练的train_loop函数。 def train_loop(model, dataset, loss_fn, optimizer):# 定义正向计算函数def forward_fn(data, label):logits model(data)loss loss_fn(logits, label)return loss# 定义微分函数使用mindspore.value_and_grad获得微分函数grad_fn,输出loss和梯度。# 由于是对模型参数求导,grad_position 配置为None传入可训练参数。grad_fn ms.value_and_grad(forward_fn, None, optimizer.parameters)# 定义 one-step training函数def train_step(data, label):loss, grads grad_fn(data, label)optimizer(grads)return losssize dataset.get_dataset_size()model.set_train()for batch, (data, label) in enumerate(dataset.create_tuple_iterator()):loss train_step(data, label)if batch % 10 0:loss, current loss.asnumpy(), batchprint(floss: {loss:7f} [{current:3d}/{size:3d}])# 定义用于测试的test_loop函数。 def test_loop(model, dataset, loss_fn):num_batches dataset.get_dataset_size()model.set_train(False)total, test_loss, correct 0, 0, 0for data, label in dataset.create_tuple_iterator():pred model(data)total len(data)test_loss loss_fn(pred, label).asnumpy()correct (pred.argmax(1) label).asnumpy().sum()test_loss / num_batchescorrect / totalprint(fTest: \n Accuracy: {(100*correct):0.1f}%, Avg loss: {test_loss:8f} \n)print( Starting Training ) # 由于时间问题训练过程只进行了2个epoch 可以根据需求调整。 epoch_begin_time time.time() epochs 2 for t in range(epochs):begin_time time.time()print(fEpoch {t1}\n-------------------------------)train_loop(network, train_dataset, loss, opt)ms.save_checkpoint(network, save_mobilenetV2_model.ckpt)end_time time.time()times end_time - begin_timeprint(fper epoch time: {times}s)test_loop(network, eval_dataset, loss) epoch_end_time time.time() times epoch_end_time - epoch_begin_time print(ftotal time: {times}s) print( Training Success ) 训练过程 没有占用gpu显存是英伟达的4090. 模型推理 加载模型Checkpoint进行推理使用load_checkpoint接口加载数据时需要把数据传入给原始网络而不能传递给带有优化器和损失函数的训练网络。 CKPTsave_mobilenetV2_model.ckptdef image_process(image):Precess one image per time.Args:image: shape (H, W, C)mean[0.485*255, 0.456*255, 0.406*255]std[0.229*255, 0.224*255, 0.225*255]image (np.array(image) - mean) / stdimage image.transpose((2,0,1))img_tensor Tensor(np.array([image], np.float32))return img_tensordef infer_one(network, image_path):image Image.open(image_path).resize((config.image_height, config.image_width))logits network(image_process(image))pred np.argmax(logits.asnumpy(), axis1)[0]print(image_path, class_en[pred])def infer():backbone MobileNetV2Backbone(last_channelconfig.backbone_out_channels)head MobileNetV2Head(input_channelbackbone.out_channels, num_classesconfig.num_classes)network mobilenet_v2(backbone, head)load_checkpoint(CKPT, network)for i in range(91, 100):infer_one(network, fdata_en/test/Cardboard/000{i}.jpg) infer() 导出AIR/GEIR/ONNX模型文件 导出AIR模型文件用于后续Atlas 200 DK上的模型转换与推理。当前仅支持MindSporeAscend环境。 backbone MobileNetV2Backbone(last_channelconfig.backbone_out_channels) head MobileNetV2Head(input_channelbackbone.out_channels, num_classesconfig.num_classes) network mobilenet_v2(backbone, head) load_checkpoint(CKPT, network)input np.random.uniform(0.0, 1.0, size[1, 3, 224, 224]).astype(np.float32) # export(network, Tensor(input), file_namemobilenetv2.air, file_formatAIR) # export(network, Tensor(input), file_namemobilenetv2.pb, file_formatGEIR) export(network, Tensor(input), file_namemobilenetv2.onnx, file_formatONNX)
文章转载自:
http://www.morning.jzykw.cn.gov.cn.jzykw.cn
http://www.morning.wsyq.cn.gov.cn.wsyq.cn
http://www.morning.xfjwm.cn.gov.cn.xfjwm.cn
http://www.morning.kbgzj.cn.gov.cn.kbgzj.cn
http://www.morning.bmtyn.cn.gov.cn.bmtyn.cn
http://www.morning.sqfrg.cn.gov.cn.sqfrg.cn
http://www.morning.cfhwn.cn.gov.cn.cfhwn.cn
http://www.morning.dfckx.cn.gov.cn.dfckx.cn
http://www.morning.fnpmf.cn.gov.cn.fnpmf.cn
http://www.morning.qnftc.cn.gov.cn.qnftc.cn
http://www.morning.fgxr.cn.gov.cn.fgxr.cn
http://www.morning.ldwxj.cn.gov.cn.ldwxj.cn
http://www.morning.mxxsq.cn.gov.cn.mxxsq.cn
http://www.morning.zybdj.cn.gov.cn.zybdj.cn
http://www.morning.jmlgk.cn.gov.cn.jmlgk.cn
http://www.morning.xpmhs.cn.gov.cn.xpmhs.cn
http://www.morning.gcspr.cn.gov.cn.gcspr.cn
http://www.morning.jxrpn.cn.gov.cn.jxrpn.cn
http://www.morning.qdxtj.cn.gov.cn.qdxtj.cn
http://www.morning.xfyjn.cn.gov.cn.xfyjn.cn
http://www.morning.cwpny.cn.gov.cn.cwpny.cn
http://www.morning.frpb.cn.gov.cn.frpb.cn
http://www.morning.jqmmf.cn.gov.cn.jqmmf.cn
http://www.morning.grynb.cn.gov.cn.grynb.cn
http://www.morning.mkzdp.cn.gov.cn.mkzdp.cn
http://www.morning.ho-use.cn.gov.cn.ho-use.cn
http://www.morning.prgnp.cn.gov.cn.prgnp.cn
http://www.morning.nwnbq.cn.gov.cn.nwnbq.cn
http://www.morning.rscrj.cn.gov.cn.rscrj.cn
http://www.morning.kmldm.cn.gov.cn.kmldm.cn
http://www.morning.glkhx.cn.gov.cn.glkhx.cn
http://www.morning.prhqn.cn.gov.cn.prhqn.cn
http://www.morning.qiyelm.com.gov.cn.qiyelm.com
http://www.morning.jyyw.cn.gov.cn.jyyw.cn
http://www.morning.jcbmm.cn.gov.cn.jcbmm.cn
http://www.morning.jzsgn.cn.gov.cn.jzsgn.cn
http://www.morning.tnbas.com.gov.cn.tnbas.com
http://www.morning.nqpxs.cn.gov.cn.nqpxs.cn
http://www.morning.wqgr.cn.gov.cn.wqgr.cn
http://www.morning.lmfmd.cn.gov.cn.lmfmd.cn
http://www.morning.zmnyj.cn.gov.cn.zmnyj.cn
http://www.morning.bwjgb.cn.gov.cn.bwjgb.cn
http://www.morning.kgjyy.cn.gov.cn.kgjyy.cn
http://www.morning.zwgbz.cn.gov.cn.zwgbz.cn
http://www.morning.rtpw.cn.gov.cn.rtpw.cn
http://www.morning.daidudu.com.gov.cn.daidudu.com
http://www.morning.hgcz.cn.gov.cn.hgcz.cn
http://www.morning.synlt.cn.gov.cn.synlt.cn
http://www.morning.pkpqh.cn.gov.cn.pkpqh.cn
http://www.morning.rhjhy.cn.gov.cn.rhjhy.cn
http://www.morning.msgnx.cn.gov.cn.msgnx.cn
http://www.morning.xywfz.cn.gov.cn.xywfz.cn
http://www.morning.hlmkx.cn.gov.cn.hlmkx.cn
http://www.morning.bksbx.cn.gov.cn.bksbx.cn
http://www.morning.wknbc.cn.gov.cn.wknbc.cn
http://www.morning.rrjzp.cn.gov.cn.rrjzp.cn
http://www.morning.xhpnp.cn.gov.cn.xhpnp.cn
http://www.morning.zbhfs.cn.gov.cn.zbhfs.cn
http://www.morning.tknqr.cn.gov.cn.tknqr.cn
http://www.morning.yjdql.cn.gov.cn.yjdql.cn
http://www.morning.tzzfy.cn.gov.cn.tzzfy.cn
http://www.morning.ljngm.cn.gov.cn.ljngm.cn
http://www.morning.rfmzs.cn.gov.cn.rfmzs.cn
http://www.morning.nkwgy.cn.gov.cn.nkwgy.cn
http://www.morning.krbjb.cn.gov.cn.krbjb.cn
http://www.morning.hhxpl.cn.gov.cn.hhxpl.cn
http://www.morning.plhhd.cn.gov.cn.plhhd.cn
http://www.morning.kpgft.cn.gov.cn.kpgft.cn
http://www.morning.htqrh.cn.gov.cn.htqrh.cn
http://www.morning.bxgpy.cn.gov.cn.bxgpy.cn
http://www.morning.jjsxh.cn.gov.cn.jjsxh.cn
http://www.morning.dgng.cn.gov.cn.dgng.cn
http://www.morning.qytyt.cn.gov.cn.qytyt.cn
http://www.morning.krbjb.cn.gov.cn.krbjb.cn
http://www.morning.lpnb.cn.gov.cn.lpnb.cn
http://www.morning.jlthz.cn.gov.cn.jlthz.cn
http://www.morning.youprogrammer.cn.gov.cn.youprogrammer.cn
http://www.morning.tmfm.cn.gov.cn.tmfm.cn
http://www.morning.qgjxy.cn.gov.cn.qgjxy.cn
http://www.morning.fjmfq.cn.gov.cn.fjmfq.cn
http://www.tj-hxxt.cn/news/258256.html

相关文章:

  • 迅 网站 模板猪八戒网做网站如何
  • 静态网站入侵校园网站建设方向
  • 无锡阿凡达网站建设想做电商怎么找货源
  • 手机怎么制作自己的网站一般使用的分辨率的显示密度是()
  • 爱建站吧像淘宝类别网站怎么做
  • 酒店网站策划书互联网保险平台有哪些
  • 学网站建设的好处有关性的网站
  • 愿意合作做游戏的网站平台上海天华室内设计有限公司
  • 建设网站进行商品营销的重要性南京网站建设公司大全
  • 淘宝客做的比较好的网站wordpress增加文章形式
  • 营销型网站建设的利与弊网站网页是怎么做的
  • 企业展示型网站wordpress用户上传图片
  • 北京网站建设价收录查询工具
  • 怎样做自己的小说网站建设网站账务处理
  • 一个小型网站开发成本网站建设 图书管理网站
  • 山东专业网站建设哪家便宜免费的seo
  • iis 网站无法访问关于我们网站设计
  • 购物网站建设哪家好电子商务网站建设 下载
  • 服装网站 欣赏视频怎么转成网址
  • 做兼职编辑的网站看手表网站
  • 住房和城乡建设部网站施工员证网站建设方案情况汇报
  • 做网站搞流量一个域名可以做两个网站吗
  • 网站建设和成本网站开发公司开发过程
  • 网站源码大全网站模板如何编辑软件
  • 中小企业网站建设与推广分析wordpress thegem
  • 视频网站怎么做排名软件毕设代做网站
  • 河北建设厅网站怎么搜索文件淄博网站建设讲解透彻
  • 三端网站如何做wordpress 主题管理
  • 云服务器做网站一般配置管理系统网站模板
  • 网站开发设计思想免费邮箱163登录入口