pytorch读写文件

加载和保存张量

x = torch.arange(4)
torch.save(x, 'x-file')
x2 = torch.load('x-file')
x2
tensor([0, 1, 2, 3])

张量列表

y = torch.zeros(4)
torch.save([x, y],'x-files')
x2, y2 = torch.load('x-files')
(x2, y2)

(tensor([0, 1, 2, 3]), tensor([0., 0., 0., 0.]))

张量的字典

mydict = {'x': x, 'y': y}
torch.save(mydict, 'mydict')
mydict2 = torch.load('mydict')
mydict2

{‘x’: tensor([0, 1, 2, 3]), ‘y’: tensor([0., 0., 0., 0.])}

加载和保存模型参数

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()

MLP( (hidden): Linear(in_features=20, out_features=256, bias=True)
(output): Linear(in_features=256, out_features=10, bias=True) )

import torch
import torch.nn.functional as F
from torch import nn

model = nn.Sequential(nn.Linear(10,100), nn.ReLU(), nn.Linear(100,10))
torch.save(model, 'model.pt')
m = torch.load('model.pt')
i = m(torch.rand(2,10))
print(i)

相关推荐

  1. pytorch文件

    2024-04-04 16:14:04       38 阅读
  2. Pytorch张量文件

    2024-04-04 16:14:04       73 阅读
  3. python文件

    2024-04-04 16:14:04       42 阅读
  4. 文件

    2024-04-04 16:14:04       34 阅读
  5. Python:文件

    2024-04-04 16:14:04       35 阅读
  6. Python 文件

    2024-04-04 16:14:04       24 阅读
  7. Python--文件

    2024-04-04 16:14:04       27 阅读
  8. c++的文件

    2024-04-04 16:14:04       58 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-04 16:14:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-04 16:14:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-04 16:14:04       87 阅读
  4. Python语言-面向对象

    2024-04-04 16:14:04       96 阅读

热门阅读

  1. Composer常见错误及解决方法

    2024-04-04 16:14:04       42 阅读
  2. Linux初学(十三)中间件

    2024-04-04 16:14:04       40 阅读
  3. var let 在 for 循环中的区别

    2024-04-04 16:14:04       39 阅读
  4. VMware虚拟机三种网络模式

    2024-04-04 16:14:04       36 阅读
  5. OBS在Linux下安装NDI插件手札

    2024-04-04 16:14:04       37 阅读