6、PyTorch中搭建分类网络实例

1. 重要类

  • nn.Module
  • nn.flatten
  • nn.linear
  • nn.relu
  • to.device
  • torch.cuda.is_available
  • nn.softmax
  • nn.argmax
  • nn.sequential
  • nn.conv2d
  • add_module
  • buffer
  • load_state_dict
  • named_parameters
  • requires_grad
  • save_check_points

2. 代码测试

python 复制代码
import torch
from torch import nn
from torch.nn import Module

torch.set_printoptions(precision=3)


class MyModelTest(Module):
    def __init__(self):
        super(MyModelTest, self).__init__()
        self.linear_1 = nn.Linear(3, 4)
        self.relu = nn.ReLU()
        self.linear_2 = nn.Linear(4, 5)

    def forward(self, x):
        x = self.linear_1(x)
        x = self.relu(x)
        y = self.linear_2(x)
        return y


if __name__ == "__main__":
    matrix = torch.arange(3,dtype=torch.float)
    my_softmax = nn.Softmax(dim=0)
    output = my_softmax(matrix)
    print(f"matrix=\n{matrix}")
    print(f"output=\n{output}")
    my_model = MyModelTest()
    for name, param in my_model.named_parameters():
        print(f"layer:{name}\n|size:{param.size()}\n|values:{param[:2]}\n")
  • 结果:
python 复制代码
matrix=
tensor([0., 1., 2.])
output=
tensor([0.090, 0.245, 0.665])
layer:linear_1.weight
|size:torch.Size([4, 3])
|values:tensor([[-0.544, -0.492,  0.190],
        [-0.424, -0.068,  0.134]], grad_fn=<SliceBackward0>)

layer:linear_1.bias
|size:torch.Size([4])
|values:tensor([0.295, 0.306], grad_fn=<SliceBackward0>)

layer:linear_2.weight
|size:torch.Size([5, 4])
|values:tensor([[ 0.489,  0.018,  0.314,  0.497],
        [ 0.364, -0.455,  0.047, -0.215]], grad_fn=<SliceBackward0>)

layer:linear_2.bias
|size:torch.Size([5])
|values:tensor([-0.027,  0.190], grad_fn=<SliceBackward0>)
相关推荐
上弦外贸新观察5 分钟前
为什么你的外贸官网内容很多,ChatGPT却不推荐?海外GEO优化的几个关键问题
人工智能·chatgpt
火山引擎边缘云13 分钟前
从“看见文字”到“读懂画面”:AI MediaKit 如何实现视频字幕无痕擦除
人工智能·音视频
喵叔哟14 分钟前
企业知识库 RAG 检索设计,三层召回如何兼顾精度与召回率
人工智能
算家云15 分钟前
doubao-seed-2-1 系列模型上架算桥 API | 多模态理解能力继续加强!
人工智能·api·token·算力租赁·算力平台
程序员清风22 分钟前
企业级 AI 中台架构:模型、知识库、Agent 与业务系统
人工智能·架构
甲维斯27 分钟前
“凤雏”MiniMax3.1和 “太空兔”一锅炖了吧!!
人工智能
ADAI_Bowen29 分钟前
建筑可视化的 AI 可控生成路径:渲境 AI 技术原理与工程应用要点
人工智能
天空'之城33 分钟前
多智能体通信灾难:消息泛滥如何拖垮整个 Agent 系统
大数据·人工智能
赤龙ERP33 分钟前
AI+ERP:Agent 进企业,卡在数据和权限这两道坎
人工智能·erp·企业数字化
智圣新创0134 分钟前
地方应用型高校智慧校园效能跃升 智圣新创数据治理全链路落地参考框架
人工智能