numpy读写数据

numpy读写数据

  1. 使用numpy读写ndarray
import numpy as np
aa=np.random.randint(1,4,size=(3,3))
print(aa)
np.save('ndarray_data.npy',aa)

bb=np.load('ndarray_data.npy')
print(bb)
print(type(bb))

显示结果为:

[[3 3 2]
 [1 3 1]
 [1 3 3]]
[[3 3 2]
 [1 3 1]
 [1 3 3]]
<class 'numpy.ndarray'>
  1. 使用numpy保存和读取字典(value是torch.Tensor)
import numpy as np
import torch as t

a={}
w1=t.randn(3,3)
print(w1)
b1=t.randn(3,1)
print(b1)
w2=t.randn(3,3)
print(w2)
b2=t.randn(3,1)
print(b2)
a['conv1/weight']=w1
a['conv1/bias']=b1
a['conv2/weight']=w2
a['conv2/bias']=b2
np.save('aaa.npy',a)

print('save success')

tmp=np.load('aaa.npy')
print(type(tmp))
print(tmp[()].keys())

print('-'*20)
for key in tmp[()]:
    print(key,':')
    print(type(tmp[()][key]))
    print(tmp[()][key])
    print('-'*10)

显示结果为:

tensor([[ 0.5694,  0.8036, -0.6987],
        [-0.8518,  0.3729, -1.3868],
        [-0.0352, -0.7815,  0.3556]])
tensor([[1.0807],
        [2.4857],
        [0.5353]])
tensor([[-0.0558,  0.2604,  2.3809],
        [-0.1489, -0.3342,  1.7391],
        [-0.3890,  0.5136,  0.2696]])
tensor([[-2.5337],
        [-1.1947],
        [-0.4896]])
save success
<class 'numpy.ndarray'>
dict_keys(['conv1/weight', 'conv1/bias', 'conv2/weight', 'conv2/bias'])
--------------------
conv1/weight :
<class 'torch.Tensor'>
tensor([[ 0.5694,  0.8036, -0.6987],
        [-0.8518,  0.3729, -1.3868],
        [-0.0352, -0.7815,  0.3556]])
----------
conv1/bias :
<class 'torch.Tensor'>
tensor([[1.0807],
        [2.4857],
        [0.5353]])
----------
conv2/weight :
<class 'torch.Tensor'>
tensor([[-0.0558,  0.2604,  2.3809],
        [-0.1489, -0.3342,  1.7391],
        [-0.3890,  0.5136,  0.2696]])
----------
conv2/bias :
<class 'torch.Tensor'>
tensor([[-2.5337],
        [-1.1947],
        [-0.4896]])
----------
  1. 使用numpy中的savez()同时保存数组、字符串、字典数据
    参考链接:https://blog.csdn.net/lilong117194/article/details/83589510
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值