#
import torch
from torch import nn
from d2l import torch as d2l
import torchvision
from torch.utils import data
from torchvision import transforms
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
class Reshape(torch.nn.Module):
def forward(self,x):
return x.view(-1,1,28,28)
net = torch.nn.Sequential(
Reshape(),nn.Conv2d(1,6,kernel_size=5,padding=2),nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2,stride=2),
nn.Conv2d(6,16,kernel_size=5),nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2,stride=2),nn.Flatten(),
nn.Linear(16*5*5,120),nn.Sigmoid(),
nn.Linear(120,84),nn.Sigmoid(),
nn.Linear(84,10)
)
x = torch.rand(size=(1,1,28,28),dtype=torch.float32)
for layer in net:
x = layer(x)
print(layer.__class__.__name__,'output shape: \t',x.shape)
trans = transforms.ToTensor()
mnist_train = torchvision.datasets.FashionMNIST(root="./data",train=True,transform=trans,download=True)
mnist_test = torchvision.datasets.FashionMNIST(root="./data",train=False,transform=trans,download=True)
batch_size = 256
train_iter,test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)
def evaluate_accuracy_gpu(net,data_iter,device=None):
#使用gpu计算模型在数据集上的精度
if isinstance(net,torch.nn.Module):
net.eval()
if not device:
device = next(iter(net.parameters())).device
metric = d2l.Accumulator(2)
for x,y in data_iter:
if isinstance(x,list):
x = [a.to(device) for a in x]
else:
x = x.to(device)
y = y.to(device)
metric.add(d2l.accuracy(net(x),y),y.numel())
return metric[0] / metric[1]
lr,num_epochs = 0.9,10
d2l.train_ch6(net,train_iter,test_iter,num_epochs,lr,d2l.try_gpu())
d2l.plt.show()
23-lenet 动手深度学习
最新推荐文章于 2023-03-13 22:00:11 发布