import os
import cv2
import torch
if __name__ == "__main__":
# 创建未初始化的矩阵
x = torch.empty(5, 3)
# 创建随机初始化矩阵
x1 = torch.rand(5, 3)
# 创建一个0填充的矩阵,数据类型为long
# 注意 zeros 有s,类型参数为dtype 且是torch.long
x2 = torch.zeros(5, 3, dtype=torch.long)
# 创建并使用现有数据初始化
x3 = torch.tensor([5.5, 3.3], requires_grad=True)
print(x3)
x4 = torch.tensor(x2)
print(x4)
# 不建议x4赋值方式,运行会提示
# UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach()
# or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
x5 = x3.clone().detach() # clone会做一个当前计算图的copy,然后不影响主计算图
print(x5)
x5[1] = 1
print(x3.grad, x5.grad)
x6 = x3.detach()
# 返回一个新的Variable,从当前计算图中分离下来的,但是仍指向原变量的存放位置,不同之处只是requires_grad为false,得到的这个Variable永远不需要计算其梯度,不具有grad。
# 即使之后重新将它的requires_grad置为true,它也不会具有梯度grad
# 使用detach返回的tensor和原始的tensor共同一个内存,即一个修改另一个也会跟着改变。
print(x6)
x6[1] = 1
print(x3.grad, x6.grad)
print(x3, x6)
# 根据现有张量创建张量,会重用输入张量的属性,除非设置新的值覆盖
x7 = x1.new_ones(5, 4) # new_* 创建对象
print(x7)
x8 = torch.randn_like(x3)
print(x8)
# size
x.size()
# view
x9 = torch.randn(4, 4)
y = x9.view(16)
z = x9.view(-1, 8) # size -1 从其他维度推断
print(x.size(), y.size(), z.size())
# .item()
print(x1[0][0].item())
# 转换为numpy
y1 = x.numpy()
print(y1)
# numpy 转torch
y2 = torch.from_numpy(y1)
print(y2)
# 所有的 Tensor 类型默认都是基于CPU, 使用.to 方法 可以将Tensor移动到任何设备中
y2.to("cpu", torch.double) # ``.to`` 也会对变量的类型做更改
pytorch基础:tensor
最新推荐文章于 2024-06-08 09:33:15 发布