ドキュメント ============ すべての PyTorch の関数やクラスをここで紹介することは到底できないし、 その情報はすぐに古くなってしまうかもしれないが、 `API ドキュメント `__ や追加の `チュートリアル `__ と例が そのような文書を提供している。 この節では、PyTorch の API を調べるための指針を示す。 .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python import torch .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python from mxnet import np .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python import jax .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python import tensorflow as tf .. raw:: html
.. raw:: html
モジュール内の関数とクラス -------------------------- モジュール内でどの関数やクラスを呼び出せるかを知るには、 ``dir`` 関数を使う。たとえば、 乱数生成のためのモジュール内のすべての属性を問い合わせることができる。 .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python print(dir(torch.distributions)) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output ['AbsTransform', 'AffineTransform', 'Bernoulli', 'Beta', 'Binomial', 'CatTransform', 'Categorical', 'Cauchy', 'Chi2', 'ComposeTransform', 'ContinuousBernoulli', 'CorrCholeskyTransform', 'CumulativeDistributionTransform', 'Dirichlet', 'Distribution', 'ExpTransform', 'Exponential', 'ExponentialFamily', 'FisherSnedecor', 'Gamma', 'Geometric', 'Gumbel', 'HalfCauchy', 'HalfNormal', 'Independent', 'IndependentTransform', 'Kumaraswamy', 'LKJCholesky', 'Laplace', 'LogNormal', 'LogisticNormal', 'LowRankMultivariateNormal', 'LowerCholeskyTransform', 'MixtureSameFamily', 'Multinomial', 'MultivariateNormal', 'NegativeBinomial', 'Normal', 'OneHotCategorical', 'OneHotCategoricalStraightThrough', 'Pareto', 'Poisson', 'PositiveDefiniteTransform', 'PowerTransform', 'RelaxedBernoulli', 'RelaxedOneHotCategorical', 'ReshapeTransform', 'SigmoidTransform', 'SoftmaxTransform', 'SoftplusTransform', 'StackTransform', 'StickBreakingTransform', 'StudentT', 'TanhTransform', 'Transform', 'TransformedDistribution', 'Uniform', 'VonMises', 'Weibull', 'Wishart', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'bernoulli', 'beta', 'biject_to', 'binomial', 'categorical', 'cauchy', 'chi2', 'constraint_registry', 'constraints', 'continuous_bernoulli', 'dirichlet', 'distribution', 'exp_family', 'exponential', 'fishersnedecor', 'gamma', 'geometric', 'gumbel', 'half_cauchy', 'half_normal', 'identity_transform', 'independent', 'kl', 'kl_divergence', 'kumaraswamy', 'laplace', 'lkj_cholesky', 'log_normal', 'logistic_normal', 'lowrank_multivariate_normal', 'mixture_same_family', 'multinomial', 'multivariate_normal', 'negative_binomial', 'normal', 'one_hot_categorical', 'pareto', 'poisson', 'register_kl', 'relaxed_bernoulli', 'relaxed_categorical', 'studentT', 'transform_to', 'transformed_distribution', 'transforms', 'uniform', 'utils', 'von_mises', 'weibull', 'wishart'] .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python print(dir(np.random)) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output ['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_mx_nd_np', 'beta', 'chisquare', 'choice', 'exponential', 'gamma', 'gumbel', 'logistic', 'lognormal', 'multinomial', 'multivariate_normal', 'normal', 'pareto', 'power', 'rand', 'randint', 'randn', 'rayleigh', 'shuffle', 'uniform', 'weibull'] .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python print(dir(jax.random)) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output ['KeyArray', 'PRNGKey', 'PRNGKeyArray', '_PRNGKeyArray', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'ball', 'bernoulli', 'beta', 'bits', 'categorical', 'cauchy', 'chisquare', 'choice', 'default_prng_impl', 'dirichlet', 'double_sided_maxwell', 'exponential', 'f', 'fold_in', 'gamma', 'generalized_normal', 'geometric', 'gumbel', 'key', 'key_data', 'laplace', 'loggamma', 'logistic', 'maxwell', 'multivariate_normal', 'normal', 'orthogonal', 'pareto', 'permutation', 'poisson', 'rademacher', 'randint', 'random_gamma_p', 'rayleigh', 'rbg_key', 'shuffle', 'split', 't', 'threefry2x32_key', 'threefry2x32_p', 'threefry_2x32', 'truncated_normal', 'typing', 'uniform', 'unsafe_rbg_key', 'wald', 'weibull_min'] .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python print(dir(tf.random)) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output ['Algorithm', 'Generator', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_sys', 'all_candidate_sampler', 'categorical', 'create_rng_state', 'experimental', 'fixed_unigram_candidate_sampler', 'fold_in', 'gamma', 'get_global_generator', 'learned_unigram_candidate_sampler', 'log_uniform_candidate_sampler', 'normal', 'poisson', 'set_global_generator', 'set_seed', 'shuffle', 'split', 'stateless_binomial', 'stateless_categorical', 'stateless_gamma', 'stateless_normal', 'stateless_parameterized_truncated_normal', 'stateless_poisson', 'stateless_truncated_normal', 'stateless_uniform', 'truncated_normal', 'uniform', 'uniform_candidate_sampler'] .. raw:: html
.. raw:: html
一般に、\ ``__`` で始まり ``__`` で終わる関数(Python の特別なオブジェクト)や、 単一の ``_`` で始まる関数(通常は内部関数)は無視して構わない。 残った関数名や属性名から判断すると、 このモジュールは一様分布(\ ``uniform``\ )、 正規分布(\ ``normal``\ )、 多項分布(\ ``multinomial``\ )からのサンプリングを含む、 さまざまな乱数生成メソッドを提供していると推測できる。 特定の関数とクラス ------------------ 特定の関数やクラスの使い方について詳しく知るには、 ``help`` 関数を呼び出す。例として、 テンソルの ``ones`` 関数の使い方を調べてみましょう。 .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python help(torch.ones) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output 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 :attr:`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 (:class:`torch.dtype`, optional): the desired data type of returned tensor. Default: if ``None``, uses a global default (see :func:`torch.set_default_tensor_type`). layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. Default: ``torch.strided``. device (:class:`torch.device`, optional): the desired device of returned tensor. Default: if ``None``, uses the current device for the default tensor type (see :func:`torch.set_default_tensor_type`). :attr:`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.]) .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python help(np.ones) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output Help on function ones in module mxnet.numpy: ones(shape, dtype=, order='C', ctx=None) Return a new array of given shape and type, filled with ones. This function currently only supports storing multi-dimensional data in row-major (C-style). Parameters ---------- shape : int or tuple of int The shape of the empty array. dtype : str or numpy.dtype, optional An optional value type. Default is `numpy.float32`. Note that this behavior is different from NumPy's `ones` function where `float64` is the default value, because `float32` is considered as the default data type in deep learning. order : {'C'}, optional, default: 'C' How to store multi-dimensional data in memory, currently only row-major (C-style) is supported. ctx : Context, optional An optional device context (default is the current default context). Returns ------- out : ndarray Array of ones with the given shape, dtype, and ctx. Examples -------- >>> np.ones(5) array([1., 1., 1., 1., 1.]) >>> np.ones((5,), dtype=int) array([1, 1, 1, 1, 1], dtype=int64) >>> np.ones((2, 1)) array([[1.], [1.]]) >>> s = (2,2) >>> np.ones(s) array([[1., 1.], [1., 1.]]) .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python help(jax.numpy.ones) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output Help on function ones in module jax._src.numpy.lax_numpy: ones(shape: Any, dtype: Union[Any, str, numpy.dtype, jax._src.SupportsDType, NoneType] = None) -> jax.Array Return a new array of given shape and type, filled with ones. LAX-backend implementation of :func:`numpy.ones`. *Original docstring below.* Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. Returns ------- out : ndarray Array of ones with the given shape, dtype, and order. .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python help(tf.ones) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output Help on function ones in module tensorflow.python.ops.array_ops: ones(shape, dtype=tf.float32, name=None) Creates a tensor with all elements set to one (1). See also `tf.ones_like`, `tf.zeros`, `tf.fill`, `tf.eye`. This operation returns a tensor of type `dtype` with shape `shape` and all elements set to one. >>> tf.ones([3, 4], tf.int32) Args: shape: A `list` of integers, a `tuple` of integers, or a 1-D `Tensor` of type `int32`. dtype: Optional DType of an element in the resulting `Tensor`. Default is `tf.float32`. name: Optional string. A name for the operation. Returns: A `Tensor` with all elements set to one (1). .. raw:: html
.. raw:: html
ドキュメントから、\ ``ones`` 関数は 指定された形状をもつ新しいテンソルを作成し、 すべての要素を 1 に設定することがわかる。 可能な限り、解釈が正しいことを確認するために 簡単なテストを実行するべきである。 .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python torch.ones(4) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output tensor([1., 1., 1., 1.]) .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python np.ones(4) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output [07:00:06] ../src/storage/storage.cc:196: Using Pooled (Naive) StorageManager for CPU .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output array([1., 1., 1., 1.]) .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python jax.numpy.ones(4) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output Array([1., 1., 1., 1.], dtype=float32) .. raw:: html
.. raw:: html
.. raw:: latex \diilbookstyleinputcell .. code:: python tf.ones(4) .. raw:: latex \diilbookstyleoutputcell .. parsed-literal:: :class: output .. raw:: html
.. raw:: html
Jupyter ノートブックでは、\ ``?`` を使ってドキュメントを別ウィンドウに表示できる。 たとえば、\ ``list?`` は ``help(list)`` とほぼ同じ内容を生成し、 新しいブラウザウィンドウに表示す。 さらに、\ ``list??`` のように疑問符を 2 つ使うと、 その関数を実装している Python コードも表示される。 公式ドキュメントには、この本の範囲を超える豊富な説明と実例が掲載されている。 私たちは、単なる網羅的なリストを作るよりも、実際に問題を解決するために役立つ重要な使用例を重視して紹介していきる。 また、ライブラリのソースコードを調べて、 本番コードの高品質な実装例を見ることも勧める。 そうすることで、より優れた科学者になるだけでなく、 より優れたエンジニアにもなれるだろう。