• pytorch.创建神经网络


    到目前为止,我们已经学会了怎么生成我们需要的数据和怎么倒入我们需要的数据,其实我们已经完成了一个神经网络的一大半,接下来就是搭建一个神经网络的框架。

    import os
    import torch
    from torch import nn
    from torch.utils.data import DataLoader
    from torchvision import datasets, transforms
    
    # 如果有cuda,那我们就使用cuda加速
    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Using {device} device")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    我们需要创建自己的神经网络的类

    这里我们需要明白,神经网络的每一层的种类我们都是可以自己定义的,如果有其它需要的层,可以看官方文档说明

    https://pytorch.org/docs/stable/nn.html

    class NeuralNetwork(nn.Module):
        def __init__(self):
            super(NeuralNetwork, self).__init__()
            self.flatten = nn.Flatten()
            self.linear_relu_stack = nn.Sequential(
                nn.Linear(28*28, 512),
                nn.ReLU(),
                nn.Linear(512, 512),
                nn.ReLU(),
                nn.Linear(512, 10),
            )
    
        # 前向传播
        def forward(self, x):
            # flatten 用于将x压缩为tensor,与Sequential一起使用
            x = self.flatten(x)
            logits = self.linear_relu_stack(x)
            return logits
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    创建我们的模型

    model = NeuralNetwork().to(device)
    print(model)
    
    • 1
    • 2

    将输出的数字转化为概率

    # 参数device 决定我们将这个矩阵转换为CPU的tensor还是GPU的tensor
    X = torch.rand(1, 28, 28, device=device)
    # 模型的训练结果,得到的结果并不是概率,我们期望得到的是一个概率值
    logits = model(X)
    # 这个可以将神经元的输出转换为概率,返回值为一个tensor,直接创建了一个softmax对象,dim为1,输入值为logits
    pred_probab = nn.Softmax(dim=1)(logits)
    # 返回一个维度上tensor最大值的下表
    y_pred = pred_probab.argmax(1)
    print(f"Predicted class: {y_pred}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    线性层

    layer1 = nn.Linear(in_features=28*28, out_features=20)
    hidden1 = layer1(flat_image)
    print(hidden1.size())
    
    • 1
    • 2
    • 3

    激活层

    print(f"Before ReLU: {hidden1}\n\n")
    hidden1 = nn.ReLU()(hidden1)
    print(f"After ReLU: {hidden1}")
    
    • 1
    • 2
    • 3

    模块的容器

    seq_modules = nn.Sequential(
        flatten,
        layer1,
        nn.ReLU(),
        nn.Linear(20, 10)
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    flatten的作用

    # 产生一个三层 28*28 的tensor
    input_image = torch.rand(3, 28, 28)
    print(input_image.size())
    # flatten可以将二维数据转换为一维数据 3*28*28 -》 3*784
    flatten = nn.Flatten()
    flat_image = flatten(input_image)
    print(flat_image.size())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    输出概率

    input_image = torch.rand(3,28,28)
    logits = seq_modules(input_image)
    
    # softmax输出概率
    softmax = nn.Softmax(dim=1)
    pred_probab = softmax(logits)python
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    输出模型的参数

    # 模型的参数
    print(f"Model structure: {model}\n\n")
    
    for name, param in model.named_parameters():
        print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    Linux CentOS7 vim重复行
    MKD调试下载的时候提示:Contents mismatch at: xxxxxxxxH (Flash=xxH Required=xxH)
    LISTAGG () 和STRING_AGG () 函数的区别与简单使用
    深入理解ngx_http_upstream_vnswrr_module负载均衡模块
    MySQL数据库——权限控制及日志管理
    25.10 MySQL 约束
    WindowsPE(二)空白区添加代码&新增,扩大,合并节
    TDengine 跨版本迁移实战
    java计算机毕业设计Web端校园报修系统MyBatis+系统+LW文档+源码+调试部署
    @Reference 、@Resource和@Autowired的简单区分
  • 原文地址:https://blog.csdn.net/weixin_43903639/article/details/126907960