• 21李沐动手学深度学习v2/读写文件,加载和保存张量


    加载和保存张量

    # 1个张量
    import torch
    from torch import nn
    from torch.nn import functional as F
    
    x=torch.arange(4)
    torch.save(x,'x-file')
    
    x2=torch.load('x-file')
    x2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    tensor([0, 1, 2, 3])
    
    • 1
    # 张量list
    y=torch.zeros(4)
    torch.save([x,y],'x-files')
    x2,y2=torch.load('x-files')
    (x2,y2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    (tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))
    
    • 1
    # 张量字典
    mydict={'x':x,'y':y}
    torch.save(mydict,'mydict')
    mydict2=torch.load('mydict')
    mydict2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    {'x': tensor([0, 1, 2, 3]), 'y': tensor([0., 0., 0., 0.])}
    
    • 1

    加载和保存模型参数(存储权重参数即可)

    class MLP(nn.Module):
        def __init__(self):
            super().__init__()
            self.hidden=nn.Linear(20,256)
            self.output=nn.Linear(256,10)
        def forward(self,x):
            return self.output(F.relu(self.hidden(X)))
    
    net=MLP()
    X=torch.randn(size=(2,20))
    Y=net(X)
    
    # 存储权重参数
    torch.save(net.state_dict(),'mlp.params')
    # 加载权重参数
    clone=MLP()
    clone.load_state_dict(torch.load('mlp.params'))
    clone.eval()
    
    # 使用
    Y_clone=clone(X)
    Y_clone==Y
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    tensor([[True, True, True, True, True, True, True, True, True, True],
            [True, True, True, True, True, True, True, True, True, True]])
    
    • 1
    • 2

    query

    将类别变量转伪变量(one-hot编码特征值),内存炸掉了

    • 答:使用稀疏矩阵,因为one-hot编码,一行只有1个为1其他全0
    • 答:不拿整个句子,拿其中的几个词语

    net(X)会自动调用forward()方法

    • 答:因为python中的magic method会自动被调用,__call__()中调用了forward()方法。__call__(), __init__()这种格式的方法都是magic method,他们会被python自动调用

    kaiming初始化和xavier初始化

    • 答:二者作用一致,用哪个都行,
    • 答:Xavier是常用的权重初始化方法,它表示权重和梯度期望=0,权重和梯度的方差由第t层输入和输出的神经元数量决定。将参数限制在合理的范围内
  • 相关阅读:
    C++回顾录
    计算机网络——IPv4详解
    JS高级02:ES5数组新增方法、函数、闭包
    第03章 Tableau基础操作
    神经网络中的偏置(bias)究竟有什么用?
    Linux重要知识点
    永恒之蓝ms17_010复现过程
    大型语言模型在AMD GPU上的推理优化
    DTLS数据包传输层安全性协议详解
    SpringBoot+Vue实现前后端的毕业设计管理系统
  • 原文地址:https://blog.csdn.net/baidu_35805755/article/details/126803952