库导入
import torch
from __future__ import print_function
矩阵(张量)创建函数ones/zeros/rand(n)/empty/full/eye
from __future__ import print_function
import torch
# 空阵
# create a matrix without initial value
x = torch.empty(5, 3)
print(x)
# 全0阵
# create a matrix with 0 initial value
x = torch.zeros(5,3,dtype=torch.long)
print(x)
# 随机数矩阵
# create a matrix with random initial value
x = torch.rand(5,3) # 均匀分布(0,1)
x = torch.randn(5,3) # 标准正态分布 N(0,1)
x = torch.randint(low = 0, high, size) # 整数范围[low, high)
print(x)
# 特定矩阵
# create a tensor with a certain value
x = torch.tensor([5.5, 3])
print(x)
# 根据已有矩阵的属性新建矩阵,大小不一样
# new_(ones/zeros/empty/tensor) method's output tensor inherits x's properties like dtype, device, etc.
x = x.new_ones((5,3),dtype=torch.double)
print(x)
# 根据已有矩阵的属性新建矩阵,大小也一样
# (randn/zeros/empty/ones)_like method's result has the same size as x
x = torch.randn_like(x, dtype=torch.float)
print(x)
print(x.size())
# 相同值填充矩阵
torch.full(size, fill_value)
torch.full_like(input, fill_value)
# 对角阵
torch.eye(size)
# 与numpy的交互
torch.from_numpy(ndarray) # 从ndarray导入数据
a = torch.ones(5)
b = a.numpy() # 转换为numpy数据,(b的值会随着a改变而变化)
torch.tensor(data, dtype) # data 可以是Numpy中的数组
序列生成
torch.arange(start, end, step) # 不包括end, step是两个点间距
torch.range(start, end, step) # 包括end,step是两个点间距
torch.linspace(start, end, steps) # 包括end, steps 是点的个数,包括端点, (等距离)
torch.logspace(start, end, steps) #
矩阵运算函数
x.size() # 获取矩阵形状 output: torch.Size([5,3])
x[:,1] # 类似numpy的方法来访问元素
# 1 矩阵加法
# |-x + y
# |-torch.add(x, y)
# |-result = torch.empty(5,3); torch.add(x, y, out = result)
# |-y.__add__(x) #相当于y = y + x
# 2 改变形状
# x = torch.randn(4, 4) # x形状是(4,4)
# y = x.view(16) # y形状是(16)
# z = x.view(-1, 8) #z形状是(2,8),-1表示待定,与tensorflow里很像
# 3 获取数值
# x = torch.randn(1)
# print(x)
# print(x.item()) #.item()函数用来读取数值
# 4 矩阵拆分与合并
torch.cat(tensors = (a,b,c), dim = 0, out = None) # 按照某一维度对多个矩阵进行合并, 0-行 1-列
torch.chunk(tensor, chunks, dim = 0) # 按照某一维度对矩阵进行切分
# CUDA张量
# is_available 函数判断是否有cuda可以使用
# torch.device将张量移动到指定的设备中
x = torch.randn(1)
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA 设备对象
y = torch.ones_like(x, device=device) # 直接从GPU创建张量
x = x.to(device) # 或者直接使用``.to("cuda")``将张量移动到cuda中
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` 也会对变量的类型做更改
# 上面一段代码打印
tensor([0.7632], device='cuda:0')
tensor([0.7632], dtype=torch.float64)