<jupyter_start><jupyter_text>自定义训练[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_source.png)](https://gitee.com/mindspore/docs/blob/master/tutorials/source_zh_cn/intermediate/custom/train.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_notebook.png)](https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/master/tutorials/zh_cn/mindspore_train.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_modelarts.png)](https://authoring-modelarts-cnnorth4.huaweicloud.com/console/lab?share-url-b64=aHR0cHM6Ly9taW5kc3BvcmUtd2Vic2l0ZS5vYnMuY24tbm9ydGgtNC5teWh1YXdlaWNsb3VkLmNvbS9ub3RlYm9vay9tYXN0ZXIvdHV0b3JpYWxzL3poX2NuL21pbmRzcG9yZV90cmFpbi5pcHluYg==&imageid=65f636a0-56cf-49df-b941-7d2a07ba8c8c)MindSpore提供了`model.train`接口来进行模型训练。使用方式可以参考[初级教程-初学入门](https://www.mindspore.cn/tutorials/zh-CN/master/quick_start.html)。此外，还可以使用`TrainOneStepCell`，该接口当前支持GPU、Ascend环境。作为高阶接口，`model.train`封装了`TrainOneStepCell`，可以直接利用设定好的网络、损失函数与优化器进行训练。用户也可以选择使用`TrainOneStepCell`实现更加灵活的训练，例如控制训练数据集、实现多输入多输出网络、或自定义训练过程。 TrainOneStepCell说明`TrainOneStepCell`中包含三种入参：- network (Cell)：参与训练的网络，当前仅接受单输出网络。- optimizer (Cell)：所使用的优化器。- sens (Number)：反向传播的缩放比例。下面使用`TrainOneStepCell`替换`model.train`，实现简单的线性网络训练过程。 TrainOneStepCell使用示例 创建模型并生成数据> 本小节详细解释说明可参考[初级教程-初学入门](https://www.mindspore.cn/tutorials/zh-CN/master/quick_start.html)。定义网络LinearNet，内部有两层全连接层组成的网络， 包含5个入参和1个出参的神经网络。<jupyter_code>import numpy as np

from mindspore import Tensor
import mindspore.nn as nn
from mindspore.nn import Cell, Dense
import mindspore.ops as ops
import mindspore.dataset as ds
from mindspore import ParameterTuple

class LinearNet(Cell):
    def __init__(self):
        super().__init__()
        self.relu = nn.ReLU()
        self.dense1 = Dense(5, 32)
        self.dense2 = Dense(32, 1)

    def construct(self, x):
        x = self.dense1(x)
        x = self.relu(x)
        x = self.dense2(x)
        return x<jupyter_output><empty_output><jupyter_text>产生输入数据。<jupyter_code>np.random.seed(4)

class DatasetGenerator:
    def __init__(self):
        self.data = np.random.randn(5, 5).astype(np.float32)
        self.label = np.random.randn(5, 1).astype(np.int32)

    def __getitem__(self, index):
        return self.data[index], self.label[index]

    def __len__(self):
        return len(self.data)<jupyter_output><empty_output><jupyter_text>数据处理。<jupyter_code># 对输入数据进行处理
dataset_generator = DatasetGenerator()
dataset = ds.GeneratorDataset(dataset_generator, ["data", "label"], shuffle=True)
dataset = dataset.batch(32)

# 实例化网络
net = LinearNet()<jupyter_output><empty_output><jupyter_text>定义TrainOneStepCell在`TrainOneStepCell`中，可以实现对训练过程的个性化设定。<jupyter_code>class TrainOneStepCell(nn.Cell):
    def __init__(self, network, optimizer, sens=1.0):
        """参数初始化"""
        super(TrainOneStepCell, self).__init__(auto_prefix=False)
        self.network = network
        # 使用tuple包装weight
        self.weights = ParameterTuple(network.trainable_params())
        self.optimizer = optimizer
        # 定义梯度函数
        self.grad = ops.GradOperation(get_by_list=True, sens_param=True)
        self.sens = sens

    def construct(self, data, label):
        """构建训练过程"""
        weights = self.weights
        loss = self.network(data, label)
        # 为反向传播设定系数
        sens = ops.Fill()(ops.DType()(loss), ops.Shape()(loss), self.sens)
        grads = self.grad(self.network, weights)(data, label, sens)
        return loss, self.optimizer(grads)<jupyter_output><empty_output><jupyter_text>网络训练在使用`TrainOneStepCell`时，需要利用`WithLossCell`接口引入损失函数，共同完成训练过程。下面利用之前设定好的参数训练LeNet网络，并获取loss值。<jupyter_code># 设定损失函数
crit = nn.MSELoss()
# 设定优化器
opt = nn.Adam(params=net.trainable_params())
# 引入损失函数
net_with_criterion = nn.WithLossCell(net, crit)
# 自定义网络训练
train_net = TrainOneStepCell(net_with_criterion, opt)

# 获取训练过程数据

for i in range(300):
    for d in dataset.create_dict_iterator():
        train_net(d["data"], d["label"])
        print(net_with_criterion(d["data"], d["label"]))<jupyter_output>0.7998974
0.79927444
0.7986423
0.7979911
0.79732
... ...
0.042837422
0.041227795
0.039638687
... ...
9.276913e-06
8.4145695e-06
7.625091e-06
6.904066e-06
6.2513377e-06
{'fraction_non_alphanumeric': 0.13467455621301774, 'fraction_numerical': 0.046627218934911244, 'mean_word_length': 5.160349854227405, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 21, 'https://': 8, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '503086', 'license': 'Apache-2.0', 'n_tokens_mistral': 2031, 'n_tokens_neox': 2018, 'n_words': 181, 'path': 'tutorials/source_zh_cn/intermediate/custom/train.ipynb', 'repo_name': 'bwcsswcx/docs', 'size': '4225'}