线性卷积和有关手写识别例题的提升

```import torch
from matplotlib import pyplot as plt
from torchvision import datasets
from torchvision import transforms
import torch.optim as optim
import numpy as np

batch_size = 64
batch_size_test = 100
data_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])

class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear1 = torch.nn.Linear(784, 512)
self.linear2 = torch.nn.Linear(512, 256)
self.linear3 = torch.nn.Linear(256, 128)
self.linear4 = torch.nn.Linear(128, 64)
self.linear5 = torch.nn.Linear(64, 10)
self.relu = torch.nn.ReLU()

def forward(self, x):
x = x.view(-1, 784)
x = self.relu(self.linear1(x))
x = self.relu(self.linear2(x))
x = self.relu(self.linear3(x))
x = self.relu(self.linear4(x))
return self.linear5(x)

model = Model()
criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=1e-2, momentum=0.5)
loss_list = list()

def test_accuracy():
correct = 0
images, labels = data
pred = model(images)
total_num = 0
correct = 0
for i in range(batch_size_test):
labels_np = labels.numpy().tolist()
pred_np = pred.numpy().tolist()
total_num += 1
if labels_np[i] == pred_np[i].index(max(pred_np[i])):
correct += 1
print(f'Accuracy = {correct/total_num}, i = {i}')

if __name__ == '__main__':
for epoch in range(10):
for i, data in enumerate(trainloader, 0):
inputs, label = data
outputs = model(inputs)

loss = criterion(outputs, label)
loss_list.append(loss)
loss.backward()

optimizer.step()
print(f'[{epoch}]: loss = {loss}')

plt.plot(loss_list)
plt.show()

test_accuracy()

import numpy as np
from PIL import Image

a = Image.open('test.jpg')
c = a.convert('L')
c.show()
# print(c)
im = np.array(a)
im_gray = np.array(c)
print(im_gray.shape)
print(im_gray)
print(im.shape)
# print(im)
b = np.array([[[1,2,3],[2,3,3],[3,4,5]],[[2,1,2],[3,4,5],[4,5,6]]])
# print(b.shape)
# a.show()
# print(a)```

```import torch
from torchvision import datasets,transforms
transform=transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,),(0.3081,))])

class ConvModel(torch.nn.Module):
def __init__(self):
super(ConvModel, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = torch.nn.Conv2d(10, 20, kernel_size=5)
self.maxpooling=torch.nn.MaxPool2d(kernel_size=2)
self.linear=torch.nn.Linear(320,10)
self.relu=torch.nn.ReLU()
def forward(self,x):
batch_size=x.size(0)
x=self.relu(self.maxpooling(self.conv1(x)))
x = self.relu(self.maxpooling(self.conv2(x)))
x=x.view(batch_size,-1)
return self.linear(x)  #模型的构建
model=ConvModel()              #模型的初始化

criterion=torch.nn.CrossEntropyLoss()    #选择函数和优化器
optim=torch.optim.SGD(model.parameters(),lr=1e-2,momentum=0.5)

if __name__ == '__main__':
for epoch in range(10):
sum=0
inputs,labels=data
pred=model(inputs)
loss=criterion(pred,labels)  #优化器的清零
sum=sum+loss.item()