虽然之前有tensorflow的基础,但还是想从头系统的学一边pytorch,跟着tutorial走一遍。
另外tutorial写的真的非常仔细非常好,这篇博客主要是给自己复习用的,其他人可能直接看tutorial比较好。
https://pytorch.org/tutorials/beginner/basics/tensor_tutorial.html
pytorch的张量和numpy的张量在底层用的是一块存储器,可以减少copy的操作。两者互通。
定义tensor的方法
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
也可以从numpy中定义,如:
data = [[1, 2],[3, 4]]
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
下面的操作可以复制一个tensor的形状,数据类型,但是里面的值不一样,如:
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
shape
shape是一个二维元组,定义tensor的维度。
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
上面的shape是(2,3,)结尾多了一个逗号,如果我没记错的话这个的作用在后面是可以起到维度自动对其的作用。这里的话加不加逗号运行结果都一样。
Tensor的属性
有 .shape ,.dtype , .device
tensor = torch.rand(3,4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
结果为:
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
更多属性和方法:
https://pytorch.org/docs/stable/torch.html
利用.to的方法进入GPU模式。
if torch.cuda.is_available():
tensor = tensor.to('cuda')
和numpy类似的索引方法
tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor)
结果为:
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
矩阵拼接
: .cat方法。
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
dim=1的话相当于横着拼,dim=0的话是竖着拼。
因为这个Tensor是二维的,所以dim=2的话会报错。dim本质上来说就是Tensor拼接的维度。简单来说,dim=x,就相当于shape中的[n,m,l,k…]中的第x个维度扩展。如x=1的话就是n变多,其他不变;x=2的话m扩展;x=4,k扩展…
乘法
另外tensor里还有mul、matmul、*,等乘法操作。
tensor = torch.tensor([[1,2,3],[2,2,2]])
y1 = tensor * tensor
print(y1)
结果为:
tensor([[1, 4, 9],
[4, 4, 4]])
tensor = torch.tensor([[1.1,2,3],[2,2,2],[1,1,1]])
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
print(y2)
print(y3)
结果为:
tensor([[14.2100, 12.2000, 6.1000],
[12.2000, 12.0000, 6.0000],
[ 6.1000, 6.0000, 3.0000]])
tensor([[14.2100, 12.2000, 6.1000],
[12.2000, 12.0000, 6.0000],
[ 6.1000, 6.0000, 3.0000]])
matmul和@都是矩阵乘法,*和mul都是数乘。
下划线的使用
在一些方法中末尾价格下划线 _
会使该方法直接替换作用的矩阵,如:
tensor = torch.tensor([[1.1,2,3],[2,2,2],[1,1,1]])
tensor.add(5)
print(tensor, "\n")
tensor.add_(5)
print(tensor)
结果为:
tensor([[1.1000, 2.0000, 3.0000],
[2.0000, 2.0000, 2.0000],
[1.0000, 1.0000, 1.0000]])
tensor([[6.1000, 7.0000, 8.0000],
[7.0000, 7.0000, 7.0000],
[6.0000, 6.0000, 6.0000]])
tutorial中表示不鼓励这种用法,因为常常出错。
NOTE: In-place operations save some memory, but can be problematic when computing derivatives because of an immediate loss of history. Hence, their use is discouraged.
numpy和pytorch的桥梁
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
结果为:
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
上文说到,pytorch和numpy用的底层存储器是同一块,这里的n
和t
本质上是一个东西。
如对t进行操作:
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
结果为:
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
n也一起跟着变了。
上面这个例子是从tensor到numpy的,反过来从numpy到tensor同理。
n = np.ones(5)
t = torch.from_numpy(n)
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
结果为:
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]