PyTorch神经网络模型可视化--以卷积神经网络建模识别手写体数字为例

#神经网络模型可视化--以手写体数字识别卷积神经网络为例
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,
    #将数据转化为torch使用的张量 取值范围为【0,1】
    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.data
test_data_x=test_data.data.type(torch.FloatTensor)/255.0#转化为张量并规范化,取值范围缩放到【0,1】区间
#增加一个通道维度
test_data_x=torch.unsqueeze(test_data_x,dim=1)
test_data_y=test_data.targets#测试集标签test_data.targets
print("test_data_x.shape:",test_data_x.shape)
print("test_data_y.shape:",test_data_y.shape)
# #检查训练数据集的一个batch的样本的维度是否正确
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(
            # 输入维度1 输出维度16 卷积核尺寸3x3,卷积核步长1 进行填充
            nn.Conv2d(in_channels=1,out_channels=16,kernel_size=3,stride=1,padding=1,),#1x16x28x28
            nn.ReLU(),#激活函数
            nn.AvgPool2d(kernel_size=2,stride=2),#平均池化层 2x2 步长2  1x16x14x14
        )
        #定义第二个卷积层
        self.conv2=nn.Sequential(
            nn.Conv2d(16,32,3,1,1),#1x32x14x14
            nn.ReLU(),
            nn.MaxPool2d(2,2)#1x32x7x7
        )
        #定义全连接层
        self.fc=nn.Sequential(
            # 这里之前有一个展平的步骤x=x.view(x.size(0),-1)#展平多维的卷积图层 所以维度改变 32x7x7
            # 1x1568(32*7*7)
            nn.Linear(in_features=32*7*7,out_features=128),#1x128
            nn.ReLU(),
            nn.Linear(128,64),#1x64
            nn.ReLU()
        )
        #最后的分类层
        self.out=nn.Linear(64,10)#1x10
    #定义网络的前向传播路径:
    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)
#hiddenlayer可视化
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")

在这里插入图片描述

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值