import torch
import torch.nn as nn
import torchvision
import torchvision.utils as vutils
from torch.optim import SGD
import torch.utils.data as Data
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
train_data=torchvision.datasets.MNIST(
root="Data",
train=True,
transform=torchvision.transforms.ToTensor(),
download=True,
)
train_loader=Data.DataLoader(
dataset=train_data,
batch_size=128,
shuffle=True,
num_workers=0,
)
test_data=torchvision.datasets.MNIST(
root="Data",
train=False,
download=True,
)
test_data_x=test_data.data.type(torch.FloatTensor)/255.0
test_data_x=torch.unsqueeze(test_data_x,dim=1)
test_data_y=test_data.targets
print("test_data_x.shape:",test_data_x.shape)
print("test_data_y.shape:",test_data_y.shape)
for step,(b_x,b_y) in enumerate(train_loader):
if step>0:
break
print("b_x.shape:",b_x.shape)
print("b_y.shape:",b_y.shape)
print("b_x.dtype:",b_x.dtype)
print("b_y.dtype:",b_y.dtype)
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet,self).__init__()
self.conv1=nn.Sequential(
nn.Conv2d(in_channels=1,out_channels=16,kernel_size=3,stride=1,padding=1,),
nn.ReLU(),
nn.AvgPool2d(kernel_size=2,stride=2),
)
self.conv2=nn.Sequential(
nn.Conv2d(16,32,3,1,1),
nn.ReLU(),
nn.MaxPool2d(2,2)
)
self.fc=nn.Sequential(
nn.Linear(in_features=32*7*7,out_features=128),
nn.ReLU(),
nn.Linear(128,64),
nn.ReLU()
)
self.out=nn.Linear(64,10)
def forward(self,x):
x=self.conv1(x)
x=self.conv2(x)
x=x.view(x.size(0),-1)
x=self.fc(x)
output=self.out(x)
return output
MyConvnet=ConvNet()
print(MyConvnet)
import hiddenlayer as hl
from graphviz import Digraph
hl_graph=hl.build_graph(MyConvnet,torch.zeros([1,1,28,28]))
hl_graph.theme=hl.graph.THEMES["blue"].copy()
hl_graph.save("Data/MyConvnet_hl.png",format="png")
![在这里插入图片描述](https://img-blog.csdnimg.cn/2020112711111470.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zOTI3NDA2Nw==,size_16,color_FFFFFF,t_70#pic_center)
test_data_x.shape: torch.Size([10000, 1, 28, 28])
test_data_y.shape: torch.Size([10000])
b_x.shape: torch.Size([128, 1, 28, 28])
b_y.shape: torch.Size([128])
b_x.dtype: torch.float32
b_y.dtype: torch.int64
ConvNet(
(conv1): Sequential(
(0): Conv2d(1, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU()
(2): AvgPool2d(kernel_size=2, stride=2, padding=0)
)
(conv2): Sequential(
(0): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU()
(2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(fc): Sequential(
(0): Linear(in_features=1568, out_features=128, bias=True)
(1): ReLU()
(2): Linear(in_features=128, out_features=64, bias=True)
(3): ReLU()
)
(out): Linear(in_features=64, out_features=10, bias=True)
)
Process finished with exit code 0