基于MindSpore,使用LeNet实现手写体数字识别,python代码,网络的通道数不是6,卷卷积核大小大于5*5,给出python代码
时间: 2024-02-25 17:56:22 浏览: 86
以下是基于MindSpore实现手写体数字识别的LeNet代码,其中将网络的通道数修改为了16,卷积核大小为7*7:
```
import mindspore.nn as nn
from mindspore import Tensor
from mindspore import context
from mindspore.train import Model
from mindspore.train.callback import LossMonitor
from mindspore.nn.metrics import Accuracy
from mindspore.dataset import MnistDataset
from mindspore.dataset.transforms import py_transforms
class LeNet5(nn.Cell):
def __init__(self, num_class=10, num_channel=1):
super(LeNet5, self).__init__()
self.conv1 = nn.Conv2d(num_channel, 16, 7, pad_mode='valid')
self.conv2 = nn.Conv2d(16, 32, 5, pad_mode='valid')
self.fc1 = nn.Dense(32 * 4 * 4, 120, weight_init='normal')
self.fc2 = nn.Dense(120, 84, weight_init='normal')
self.fc3 = nn.Dense(84, num_class, weight_init='normal')
self.relu = nn.ReLU()
self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
self.flatten = nn.Flatten()
def construct(self, x):
x = self.max_pool2d(self.relu(self.conv1(x)))
x = self.max_pool2d(self.relu(self.conv2(x)))
x = self.flatten(x)
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.fc3(x)
return x
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
lr = 0.01
momentum = 0.9
epoch = 10
batch_size = 32
network = LeNet5()
loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
opt = nn.Momentum(network.trainable_params(), lr, momentum)
model = Model(network, loss_fn=loss, optimizer=opt, metrics={"Accuracy": Accuracy()})
trans = py_transforms.Compose([py_transforms.Resize((32, 32)), py_transforms.ToTensor(), py_transforms.Normalize((0.1307,), (0.3081,))])
ds_train = MnistDataset("./MNIST_Data/train", num_shards=1, shard_id=0, shuffle=True, transform=trans)
ds_test = MnistDataset("./MNIST_Data/test", num_shards=1, shard_id=0, shuffle=True, transform=trans)
model.train(epoch, ds_train, callbacks=[LossMonitor(50)], dataset_sink_mode=False)
res = model.eval(ds_test)
print("Accuracy: ", res["Accuracy"])
```
需要注意的是,我们在数据预处理时对图像进行了 resize 操作,并将像素值做了归一化处理,这有助于提高网络的性能和识别效果。此外,在训练过程中,我们使用了 SoftmaxCrossEntropyWithLogits 作为损失函数,并使用 Momentum 作为优化器,这些超参数的设置会对最终的识别效果产生影响。
阅读全文