深度学习查阅文档

查阅文档

由于篇幅限制,本书不可能介绍每一个 PyTorch 函数和类。API 文档、其他教程和示例提供了本书之外的大量文档。本节提供了一些查看 PyTorch API 的指导。

查找模块中的所有函数和类

为了知道模块中可以调用哪些函数和类,可以调用 dir 函数。例如,我们可以查询随机数生成模块中的所有属性:

1
2
3
import torch

print(dir(torch.distributions))

输出(部分):

1
2
3
4
['AbsTransform', 'AffineTransform', 'Bernoulli', 'Beta', 'Binomial', ...,
'Distribution', 'Exponential', 'ExponentialFamily', ...,
'Multinomial', 'MultivariateNormal', 'Normal', ...,
'Uniform', 'VonMises', 'Weibull', 'Wishart', ...]

通常可以忽略以 “__“(双下划线)开始和结束的函数,它们是 Python 中的特殊对象,或以单个 “_“(单下划线)开始的函数,它们通常是内部函数。根据剩余的函数名或属性名,我们可能会猜测这个模块提供了各种生成随机数的方法,包括从均匀分布(uniform)、正态分布(normal)和多项分布(multinomial)中采样。

查找特定函数和类的用法

有关如何使用给定函数或类的更具体说明,可以调用 help 函数。例如,我们来查看张量 ones 函数的用法。

1
help(torch.ones)

输出(部分):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Help on built-in function ones in module torch:

ones(...)
ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor

Returns a tensor filled with the scalar value 1, with the shape defined
by the variable argument `size`.

Args:
size (int...): a sequence of integers defining the shape of the output tensor.
Can be a variable number of arguments or a collection like a list or tuple.

Keyword arguments:
out (Tensor, optional): the output tensor.
dtype (`torch.dtype`, optional): the desired data type of returned tensor.
Default: if `None`, uses a global default (see `torch.set_default_tensor_type()`).
layout (`torch.layout`, optional): the desired layout of returned Tensor.
Default: `torch.strided`.
device (`torch.device`, optional): the desired device of returned tensor.
Default: if `None`, uses the current device for the default tensor type
(see `torch.set_default_tensor_type()`). `device` will be the CPU
for CPU tensor types and the current CUDA device for CUDA tensor types.
requires_grad (bool, optional): If autograd should record operations on the
returned tensor. Default: `False`.

Example::

>>> torch.ones(2, 3)
tensor([[ 1., 1., 1.],
[ 1., 1., 1.]])

>>> torch.ones(5)
tensor([ 1., 1., 1., 1., 1.])

从文档中,我们可以看到 ones 函数创建一个具有指定形状的新张量,并将所有元素值设置为 1。下面来运行一个快速测试来确认这一解释:

1
2
torch.ones(4)
# tensor([1., 1., 1., 1.])

在 Jupyter 记事本中,我们可以使用 ? 指令在另一个浏览器窗口中显示文档。例如,list? 指令将创建与 help(list) 指令几乎相同的内容,并在新的浏览器窗口中显示它。此外,如果我们使用两个问号,如 list??,将显示实现该函数的 Python 代码。

小结

  • 官方文档提供了本书之外的大量描述和示例。
  • 可以通过调用 dirhelp 函数或在 Jupyter 记事本中使用 ??? 查看 API 的用法文档。

参考资料