什么是pytorch?
pytorch是一个基于Numpy的科学技术包:
- 作为Numpy的替代者,向用户提供使用GPU的强大功能;
- 作为一款深度学习的平台,向用户提供最大的灵活性和速度。
pytorch的基本元素操作
Tensors张量:张量的概念类似于Numpy的ndarray数据结构,最大的区别是张量可以使用GPU加速功能。
import torch
# 创建一个没有初始化的矩阵
x = torch.empty(5, 3)
print(x)
tensor([[1.4347e-13, 6.0676e-43, 1.4347e-13],
[6.0676e-43, 1.4347e-13, 6.0676e-43],
[1.4347e-13, 6.0676e-43, 1.4347e-13],
[6.0676e-43, 1.4347e-13, 6.0676e-43],
[1.4347e-13, 6.0676e-43, 1.4347e-13]])
# 创建一个初始化的矩阵
x = torch.rand(5, 3)
print(x)
tensor([[0.2793, 0.6181, 0.2992],
[0.7091, 0.2604, 0.5336],
[0.2110, 0.3474, 0.5670],
[0.4748, 0.1299, 0.2168],
[0.1401, 0.1816, 0.1144]])
# 创建一个全零矩阵并数据元素类型为long
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
# 直接通过数据创建张量
x = torch.tensor([2.5, 3.5])
print(x)
tensor([2.5000, 3.5000])
# 利用news_methods方法得到一个张量,利用已有张量创建新张量
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
# 利用已有张量创建相同尺寸的张量
y = torch.randn_like(x, dtype=torch.float)
print(y)
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[-0.6377, 1.0156, -0.5379],
[-0.1870, 0.1735, 0.5903],
[-0.0608, -0.6910, 0.6437],
[ 0.9658, 1.1962, 0.7312],
[ 0.5714, -0.4234, -1.2121]])
# 得到张量形状
print(x.size())
print(y.size())
torch.Size([5, 3])
torch.Size([5, 3])
# x.size()返回的是元组
a, b = x.size()
print('a=', a)
print('b=', b)
a= 5
b= 3
# 加法操作
x = torch.rand(5, 3)
y = torch.rand(5, 3)
print(x + y)
tensor([[1.5752, 1.0136, 0.6618],
[0.5193, 0.9882, 0.1690],
[0.8353, 1.2732, 0.6524],
[0.4697, 1.0188, 1.4941],
[1.3384, 1.1633, 0.2593]])
print(torch.add(x, y))
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
原地置换,所有原地置换in-place都有一个下划线
# y=y+x
y.add_(x)
print(y)
# 改变张量的形状
x = torch.rand(4, 4)
y = x.view(16)
z = x.view(-1, 8)
print(x.size(), y.size(), z.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
# 如果张量中只有一个元素,可以用.item()将其取出,作为一个python number
x = torch.rand(1)
print(x)
print(x.item())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
tensor([0.7272])
0.7272240519523621
# 将Tensor转换为numpy类型
x = torch.ones(5)
print(x)
y = x.numpy()
print(y)
tensor([1., 1., 1., 1., 1.])
[1. 1. 1. 1. 1.]
# 将Tensor转换为numpy类型,转换后共享内存
x = torch.ones(5)
print(x)
y = x.numpy()
print(y)
x = x.add_(1)
print(x)
print(y)
tensor([1., 1., 1., 1., 1.])
[1. 1. 1. 1. 1.]
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
# 将numpy array转换为torch tensor
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
# 将张量移动到GPU上
x = torch.ones(5)
if torch.cuda.is_available():
# 定义一个设备对象,这里指定为CUDA,即GPU
device = torch.device('cuda')
# 直接在GPU上创建一个张量
y = torch.ones_like(x, device=device)
# 将CPU上的x张量移动到GPU上
x = x.to(device)
z = x + y
print(z)
# 将z转移到CPU上
print(z.to('cpu', torch.double))
tensor([2., 2., 2., 2., 2.], device=‘cuda:0’)
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)