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>)
相关推荐
AI办公探索者8 小时前
多智能体协作架构:从单Agent到多Agent协同的技术演进
人工智能·ai·架构
V哥AI增长8 小时前
宠物行业GEO机制:AI如何推荐医院与产品
人工智能·搜索引擎·宠物
baidu_259339579 小时前
智慧消防管理系统平台(基于物联网与大数据的城市消防安全解决方案)
大数据·人工智能·物联网·云计算·智慧消防·力安科技·gdliontech.cn
欧阳天羲9 小时前
【升级版】AI毫米波雷达扫描+视觉双鉴激光灭蚊机器人|360°全域侦测+超低误杀+人体安全防护(ESP32+YOLOv8全套开源)
人工智能·安全·机器人
fthux9 小时前
装闭 RenoPit 源码解析(14):Demo模式、健康检查与Docker部署
人工智能·ai·开源·github·open source·renopit
IT_陈寒9 小时前
为什么我的JavaScript闭包总是漏掉那个变量?
前端·人工智能·后端
蜘蛛小助理9 小时前
生鲜冷链批次效期与多仓调拨损耗管控|低代码搭建生鲜供应链台账
人工智能·低代码·ai·erp·多维表格·蜘蛛表格·生鲜
ASKED_20199 小时前
从 ASR+LLM+TTS 到 GPT‑Live:解读语音智能新范式
人工智能·gpt·语音识别
DS随心转APP9 小时前
AI生成的word怎么下载?AI导出鸭技术架构深度测评
人工智能·ai·架构·word·deepseek·ai导出鸭