pytorch一小时入门教程
from __future__ import print_function
import torch#初始化5*3的矩阵
x = torch.empty(5, 3)
print("x0",x)
#创建一个随机初始化矩阵
x = torch.rand(5, 3)
print("x1",x)
#以0填充的矩阵,并定义type
x = torch.zeros(5, 3, dtype=torch.long)
print("x3",x)#直接从数据构建tensor
x = torch.tensor([5.5, 3])
print("x4",x)x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes
print("x5",x)x = torch.randn_like(x, dtype=torch.float) # 重载 dtype!
print("x6",x)print(x.size())
#注意:torch.Size 本质上还是 tuple ,所以支持 tuple 的一切操作。
#相加
y = torch.rand(5, 3)
print(x + y)
print(torch.add(x, y))result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)# adds x to y
y.add_(x)
print(y)
#注意:任何一个就地改变张量的操作后面都固定一个 _ 。例如 x.copy_(y), x.t_()将更改x#也可以使用像标准的 NumPy 一样的各种索引操作:print(x[:, 1])x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())#如果是仅包含一个元素的 tensor,可以使用 .item() 来得到对应的 python 数值x = torch.randn(1)
print(x)
print(x.item())#将 torch 的 Tensor 转换为 NumPy 数组
a = torch.ones(5)
print(a)
b = a.numpy()
print(b)a.add_(1)
print(a)
print(b)#将numpy转化成tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)# 当GPU可用时,我们可以运行以下代码
# 我们将使用`torch.device`来将tensor移入和移出GPU
if torch.cuda.is_available():device = torch.device("cuda") # a CUDA device objecty = torch.ones_like(x, device=device) # 直接在GPU上创建tensorx = x.to(device) # 或者使用`.to("cuda")`方法z = x + yprint(z)print(z.to("cpu", torch.double)) # `.to`也能在移动时改变dtype