我是靠谱客的博主 昏睡小蘑菇,这篇文章主要介绍常用PyTorch中的函数语法torch.viewtorch.randn( )使用.item()来得到对应的python数值将torch的Tensor转化为NumPy数组将NumPy数组转化为Torch张量CUDA上的张量自动求导,现在分享给大家,希望可以做个参考。

PyTorch是一个基于python的科学计算包,主要针对两类人群:
(1)作为NumPy的替代品,可以利用GPU的性能进行计算
(2)作为一个高灵活性、速度快的深度学习平台

语法目录

  • torch.view
  • torch.randn( )
  • 使用.item()来得到对应的python数值
  • 将torch的Tensor转化为NumPy数组
  • 将NumPy数组转化为Torch张量
  • CUDA上的张量
  • 自动求导
    • 张量

torch.view

>>>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())

torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])

torch.randn( )

>>> torch.randn(4)
tensor([-2.1436,  0.9966,  2.3426, -0.6366])

>>> torch.randn(2, 3)
tensor([[ 1.5954,  2.8929, -1.0923],
        [ 1.1719, -0.4709, -0.1996]])

使用.item()来得到对应的python数值

如果是仅包含一个元素的tensor,可以使用.item()来得到对应的python数值

>>>x = torch.randn(1)
>>>print(x)
>>>print(x.item())

tensor([0.0445])
0.0445479191839695

将torch的Tensor转化为NumPy数组

>>>a = torch.ones(5)
>>>print(a)

tensor([1., 1., 1., 1., 1.])

>>>b = a.numpy()
>>>print(b)
[1. 1. 1. 1. 1.]

>>>a.add_(1)
>>>print(a)
>>>print(b)
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]

将NumPy数组转化为Torch张量

>>>import numpy as np
>>>a = np.ones(5)
>>>np.add(a, 1, out=a)
>>>b = torch.from_numpy(a)
>>>print(a)
>>>print(b)

[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

CUDA上的张量

张量可以使用.to方法移动到任何设备(device)上:

# 当GPU可用时,我们可以运行以下代码
# 我们将使用`torch.device`来将tensor移入和移出GPU
if torch.cuda.is_available():
    device = torch.device("cuda")          # 一个CUDA设备对象
    y = torch.ones_like(x, device=device)  # 直接在GPU上创建tensor
    x = x.to(device)                       # 或者使用`.to("cuda")`方法
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # `.to`也能在移动时改变dtype

输出:
tensor([1.0445], device='cuda:0')
tensor([1.0445], dtype=torch.float64)

自动求导

张量

torch.Tensor 是这个包的核心类。如果设置它的属性 .requires_grad 为 True,那么它将会追踪对于该张量的所有操作。当完成计算后可以通过调用 .backward(),来自动计算所有的梯度。这个张量的所有梯度将会自动累加到.grad属性.
要阻止一个张量被跟踪历史,可以调用 .detach() 方法将其与计算历史分离,并阻止它未来的计算记录被跟踪。
为了防止跟踪历史记录(和使用内存),可以将代码块包装在 with torch.no_grad(): 中。在评估模型时特别有用,因为模型可能具有 requires_grad = True 的可训练的参数,但是我们不需要在此过程中对他们进行梯度计算

>>>import torch
>>>x = torch.ones(2, 2, requires_grad=True)
   #创建一个张量并设置requires_grad=True用来追踪其计算历史
>>>print(x)
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)

>>>y = x + 2
>>>print(y)
tensor([[3., 3.],
        [3., 3.]], grad_fn=<AddBackward0>)


>>>print(y.grad_fn)
#y是计算的结果,所以它有grad_fn属性。
<AddBackward0 object at 0x7f1b248453c8>

>>>z = y * y * 3
>>>out = z.mean()
>>>print(z, out)
tensor([[27., 27.],
        [27., 27.]], grad_fn=<MulBackward0>) 
tensor(27., grad_fn=<MeanBackward0>)

.requires_grad_(…) 原地改变了现有张量的 requires_grad 标志。如果没有指定的话,默认输入的这个标志是 False。

>>>a = torch.randn(2, 2)
>>>a = ((a * 3) / (a - 1))
>>>print(a.requires_grad)
>>>a.requires_grad_(True)
>>>print(a.requires_grad)
>>>b = (a * a).sum()
>>>print(b.grad_fn)

False
True
<SumBackward0 object at 0x7f1b24845f98>

最后

以上就是昏睡小蘑菇最近收集整理的关于常用PyTorch中的函数语法torch.viewtorch.randn( )使用.item()来得到对应的python数值将torch的Tensor转化为NumPy数组将NumPy数组转化为Torch张量CUDA上的张量自动求导的全部内容,更多相关常用PyTorch中的函数语法torch.viewtorch.randn(内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(100)

评论列表共有 0 条评论

立即
投稿
返回
顶部