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>)
相关推荐
Generalzy几秒前
langchain deepagent框架
人工智能·python·langchain
人工智能培训7 分钟前
10分钟了解向量数据库(4)
人工智能·机器学习·数据挖掘·深度学习入门·深度学习证书·ai培训证书·ai工程师证书
无忧智库13 分钟前
从“数据孤岛”到“城市大脑”:深度拆解某智慧城市“十五五”数字底座建设蓝图
人工智能·智慧城市
Rui_Freely15 分钟前
Vins-Fusion之 SFM准备篇(十二)
人工智能·算法·计算机视觉
hugerat17 分钟前
在AI的帮助下,用C++构造微型http server
linux·c++·人工智能·http·嵌入式·嵌入式linux
AI街潜水的八角24 分钟前
深度学习洪水分割系统2:含训练测试代码和数据集
人工智能·深度学习
万行27 分钟前
机器学习&第二章线性回归
人工智能·python·机器学习·线性回归
小宇的天下41 分钟前
HBM(高带宽内存)深度解析:先进封装视角的技术指南
网络·人工智能
rongcj1 小时前
2026,“硅基经济”的时代正在悄然来临
人工智能
狼叔也疯狂1 小时前
英语启蒙SSS绘本第一辑50册高清PDF可打印
人工智能·全文检索