mindspore-2代码注释


import mindspore
from mindspore import nn
from mindspore import ops
from mindspore.dataset import vision, transforms
from mindspore.dataset import MnistDataset

# Download data from open datasets
from download import download




url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/" \
      "notebook/datasets/MNIST_Data.zip"
//加载数据集地址
path = download(url, "./", kind="zip", replace=True)
//添加路径







def datapipe(path, batch_size): 
//定义数据预处理的函数
    image_transforms = [
        vision.Rescale(1.0 / 255.0, 0),
        vision.Normalize(mean=(0.1307,), std=(0.3081,)),
        vision.HWC2CHW()
    ]
//image预处理的函数
    label_transform = transforms.TypeCast(mindspore.int32)
    
    dataset = MnistDataset(path)
//加载
    dataset = dataset.map(image_transforms, 'image')
    dataset = dataset.map(label_transform, 'label')
//分别预处理
    dataset = dataset.batch(batch_size)
//分批
    return dataset

train_dataset = datapipe('MNIST_Data/train', 64)
test_dataset = datapipe('MNIST_Data/test', 64)







class Network(nn.Cell):
//构造函数
    def __init__(self):
//继承
        super().__init__()
//实例化nn.Flatten层,展开数据集
        self.flatten = nn.Flatten()
//构造一个神经网络模型
        self.dense_relu_sequential = nn.SequentialCell(
            nn.Dense(28*28, 512),
            nn.ReLU(),
            nn.Dense(512, 512),
            nn.ReLU(),
            nn.Dense(512, 10)
        )
//运作
    def construct(self, x):
        x = self.flatten(x)
        logits = self.dense_relu_sequential(x)
        return logits
        
        
//创建一个类
model = Network()

//超参设置
epochs = 10
batch_size = 32
learning_rate = 1e-2

//定义运行函数
def train_loop(model, dataset, loss_fn, optimizer):





//定义向前计算的函数
    def forward_fn(data, label):
//导入数据
        logits = model(data)
//连接损失函数
        loss = loss_fn(logits, label)
        return loss, logits





//获得梯度(待求导函数,grad_position ,weight)

    grad_fn = ops.value_and_grad(forward_fn, None, optimizer.parameters, has_aux=True)

//Define function of one-step training






//定义每一步操作的函数
    def train_step(data, label):
    
//例如 out1, out2 = fn(*args) ,梯度函数将返回 ((out1, out2), gradient) 形式的结果, 若 has_aux 为True,那么 out2 不参与求导
        (loss, _), grads = grad_fn(data, label)
        
//如果两个操作A和B没有顺序上的依赖性,而A必须在B之前执行,我们建议使用Depend来指定它们的执行顺序。
        loss = ops.depend(loss, optimizer(grads))
        return loss

    size = dataset.get_dataset_size()
    model.set_train()
    
    
    
    
    
    
   
    for batch, (data, label) in enumerate(dataset.create_tuple_iterator()):
        loss = train_step(data, label)

        if batch % 100 == 0:
            loss, current = loss.asnumpy(), batch
            print(f"loss: {loss:>7f}  [{current:>3d}/{size:>3d}]")


//测试函数
def test_loop(model, dataset, loss_fn):

    num_batches = dataset.get_dataset_size()
    model.set_train(False)
    total, test_loss, correct = 0, 0, 0
    for 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_batches
    correct /= total
    print(f"Test: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")


//主函数
loss_fn = nn.CrossEntropyLoss()
optimizer = nn.SGD(model.trainable_params(), learning_rate=learning_rate)

epochs = 3
for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train_loop(model, train_dataset, loss_fn, optimizer)
    test_loop(model, test_dataset, loss_fn)
print("Done!")

你可能感兴趣的:(学习记录,笔记,深度学习,python)