import time
import mindspore
from mindspore import nn
from mindspore.dataset import vision, transforms
from mindspore.dataset import MnistDataset
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)
train_dataset = MnistDataset('MNIST_Data/train')
test_dataset = MnistDataset('MNIST_Data/test')
print(train_dataset.get_col_names())
def datapipe(dataset, batch_size):
image_transforms = [
vision.Rescale(1.0 / 255.0, 0),
vision.Normalize(mean=(0.1307,), std=(0.3081,)),
vision.HWC2CHW()
]
label_transform = transforms.TypeCast(mindspore.int32)
dataset = dataset.map(image_transforms, 'image')
dataset = dataset.map(label_transform, 'label')
dataset = dataset.batch(batch_size)
return dataset
# Map vision transforms and batch dataset
train_dataset = datapipe(train_dataset, 64)
test_dataset = datapipe(test_dataset, 64)
for image, label in test_dataset.create_tuple_iterator():
print(f"Shape of image [N, C, H, W]: {image.shape} {image.dtype}")
print(f"Shape of label: {label.shape} {label.dtype}")
break
for data in test_dataset.create_dict_iterator():
print(f"Shape of image [N, C, H, W]: {data['image'].shape} {data['image'].dtype}")
print(f"Shape of label: {data['label'].shape} {data['label'].dtype}")
break
# Define model
class Network(nn.Cell):
def __init__(self):
super().__init__()
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()
print(model)
# Instantiate loss function and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = nn.SGD(model.trainable_params(), 1e-2)
# 1. Define forward function
def forward_fn(data, label):
logits = model(data)
loss = loss_fn(logits, label)
return loss, logits
# 2. Get gradient function
grad_fn = mindspore.value_and_grad(forward_fn, None, optimizer.parameters, has_aux=True)
# 3. Define function of one-step training
def train_step(data, label):
(loss, _), grads = grad_fn(data, label)
optimizer(grads)
return loss
def train(model, dataset):
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(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")
epochs = 10
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train(model, train_dataset)
test(model, test_dataset, loss_fn)
print("Done!")
# Save checkpoint
mindspore.save_checkpoint(model, "model.ckpt")
print("Saved Model to model.ckpt")
# Instantiate a random initialized model
model = Network()
# Load checkpoint and load parameter to model
param_dict = mindspore.load_checkpoint("model.ckpt")
param_not_load, _ = mindspore.load_param_into_net(model, param_dict)
print(param_not_load)
model.set_train(False)
for data, label in test_dataset:
pred = model(data)
predicted = pred.argmax(1)
print(f'Predicted: "{predicted[:10]}", Actual: "{label[:10]}"')
break
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),'skywp')
Downloading data from https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/MNIST_Data.zip (10.3 MB) file_sizes: 100%|███████████████████████████| 10.8M/10.8M [00:00<00:00, 161MB/s] Extracting zip file... Successfully downloaded / unzipped to ./ ['image', 'label'] Shape of image [N, C, H, W]: (64, 1, 28, 28) Float32 Shape of label: (64,) Int32 Shape of image [N, C, H, W]: (64, 1, 28, 28) Float32 Shape of label: (64,) Int32 Network< (flatten): Flatten<> (dense_relu_sequential): SequentialCell< (0): Dense<input_channels=784, output_channels=512, has_bias=True> (1): ReLU<> (2): Dense<input_channels=512, output_channels=512, has_bias=True> (3): ReLU<> (4): Dense<input_channels=512, output_channels=10, has_bias=True> > > Epoch 1 ------------------------------- loss: 2.279789 [ 0/938] loss: 1.712688 [100/938] loss: 0.872912 [200/938] loss: 0.499927 [300/938] loss: 0.528868 [400/938] loss: 0.501849 [500/938] loss: 0.398775 [600/938] loss: 0.447360 [700/938] loss: 0.286581 [800/938] loss: 0.332299 [900/938] Test: Accuracy: 90.8%, Avg loss: 0.323961 Epoch 2 ------------------------------- loss: 0.233778 [ 0/938] loss: 0.255780 [100/938] loss: 0.150093 [200/938] loss: 0.279230 [300/938] loss: 0.365830 [400/938] loss: 0.210970 [500/938] loss: 0.168809 [600/938] loss: 0.235510 [700/938] loss: 0.294178 [800/938] loss: 0.176371 [900/938] Test: Accuracy: 92.9%, Avg loss: 0.247941 Epoch 3 ------------------------------- loss: 0.275178 [ 0/938] loss: 0.174475 [100/938] loss: 0.232013 [200/938] loss: 0.145759 [300/938] loss: 0.285019 [400/938] loss: 0.306831 [500/938] loss: 0.347860 [600/938] loss: 0.131523 [700/938] loss: 0.173969 [800/938] loss: 0.240118 [900/938] Test: Accuracy: 94.0%, Avg loss: 0.209006 Epoch 4 ------------------------------- loss: 0.270546 [ 0/938] loss: 0.136092 [100/938] loss: 0.149328 [200/938] loss: 0.177321 [300/938] loss: 0.129258 [400/938] loss: 0.248159 [500/938] loss: 0.129819 [600/938] loss: 0.149704 [700/938] loss: 0.122814 [800/938] loss: 0.192139 [900/938] Test: Accuracy: 94.6%, Avg loss: 0.182635 Epoch 5 ------------------------------- loss: 0.286487 [ 0/938] loss: 0.242977 [100/938] loss: 0.093043 [200/938] loss: 0.092097 [300/938] loss: 0.199909 [400/938] loss: 0.107868 [500/938] loss: 0.186808 [600/938] loss: 0.175348 [700/938] loss: 0.135079 [800/938] loss: 0.134168 [900/938] Test: Accuracy: 95.3%, Avg loss: 0.160946 Epoch 6 ------------------------------- loss: 0.140025 [ 0/938] loss: 0.091131 [100/938] loss: 0.199530 [200/938] loss: 0.117356 [300/938] loss: 0.171679 [400/938] loss: 0.186101 [500/938] loss: 0.119611 [600/938] loss: 0.143975 [700/938] loss: 0.273533 [800/938] loss: 0.036094 [900/938] Test: Accuracy: 95.8%, Avg loss: 0.143220 Epoch 7 ------------------------------- loss: 0.239285 [ 0/938] loss: 0.075213 [100/938] loss: 0.026216 [200/938] loss: 0.115669 [300/938] loss: 0.132865 [400/938] loss: 0.114236 [500/938] loss: 0.139998 [600/938] loss: 0.204587 [700/938] loss: 0.098077 [800/938] loss: 0.157028 [900/938] Test: Accuracy: 96.2%, Avg loss: 0.129179 Epoch 8 ------------------------------- loss: 0.108100 [ 0/938] loss: 0.080826 [100/938] loss: 0.139983 [200/938] loss: 0.159044 [300/938] loss: 0.279953 [400/938] loss: 0.056621 [500/938] loss: 0.137742 [600/938] loss: 0.133608 [700/938] loss: 0.111276 [800/938] loss: 0.090705 [900/938] Test: Accuracy: 96.5%, Avg loss: 0.118926 Epoch 9 ------------------------------- loss: 0.115459 [ 0/938] loss: 0.094403 [100/938] loss: 0.131634 [200/938] loss: 0.071918 [300/938] loss: 0.215124 [400/938] loss: 0.090745 [500/938] loss: 0.101857 [600/938] loss: 0.257950 [700/938] loss: 0.084232 [800/938] loss: 0.174996 [900/938] Test: Accuracy: 96.8%, Avg loss: 0.108092 Epoch 10 ------------------------------- loss: 0.055152 [ 0/938] loss: 0.023567 [100/938] loss: 0.121823 [200/938] loss: 0.061770 [300/938] loss: 0.106167 [400/938] loss: 0.106240 [500/938] loss: 0.133518 [600/938] loss: 0.060433 [700/938] loss: 0.029802 [800/938] loss: 0.066283 [900/938] Test: Accuracy: 96.8%, Avg loss: 0.105468 Done! Saved Model to model.ckpt [] Predicted: "[9 7 0 1 3 7 0 5 8 2]", Actual: "[9 2 0 1 3 7 0 5 8 2]" 2024-06-26 13:53:48 skywp
ps:怎么说呢,今天的学习真的是一头雾水的赶脚,勉强把代码都跑了下,嗯,任重而道远。