原文作者:Soumith Chintala
原文地址:https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html
教程的目的:
1. 了解Pytorch中的Tensor库并且在高层次理解神经网络。
2. 训练一个小型的神经网络来实现图像分类的任务。
Pytorch是一个基于python的科学计算包。主要有如下特点:
Tensors
Tensors类似于Numpy中的ndarrays,并且可以在GPU上计算。
from __future__ import print_function
import torch
构造一个未初始化的5*3矩阵
x = torch.empty(5, 3)
print(x)
Out:
tensor(
[[ 3.2401e+18, 0.0000e+00, 1.3474e-08],
[ 4.5586e-41, 1.3476e-08, 4.5586e-41],
[ 1.3476e-08, 4.5586e-41, 1.3474e-08],
[ 4.5586e-41, 1.3475e-08, 4.5586e-41],
[ 1.3476e-08, 4.5586e-41, 1.3476e-08]]
)
建立随机初始化矩阵
x = torch.rand(5,3)
print(x)
Out:
tensor(
[[ 0.0993, 0.2305, 0.3597],
[ 0.4006, 0.8186, 0.7320],
[ 0.8274, 0.9112, 0.9628],
[ 0.5093, 0.0285, 0.1659],
[ 0.0799, 0.7159, 0.8973]]
)
构造一个零矩阵,数据类型是long
x = torch.zeros(5,3, dtype=torch.long)
print(x)
Out:
tensor(
[[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]]
)
直接从数据中构造tensor
x = torch.tensor([5.5, 3])
print(x)
Out:
tensor([ 5.5000, 3.0000])
从已经存在的tensor构造一个新的tensor。这些方法能够复用已存在的tensor的dtype等属性,除非用户指定新的属性值。
x = x.new_ones(5,3, dtype=torch.double)
print(x)
x = torch.rand_like(x, dtype=torch.floadt)
print(x)
Out:
tensor([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=torch.float64)
tensor([[ 0.2641, 0.0149, 0.7355],
[ 0.6106, -1.2480, 1.0592],
[ 2.6305, 0.5582, 0.3042],
[-1.4410, 2.4951, -0.0818],
[ 0.8605, 0.0001, -0.7220]])
获取tensor的大小
print(x.size)
Out:
torch.Size([5, 3])
注意torch.Size实际上是一个操作,它支持所有的元组操作。
操作
有很多语法可以实现操作。在下面的例子中,我们将看一下加法操作。
加法:语法1
y = torch.rand(5, 3)
print(x + y)
加法:语法2
print(torch.add(x, y)
指定tensor保存结果
result = torch.empty(5,3)
torch.add(x, y, out=result)
将一个tensor的值加到另一个tensor
y.add_(x)
任何tensor上的,并且以结尾的操作(x.copy(y), x.t_()),都将改变x的值。
可以使用类Numpy的方式来索引tensor
print( x[:, 1])
改变tensor的形状:torch.view
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(4, 4)
print(x.size(), y.size(), z.size())
Out:
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
如果你的tensor只有一个元素,可以使用.item来或者一个python的数值。
x = torch.randn(1)
print(x)
print(x.item())
Out:
tensor([ 1.3159])
1.3159412145614624
Numpy和Tensor的转化
Torch Tensor和Numpy array将共享内存位置,如果你改变其中之一,另外的也将改变
a = torch.ones(5)
b = a.numpy()
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=1)
CUDA Tensors
使用.to方法来将tensor移到指定设备上
if torch.cuda.is_available():
device = torch.device("cuda")
y = tortch.ones_like(x, device=device)
x = x.to(device)
z = x + y
print(z)
print(z.to("cup", torch.double))
Out:
tensor([ 2.3159], device=’cuda:0’)
tensor([ 2.3159], dtype=torch.float64)