Python将张量tensor/列表list/numpy array/字典dict 保存到本地

tensor

x = torch.rand(4,5)
torch.save(x.to(torch.device('cpu')), "myTensor.pth")
 
y = torch.load("myTensor.pth")
print(y)

在这里插入图片描述
在这里插入图片描述
list
保存到本地就是保存为.npy文件

import numpy as np
a = [(u'9000023330249', 1), (u'13142928', 1), (u'9000084906496', 1)]
# 保存
np.save('a.npy',a) # 保存为.npy格式
 
# 读取
b=np.load('a.npy')
#此时b是numpy array
b=b.tolist()

在这里插入图片描述
保存为txt文件,就是直接打开txt文件,往里写

file = open('file_name.txt','w');
file.write(str(list_variable));
file.close();

list保存为json

with open(os.path.join(path, "text_results_rects-format.json"), "w") as f:
    f.write(json.dumps(res))
    f.flush()

numpy array

np.save("filename.npy",a)
b = np.load("filename.npy")

dict

jsObj = json.dumps(dict_)  
fileObject = open('dict.json', 'w')  
fileObject.write(jsObj)  
fileObject.close()

如果字典中的项有numpy.array, 需要.tolist()一下
在这里插入图片描述
读就按照json文件来读

也可以用torch保存

保存成pklpth都行

d = {0:'a', 1:'b'}
torch.save(d, 'test.pkl')
x = torch.load('test.pth')

参考:链接

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值