pytorch tensor的创建
程序员文章站
2022-07-13 10:11:57
...
一、使用实际的数据创建tensor
1、使用list
tensor = torch.tensor([[2, 3, 4],[5, 6, 7]])
print(tensor)
tensor([[2, 3, 4],
[5, 6, 7]])
2、使用numpy
np_array = np.array([[1,2,3],[1,2,3]])
np_to_tensor = torch.from_numpy(np_array)
print(np_to_tensor)
二、使用维度来创建tensor
1、创建一个float类型的tesor
floattenor1 = torch.FloatTensor(2, 3)
print(floattenor1)
2、创建一个int类型的tensor
inttensor = torch.IntTensor(2, 3)
print(inttensor)
3、创建一个数值在[0,1]之间的tensor
randTensor = torch.rand(3, 3)
4、创建一个在规定范围中随机取值的tensor
randIntTensor = torch.randint(1, 10, [3, 3])
print(randIntTensor)
5、创建一个在标准正太中取值的tensor
randn = torch.randn(3, 3)
print(randn)
6、创建一个值都相同的tensor
fullTensor = torch.full([2, 3],4)
print(fullTensor)
7、创建一个rang(a,b)的tensor
arangeTensor = torch.arange(1,10)
print(arangeTensor)
8、创建全为0或者全为1的tensor
oneTensor = torch.ones(2, 3)
print(oneTensor)
zerosTensor = torch.zeros(2, 3)
print(zerosTensor)
三、tensor相关的属性
1、tensor的类型
tensor.type()
2、tensor的形状
tensor.size()
3、tenor某维的大小
tenor.shape[0]
tesnor.shape[1]
c = torch.tensor([[1, 2, 3], [1, 2, 3]])
print(c)
print(c.shape)
print(c.shape[0])
print(c.shape[1])
print(len(c.shape))
print(c.size())