查阅文档 ======== 查找模块中的所有函数和类 ------------------------ 为了知道模块中可以调用哪些函数和类,可以调用\ ``dir``\ 函数。 例如,我们可以查询随机数生成模块中的所有属性: .. raw:: latex \diilbookstyleinputcell .. code:: python import mlx.core as mx print(dir(mx.random)) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'bernoulli', 'categorical', 'gumbel', 'key', 'laplace', 'multivariate_normal', 'normal', 'permutation', 'randint', 'seed', 'split', 'state', 'truncated_normal', 'uniform'] 通常可以忽略以“``__``”(双下划线)开始和结束的函数,它们是Python中的特殊对象, 或以单个“``_``”(单下划线)开始的函数,它们通常是内部函数。 根据剩余的函数名或属性名,我们可能会猜测这个模块提供了各种生成随机数的方法, 包括从均匀分布(\ ``uniform``\ )、正态分布(\ ``normal``\ )和多项分布(\ ``multinomial``\ )中采样。 查找特定函数和类的用法 ---------------------- 有关如何使用给定函数或类的更具体说明,可以调用\ ``help``\ 函数。 例如,我们来查看张量\ ``ones``\ 函数的用法。 .. raw:: latex \diilbookstyleinputcell .. code:: python help(mx.ones) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output Help on nb_func in module mlx.core: ones = ones(shape: Union[int, Sequence[int]], dtype: Optional[Dtype] = float32, *, stream: Union[None, Stream, Device] = None) -> array Construct an array of ones. Args: shape (int or list(int)): The shape of the output array. dtype (Dtype, optional): Data type of the output array. If unspecified the output type defaults to ``float32``. Returns: array: The array of ones with the specified shape. 从文档中,我们可以看到\ ``ones``\ 函数创建一个具有指定形状的新张量,并将所有元素值设置为1。 下面来运行一个快速测试来确认这一解释: .. raw:: latex \diilbookstyleinputcell .. code:: python mx.ones(4) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output array([1, 1, 1, 1], dtype=float32) 在Jupyter记事本中,我们可以使用\ ``?``\ 指令在另一个浏览器窗口中显示文档。 例如,\ ``list?``\ 指令将创建与\ ``help(list)``\ 指令几乎相同的内容,并在新的浏览器窗口中显示它。 此外,如果我们使用两个问号,如\ ``list??``\ ,将显示实现该函数的Python代码。 小结 ---- - 官方文档提供了本书之外的大量描述和示例。 - 可以通过调用\ ``dir``\ 和\ ``help``\ 函数或在Jupyter记事本中使用\ ``?``\ 和\ ``??``\ 查看API的用法文档。 练习 ---- 1. 在深度学习框架中查找任何函数或类的文档。请尝试在这个框架的官方网站上找到文档。