深度学习(DL, Deep Learning)是机器学习(ML, Machine Learning)领域中一个新的研究方向,它被引入机器学习使其更接近于最初的目标——人工智能(AI, Artificial Intelligence)。

本实验包括:

本地部署mindspore

花卉识别实验

一、本地部署mindspore

首先,推荐先安装miniconda,这能帮助管理各种生成的虚拟空间,也就是mindspore这种。

官方下载地址: https://docs.conda.io/en/latest/miniconda.html

清华镜像源地址: https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/

Miniconda可在线安装不同 的Python版本,无需刻意下 载特定版本,但需要下载64 位。

注意:选择miniconda3

安装地址随意,哪个盘都可以,尽量别在C盘

注意勾选环境变量,这样可以直接在命令行中启动Miniconda

按下win+r,输入cmd,打开命令行。或者手动打开“终端”,如下图

输入     conda activate         ,进入base环境

然后输入:

conda create –n MindSpore python==3.7.5

过程中需要再输入y,进行确认。

输入:

activate MindSpore

进入mindspore环境。

安装mindspore:

pip install https://ms-release.obs.cn-north-4.myhuaweicloud.com/2.0.0/MindSpore/cpu/x86_64/mindspore-2.0.0-cp37-cp37m-win_amd64.whl --trusted-host ms-release.obs.cn-north-4.myhuaweicloud.com -i https://pypi.tuna.tsinghua.edu.cn/simple

结束后,验证安装成功:

在本窗口,保存mindspore环境,输入python,回车,然后输入

import mindspore

等待一会输入:

mindspore.run_check()

如果出现以下

则安装成功。

然后我们打开pycharm,如果没有,建议自行安装,这个教程还是很全的,推荐直接最新版。

官网链接:https://www.jetbrains.com/

新建项目,注意:解释器需要进行修改

我的mindspore没法按conda类型导入,也不明白为啥。

这里选择python

在下面路径中点击最右边的文件夹标志,如图:

进入你安装的miniconda3的位置,然后安装图中路径,找到mindspore里面的python.exe

选确定就ok了。

二、花卉识别实验

先看代码:

#easydict模块用于以属性的方式访问字典的值
import wget
from easydict import EasyDict as edict
#glob模块主要用于查找符合特定规则的文件路径名,类似使用windows下的文件搜索
import glob
#os模块主要用于处理文件和目录
import os

import numpy as np
import matplotlib.pyplot as plt

import mindspore
#导入mindspore框架数据集
import mindspore.dataset as ds
#vision.c_transforms模块是处理图像增强的高性能模块,用于数据增强图像数据改进训练模型。
import mindspore.dataset.vision as CV #----------------------
#c_transforms模块提供常用操作,包括OneHotOp和TypeCast
import mindspore.dataset.transforms as C #------------------

import urllib.request
import zipfile
import os

from mindspore.common import dtype as mstype
from mindspore import context
#导入模块用于初始化截断正态分布
from mindspore.common.initializer import TruncatedNormal
from mindspore import nn
from mindspore.train import Model
from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
from mindspore.train.serialization import load_checkpoint, load_param_into_net
from mindspore import Tensor
# 设置MindSpore的执行模式和设备,此处我们使用的是云平台环境ModelArts上的昇腾算力(“Ascend”),若在本地执行,device_target参数设置为“CPU”
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
cfg = edict({#-------------------------------------

    'data_path': 'flower_photos',
    'data_size': 3670,
    'image_width': 64,  # 图片宽度
    'image_height': 64,  # 图片高度
    'batch_size': 64,
    'channel': 3,  # 图片通道数
    'num_class': 5,  # 分类类别
    'weight_decay': 0.01,
    'lr': 0.0005,  # 学习率
    'dropout_ratio': 0.5,
    'epoch_size': 40,  # 训练次数
    'sigma': 0.01,

    'save_checkpoint_steps': 10,  # 多少步保存一次模型
    'keep_checkpoint_max': 3,  # 最多保存多少个模型
    'output_directory': './',  # 保存模型路径
    'output_prefix': "checkpoint_classification"  # 保存模型文件名字

})

"""
环境信息检查模块
在训练开始前运行,用于确认MindSpore环境及版本。
"""
import sys
import mindspore as ms

print("=" * 50)
print("MindSpore 环境检查")
print("=" * 50)

# 1. 输出Python基本信息
print(f"Python 版本: {sys.version}")
print(f"Python 可执行文件路径: {sys.executable}")

# 2. 输出MindSpore核心信息[citation:2][citation:6][citation:7]
print(f"MindSpore 版本: {ms.__version__}")  # 例如: 2.0.0


def download_and_extract_dataset():
    # 数据集URL
    url = 'https://ascend-professional-construction-dataset.obs.myhuaweicloud.com/deep-learning/flower_photos.zip'
    zip_path = 'flower_photos.zip'

    # 下载数据集(如果不存在)
    if not os.path.exists(zip_path):
        print("正在下载数据集...")
        urllib.request.urlretrieve(url, zip_path)
        print("下载完成!")

    # 解压数据集(如果不存在)
    if not os.path.exists('flower_photos'):
        print("正在解压数据集...")
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall('.')
        print("解压完成!")
    else:
        print("数据集已存在,跳过解压。")


# 调用函数
download_and_extract_dataset()


#从目录中读取图像的源数据集。
de_dataset = ds.ImageFolderDataset(cfg.data_path,
                                   class_indexing={'daisy':0,'dandelion':1,'roses':2,'sunflowers':3,'tulips':4})
#解码前将输入图像裁剪成任意大小和宽高比。

transform_img = CV.RandomCropDecodeResize([cfg.image_width,cfg.image_height], scale=(0.08, 1.0), ratio=(0.75, 1.333))  #改变尺寸
#转换输入图像;形状(H, W, C)为形状(C, H, W)。
hwc2chw_op = CV.HWC2CHW()
#转换为给定MindSpore数据类型的Tensor操作。
type_cast_op = C.TypeCast(mstype.float32)
#将操作中的每个操作应用到此数据集。
de_dataset = de_dataset.map(input_columns="image", num_parallel_workers=8, operations=transform_img)
de_dataset = de_dataset.map(input_columns="image", operations=hwc2chw_op, num_parallel_workers=8)
de_dataset = de_dataset.map(input_columns="image", operations=type_cast_op, num_parallel_workers=8)
de_dataset = de_dataset.shuffle(buffer_size=cfg.data_size)
#划分训练集测试集
(de_train,de_test)=de_dataset.split([0.8,0.2])
#设置每个批处理的行数
#drop_remainder确定是否删除最后一个可能不完整的批(default=False)。
#如果为True,并且如果可用于生成最后一个批的batch_size行小于batch_size行,则这些行将被删除,并且不会传播到子节点。
de_train=de_train.batch(cfg.batch_size, drop_remainder=True)
#重复此数据集计数次数。
de_test=de_test.batch(cfg.batch_size, drop_remainder=True)

print(f'类别数量:{cfg.num_class} (daisy, dandelion, roses, sunflowers, tulips)')
print(f'批处理大小:{cfg.batch_size}')
print(f'图像尺寸:{cfg.image_width}x{cfg.image_height}')
print(f'训练集批次数量:{de_train.get_dataset_size()}')
print(f'测试集批次数量:{de_test.get_dataset_size()}')

print('训练数据集数量:',de_train.get_dataset_size()*cfg.batch_size)#get_dataset_size()获取批处理的大小。
print('测试数据集数量:',de_test.get_dataset_size()*cfg.batch_size)

#__next__方法处理后,获取一个batch的数据,数据格式为NCHW,第一维度为batch的数量。----------------------------
# 简单安全的方式
iterator = de_dataset.create_dict_iterator(output_numpy=True)
data_next = next(iterator, None)  # 第二个参数是默认值

print('通道数/图像长/宽:', data_next['image'].shape)
print('一张图像的标签样式:', data_next['label'])  # 一共5类,用0-4的数字表达类别。
print(data_next['image'][0,...].shape)

plt.figure()
plt.imshow(data_next['image'][1,...])
plt.colorbar()
plt.grid(False)
plt.show()

# 定义CNN图像识别网络
class Identification_Net(nn.Cell):
    def __init__(self, num_class=5,channel=3,dropout_ratio=0.5,trun_sigma=0.01,image_size=64):  # 一共分五类,图片通道数是3
        super(Identification_Net, self).__init__()
        self.num_class = num_class
        self.channel = channel
        self.dropout_ratio = dropout_ratio
        #设置卷积层
        self.conv1 = nn.Conv2d(self.channel, 32,
                               kernel_size=5, stride=1, padding=0,
                               has_bias=True, pad_mode="same",
                               weight_init=TruncatedNormal(sigma=trun_sigma),bias_init='zeros')
        #设置ReLU激活函数
        self.relu = nn.ReLU()
        #设置最大池化层
        self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2,pad_mode="valid")
        self.conv2 = nn.Conv2d(32, 64,
                               kernel_size=5, stride=1, padding=0,
                               has_bias=True, pad_mode="same",
                               weight_init=TruncatedNormal(sigma=trun_sigma),bias_init='zeros')
        self.conv3 = nn.Conv2d(64, 128,
                               kernel_size=3, stride=1, padding=0,
                               has_bias=True, pad_mode="same",
                               weight_init=TruncatedNormal(sigma=trun_sigma),bias_init='zeros')
        self.conv4 = nn.Conv2d(128, 128,
                               kernel_size=3, stride=1, padding=0,
                               has_bias=True, pad_mode="same",
                               weight_init=TruncatedNormal(sigma=trun_sigma), bias_init='zeros')
        if image_size == 64:
            fc1_input_dim = 4 * 4 * 128  # 2048
        elif image_size == 100:
            fc1_input_dim = 6 * 6 * 128  # 4608
        else:
            # 通用计算:图片尺寸/(2^4)^2 * 128
            final_size = image_size // (2 ** 4)  # 池化4次
            fc1_input_dim = final_size * final_size * 128

        print(f"图片尺寸: {image_size}×{image_size}, fc1输入维度: {fc1_input_dim}")

        self.flatten = nn.Flatten()
        self.fc1 = nn.Dense(fc1_input_dim, 1024,weight_init =TruncatedNormal(sigma=trun_sigma),bias_init = 0.1)
        self.dropout = nn.Dropout(p=self.dropout_ratio)#----------------------------注意p的含义变化
        self.fc2 = nn.Dense(1024, 512, weight_init=TruncatedNormal(sigma=trun_sigma), bias_init=0.1)
        self.fc3 = nn.Dense(512, self.num_class, weight_init=TruncatedNormal(sigma=trun_sigma), bias_init=0.1)
    #构建模型
    def construct(self, x):
        x = self.conv1(x)
        x = self.relu(x)
        x = self.max_pool2d(x)
        x = self.conv2(x)
        x = self.relu(x)
        x = self.max_pool2d(x)
        x = self.conv3(x)
        x = self.relu(x)
        x = self.max_pool2d(x)
        x = self.conv4(x)
        x = self.relu(x)
        x = self.max_pool2d(x)
        x = self.flatten(x)
        x = self.fc1(x)
        x = self.relu(x)
        x = self.dropout(x)
        x = self.fc2(x)
        x = self.relu(x)
        x = self.dropout(x)
        x = self.fc3(x)
        return x
#实例化网络
net=Identification_Net(num_class=cfg.num_class, channel=cfg.channel, dropout_ratio=cfg.dropout_ratio)
#计算softmax交叉熵,以此作为损失函数
net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
#获取网络中需要更新的参数
fc_weight_params = list(filter(lambda x: 'fc' in x.name and 'weight' in x.name, net.trainable_params()))
other_params=list(filter(lambda x: 'fc' not in x.name or 'weight' not in x.name, net.trainable_params()))
group_params = [{'params': fc_weight_params, 'weight_decay': cfg.weight_decay},
                {'params': other_params},
                {'order_params': net.trainable_params()}]
#设置Adam优化器,将前一步设定的需要更新的参数传入
net_opt = nn.Adam(group_params, learning_rate=cfg.lr, weight_decay=0.0)
#net_opt = nn.Adam(params=net.trainable_params(), learning_rate=cfg.lr, weight_decay=0.1)
#编译网络、损失函数和优化器
model = Model(net, loss_fn=net_loss, optimizer=net_opt, metrics={"acc"})
#设定callback监控指标
loss_cb = LossMonitor(per_print_times=de_train.get_dataset_size()*10)
config_ck = CheckpointConfig(save_checkpoint_steps=cfg.save_checkpoint_steps,
                             keep_checkpoint_max=cfg.keep_checkpoint_max)
ckpoint_cb = ModelCheckpoint(prefix=cfg.output_prefix, directory=cfg.output_directory, config=config_ck)
print("============== Starting Training ==============")
#开始训练,训练时将callback监控指标设定好
model.train(cfg.epoch_size, de_train, callbacks=[loss_cb, ckpoint_cb], dataset_sink_mode=True)

# 使用测试集评估模型,打印总体准确率
metric = model.eval(de_test)
print(metric)



#加载模型
import os
#获取路径
CKPT = os.path.join(cfg.output_directory,cfg.output_prefix+'-'+str(cfg.epoch_size)+'_'+str(de_train.get_dataset_size())+'.ckpt')
#实例化网络
net = Identification_Net(num_class=cfg.num_class, channel=cfg.channel, dropout_ratio=cfg.dropout_ratio)
#将参数加载进网络
load_checkpoint(CKPT, net=net)
#编译整个模型
model = Model(net)
# 预测
class_names = {0:'daisy',1:'dandelion',2:'roses',3:'sunflowers',4:'tulips'}
#获取测试集的batch
test_ = de_test.create_dict_iterator().__next__()
#转换为tensor
test = Tensor(test_['image'], mindspore.float32)
#预测
predictions = model.predict(test)
predictions = predictions.asnumpy()
true_label = test_['label'].asnumpy()

#显示预测结果
for i in range(9):
    p_np = predictions[i, :]
    pre_label = np.argmax(p_np)
    print('第' + str(i) + '个sample预测结果:', class_names[pre_label], '真实结果:',class_names[true_label[i]])

直接复制就可以使用,然后我来讲解一下里面的一些内容:

1、你写入代码后可能有很多报错,很正常,这是缺少前置文件导致的,按照pycharm提示,一个个下载就行,这个很快解决

2、超参数

data_size,代表下载下来的flower_photos里的图片总数,这两需要保持一致,修改一个记得改另一个。减少这个可以小幅度提高训练速度

说到这里,flower_photos里其实有很多存粹垃圾图片,是可以删的,删了能有效提高精确度。

图片宽度和图片高度,这个原本是100*100的,但训练速度太慢,差不多是现在的4倍时间,就改成了64*64,这个的数值其实较大程度影响训练速度,同时一定程度影响精确度,数值大点,精确度会高点,但不一定。最好别再缩小了。

batch_size,一组训练的图片数量,这个调高可以加快训练速度,但是会拉高CPU占用,不好的电脑不建议提高,如果这个数值下也很卡,可以降低到32,再低不推荐,会拉长训练时间。

epoch_size,训练次数,这个大幅度影响训练速度和精确度,如果你的时间充足,建议数值在80-150之间。

关于训练时间:

按照我的代码的话,你不改超参数,10分钟左右就跑完了,准确率应该在0.7左右。

如果训练次数在80-150的话,20分钟左右,准确率在0.85左右。

然后吧,这个实验代码其实算是过时品了,你可以发现很多waring,都说import语句没被使用,这些建议别删,但其实删了影响应该是没有的,理论上这些都是因为版本升级后迭代掉了。

别的就没啥了,还有不懂的,这边建议找AI,虽然有点搞,但确实是这样的。

Logo

昇腾计算产业是基于昇腾系列(HUAWEI Ascend)处理器和基础软件构建的全栈 AI计算基础设施、行业应用及服务,https://devpress.csdn.net/organization/setting/general/146749包括昇腾系列处理器、系列硬件、CANN、AI计算框架、应用使能、开发工具链、管理运维工具、行业应用及服务等全产业链

更多推荐