torch.Storge
官方解释:A torch.Storage is a contiguous, one-dimensional array of a single data type.Every torch.Tensor has a corresponding storage of the same data type.
有道君:torch.Storage 是一个连续的,一维的,单一数据类型的数组。每一个torch.Tensor有一个对应的torch.storage,并且二者都有相同的数据类型。
torch.Storge与torch.Tensor的区别
a = torch.FloatTensor([1, 2, 3])
b = torch.FloatStorage([1, 2, 3])
print (a)
print (type(a))
print (type(a[0]))
print (a.shape)
print (b)
print (type(b))
print (type(b[0]))
#print (b.shape) 报错
输出内容:
tensor([1., 2., 3.])
torch.Size([3])
1.0
2.0
3.0
[torch.FloatStorage of size 3]
FloatTensor可以接受FloatStorage类型进行初始化,若对FloatStorage进行修改时,FloatTensor也会被修改:
b = torch.FloatStorage([1, 2, 3])
a = torch.FloatTensor(b)
b[0] = 10
print(b)
print(a)
输出内容:
10.0
2.0
3.0
[torch.FloatStorage of size 3]
tensor([10., 2., 3.])
torch.from_numpy
torch.from_numpy与用FloatStorage初始化类似,不是直接复制数据初始化。修改numpy类型数据时,tensor数据会发生改变.
a = np.array([1,2,3])
b = torch.from_numpy(a)
a[0] = 10
print (b)
输出内容:
tensor([10, 2, 3], dtype=torch.int32)
结论
当张量需要被多处共享使用时,使用FloatStorage初始化FloatTensor.
torch.from_numpy和torch.tensor(FloatStorage)都是浅拷贝。