numpy读写数据
- 使用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'>
- 使用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]])
----------
- 使用numpy中的savez()同时保存数组、字符串、字典数据
参考链接:https://blog.csdn.net/lilong117194/article/details/83589510