《动手学深度学习 Pytorch版》 2.7 查阅文档

2023-11-20

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

import torch

可以调用 dir 函数查询函数中有哪些模块和类。

以 “__”(双下划线) 开始和结束的函数是 Python 中的特殊对象,以 “_”(单下划线)开始的函数是内部函数,通常以上两种函数可以忽略。

dir(torch.distributions)
['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',
 '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']

2.7.2 查找特定的函数和类的用法

可以调用 help 函数查看给定函数或类的更具体的说明。

help(torch.ones)
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.])

练习

(1)在深度学习框架中查找任何函数或类的文档。请尝试在这个框架的官方网站上找到文档。

查找 torch.distributions.multinomial.Multinomial 的说明,其官方文档在此

help(torch.distributions.multinomial.Multinomial)
Help on class Multinomial in module torch.distributions.multinomial:

class Multinomial(torch.distributions.distribution.Distribution)
 |  Multinomial(total_count=1, probs=None, logits=None, validate_args=None)
 |  
 |  Creates a Multinomial distribution parameterized by :attr:`total_count` and
 |  either :attr:`probs` or :attr:`logits` (but not both). The innermost dimension of
 |  :attr:`probs` indexes over categories. All other dimensions index over batches.
 |  
 |  Note that :attr:`total_count` need not be specified if only :meth:`log_prob` is
 |  called (see example below)
 |  
 |  .. note:: The `probs` argument must be non-negative, finite and have a non-zero sum,
 |            and it will be normalized to sum to 1 along the last dimension. :attr:`probs`
 |            will return this normalized value.
 |            The `logits` argument will be interpreted as unnormalized log probabilities
 |            and can therefore be any real number. It will likewise be normalized so that
 |            the resulting probabilities sum to 1 along the last dimension. :attr:`logits`
 |            will return this normalized value.
 |  
 |  -   :meth:`sample` requires a single shared `total_count` for all
 |      parameters and samples.
 |  -   :meth:`log_prob` allows different `total_count` for each parameter and
 |      sample.
 |  
 |  Example::
 |  
 |      >>> m = Multinomial(100, torch.tensor([ 1., 1., 1., 1.]))
 |      >>> x = m.sample()  # equal probability of 0, 1, 2, 3
 |      tensor([ 21.,  24.,  30.,  25.])
 |  
 |      >>> Multinomial(probs=torch.tensor([1., 1., 1., 1.])).log_prob(x)
 |      tensor([-4.1338])
 |  
 |  Args:
 |      total_count (int): number of trials
 |      probs (Tensor): event probabilities
 |      logits (Tensor): event log probabilities (unnormalized)
 |  
 |  Method resolution order:
 |      Multinomial
 |      torch.distributions.distribution.Distribution
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __init__(self, total_count=1, probs=None, logits=None, validate_args=None)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  entropy(self)
 |      Returns entropy of distribution, batched over batch_shape.
 |      
 |      Returns:
 |          Tensor of shape batch_shape.
 |  
 |  expand(self, batch_shape, _instance=None)
 |      Returns a new distribution instance (or populates an existing instance
 |      provided by a derived class) with batch dimensions expanded to
 |      `batch_shape`. This method calls :class:`~torch.Tensor.expand` on
 |      the distribution's parameters. As such, this does not allocate new
 |      memory for the expanded distribution instance. Additionally,
 |      this does not repeat any args checking or parameter broadcasting in
 |      `__init__.py`, when an instance is first created.
 |      
 |      Args:
 |          batch_shape (torch.Size): the desired expanded size.
 |          _instance: new instance provided by subclasses that
 |              need to override `.expand`.
 |      
 |      Returns:
 |          New distribution instance with batch dimensions expanded to
 |          `batch_size`.
 |  
 |  log_prob(self, value)
 |      Returns the log of the probability density/mass function evaluated at
 |      `value`.
 |      
 |      Args:
 |          value (Tensor):
 |  
 |  sample(self, sample_shape=torch.Size([]))
 |      Generates a sample_shape shaped sample or sample_shape shaped batch of
 |      samples if the distribution parameters are batched.
 |  
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |  
 |  logits
 |  
 |  mean
 |      Returns the mean of the distribution.
 |  
 |  param_shape
 |  
 |  probs
 |  
 |  support
 |      Returns a :class:`~torch.distributions.constraints.Constraint` object
 |      representing this distribution's support.
 |  
 |  variance
 |      Returns the variance of the distribution.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __annotations__ = {'total_count': <class 'int'>}
 |  
 |  arg_constraints = {'logits': IndependentConstraint(Real(), 1), 'probs'...
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from torch.distributions.distribution.Distribution:
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  cdf(self, value)
 |      Returns the cumulative density/mass function evaluated at
 |      `value`.
 |      
 |      Args:
 |          value (Tensor):
 |  
 |  enumerate_support(self, expand=True)
 |      Returns tensor containing all values supported by a discrete
 |      distribution. The result will enumerate over dimension 0, so the shape
 |      of the result will be `(cardinality,) + batch_shape + event_shape`
 |      (where `event_shape = ()` for univariate distributions).
 |      
 |      Note that this enumerates over all batched tensors in lock-step
 |      `[[0, 0], [1, 1], ...]`. With `expand=False`, enumeration happens
 |      along dim 0, but with the remaining batch dimensions being
 |      singleton dimensions, `[[0], [1], ..`.
 |      
 |      To iterate over the full Cartesian product use
 |      `itertools.product(m.enumerate_support())`.
 |      
 |      Args:
 |          expand (bool): whether to expand the support over the
 |              batch dims to match the distribution's `batch_shape`.
 |      
 |      Returns:
 |          Tensor iterating over dimension 0.
 |  
 |  icdf(self, value)
 |      Returns the inverse cumulative density/mass function evaluated at
 |      `value`.
 |      
 |      Args:
 |          value (Tensor):
 |  
 |  perplexity(self)
 |      Returns perplexity of distribution, batched over batch_shape.
 |      
 |      Returns:
 |          Tensor of shape batch_shape.
 |  
 |  rsample(self, sample_shape=torch.Size([]))
 |      Generates a sample_shape shaped reparameterized sample or sample_shape
 |      shaped batch of reparameterized samples if the distribution parameters
 |      are batched.
 |  
 |  sample_n(self, n)
 |      Generates n samples or n batches of samples if the distribution
 |      parameters are batched.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods inherited from torch.distributions.distribution.Distribution:
 |  
 |  set_default_validate_args(value)
 |      Sets whether validation is enabled or disabled.
 |      
 |      The default behavior mimics Python's ``assert`` statement: validation
 |      is on by default, but is disabled if Python is run in optimized mode
 |      (via ``python -O``). Validation may be expensive, so you may want to
 |      disable it once a model is working.
 |      
 |      Args:
 |          value (bool): Whether to enable validation.
 |  
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from torch.distributions.distribution.Distribution:
 |  
 |  batch_shape
 |      Returns the shape over which parameters are batched.
 |  
 |  event_shape
 |      Returns the shape of a single sample (without batching).
 |  
 |  mode
 |      Returns the mode of the distribution.
 |  
 |  stddev
 |      Returns the standard deviation of the distribution.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from torch.distributions.distribution.Distribution:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from torch.distributions.distribution.Distribution:
 |  
 |  has_enumerate_support = False
 |  
 |  has_rsample = False

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

《动手学深度学习 Pytorch版》 2.7 查阅文档 的相关文章

  • MNIST、torchvision 中的输出和广播形状不匹配

    在 Torchvision 中使用 MNIST 数据集时出现以下错误 RuntimeError output with shape 1 28 28 doesn t match the broadcast shape 3 28 28 这是我的
  • Win10 64位上CUDA 12的PyTorch安装

    我需要在我的 PC 上安装 PyTorch 其 CUDA 版本 12 0 pytorch 2 的表 https i stack imgur com X13oS png in In 火炬网站 https pytorch org get sta
  • pytorch - “conv1d”在哪里实现?

    我想看看 conv1d 模块是如何实现的https pytorch org docs stable modules torch nn modules conv html Conv1d https pytorch org docs stabl
  • 如何检查 PyTorch 是否正在使用 GPU?

    如何检查 PyTorch 是否正在使用 GPU 这nvidia smi命令可以检测 GPU 活动 但我想直接从 Python 脚本内部检查它 这些功能应该有助于 gt gt gt import torch gt gt gt torch cu
  • 如何使用 torch.stack?

    我该如何使用torch stack将两个张量与形状堆叠a shape 2 3 4 and b shape 2 3 没有就地操作 堆叠需要相同数量的维度 一种方法是松开并堆叠 例如 a size 2 3 4 b size 2 3 b torc
  • pytorch通过易失性变量反向传播错误

    我试图通过多次向后传递迭代来运行它并在每个步骤更新输入 从而最小化相对于某个目标的一些输入 第一遍运行成功 但在第二遍时出现以下错误 RuntimeError element 0 of variables tuple is volatile
  • pytorch grad 在 .backward() 之后为 None

    我刚刚安装火炬 1 0 0 on Python 3 7 2 macOS 并尝试tutorial https pytorch org tutorials beginner blitz autograd tutorial html sphx g
  • torchvision.transforms.Normalize 是如何操作的?

    我不明白如何标准化Pytorch works 我想将平均值设置为0和标准差1跨越张量中的所有列x形状的 2 2 3 一个简单的例子 gt gt gt x torch tensor 1 2 3 4 5 6 7 8 9 10 11 12 gt
  • torch.mm、torch.matmul 和 torch.mul 有什么区别?

    阅读完 pytorch 文档后 我仍然需要帮助来理解之间的区别torch mm torch matmul and torch mul 由于我不完全理解它们 所以我无法简明地解释这一点 B torch tensor 1 1207 0 3137
  • 从打包序列中获取每个序列的最后一项

    我试图通过 GRU 放置打包和填充的序列 并检索每个序列最后一项的输出 当然我的意思不是 1项目 但实际上是最后一个 未填充的项目 我们预先知道序列的长度 因此应该很容易为每个序列提取length 1 item 我尝试了以下方法 impor
  • Blenderbot 微调

    我一直在尝试微调 HuggingFace 的对话模型 Blendebot 我已经尝试过官方拥抱脸网站上给出的传统方法 该方法要求我们使用 trainer train 方法来完成此操作 我使用 compile 方法尝试了它 我尝试过使用 Py
  • 如何更新 PyTorch 中神经网络的参数?

    假设我想将神经网络的所有参数相乘PyTorch 继承自的类的实例torch nn Module http pytorch org docs master nn html torch nn Module by 0 9 我该怎么做呢 Let n
  • 将 Keras (Tensorflow) 卷积神经网络转换为 PyTorch 卷积网络?

    Keras 和 PyTorch 使用不同的参数进行填充 Keras 需要输入字符串 而 PyTorch 使用数字 有什么区别 如何将一个转换为另一个 哪些代码在任一框架中获得相同的结果 PyTorch 还采用参数 in channels o
  • Pytorch 损失为 nan

    我正在尝试用 pytorch 编写我的第一个神经网络 不幸的是 当我想要得到损失时遇到了问题 出现以下错误信息 RuntimeError Function LogSoftmaxBackward0 returned nan values in
  • 预期设备类型为 cuda 的对象,但在 Pytorch 中获得了设备类型 cpu

    我有以下计算损失函数的代码 class MSE loss nn Module metric L1 L2 norms or cosine similarity mode training or evaluation mode def init
  • PyTorch 中的连接张量

    我有一个张量叫做data形状的 128 4 150 150 其中 128 是批量大小 4 是通道数 最后 2 个维度是高度和宽度 我有另一个张量叫做fake形状的 128 1 150 150 我想放弃最后一个list array从第 2 维
  • PyTorch 中的交叉熵

    交叉熵公式 但为什么下面给出loss 0 7437代替loss 0 since 1 log 1 0 import torch import torch nn as nn from torch autograd import Variable
  • 如何使用 pytorch 同时迭代两个数据加载器?

    我正在尝试实现一个接收两张图像的暹罗网络 我加载这些图像并创建两个单独的数据加载器 在我的循环中 我想同时遍历两个数据加载器 以便我可以在两个图像上训练网络 for i data in enumerate zip dataloaders1
  • 如何计算cifar10数据的平均值和标准差

    Pytorch 使用以下值作为 cifar10 数据的平均值和标准差 变换 Normalize 0 5 0 5 0 5 0 5 0 5 0 5 我需要理解计算背后的概念 因为这些数据是 3 通道图像 我不明白什么是相加的 什么是除什么的等等
  • Fine-Tuning DistilBertForSequenceClassification:不是学习,为什么loss没有变化?权重没有更新?

    我对 PyTorch 和 Huggingface transformers 比较陌生 并对此尝试了 DistillBertForSequenceClassificationKaggle 数据集 https www kaggle com c

随机推荐

  • UFT 小飞机测试

    1 1 新建GUI测试 1 2 录制 点击小红点或者菜单上的录制 任选一个 找到小飞机的文件地址 选择小飞机 地址可以参考我的目录 之后就点击确定 之后的每一步都要亲自用鼠标进行点击录制 包括下拉框的选择 选择好后点击Insert Orde
  • 集合的初始容量与扩容

    arraylist 0 50 linkedlist 0 链表每次加一 hashmap 16 加载因子0 75 超过容量的0 75才会进行扩容 扩容 容量的2倍 2 当某个桶的链表长度达到8 就转成红黑树
  • Java 常用的大算法详解

    Java 常用的大算法详解 排序算法是计算机科学中的重要主题之一 Java 提供了许多常用的排序算法 本文将详细介绍其中的几种 并提供相应的源代码实现 冒泡排序 Bubble Sort 冒泡排序是一种简单直观的排序算法 它重复地遍历待排序的
  • [LeetCode-100]-Same Tree(判断两颗二叉树是否相同)

    文章目录 0 题目相关 1 Solution 0 题目相关 题目解读 给定两颗二叉树 对这两颗二叉树进行比较 判断这两棵二叉树是否相同 原题描述 原题链接 Given two binary trees write a function to
  • @PostConstruct和线程池导致事务问题

    测试一个xxl job 遇到问题事务问题 情景再现 使用 PostConstruct注解来测试 由于是上传素材 比较耗时 所以使用了线程池 一切很顺利的是时候 保存日志的时候报了个错 org springframework transact
  • uniapp 上传音频(H5可以App不行),并播放后端返回的音频

    1 上传 record let this this uni chooseFile count 1 默认100 extension m4a mp3 根据文件拓展名过滤 每一项都不能是空字符串 默认不过滤 success function re
  • python爬虫环境准备-安装anaconda

    在windows环境下 比较头疼的就是包管理和Python不同版本的问题 为了解决这些问题 有不少发行版的Python 比如WinPython Anaconda等 这些发行版将python和许多常用的package打包 方便python开发
  • 华为OD机试 - 猜数字(Java)

    题目描述 一个人设定一组四码的数字作为谜底 另一方猜 每猜一个数 出数者就要根据这个数字给出提示 提示以XAYB形式呈现 直到猜中位置 其中X表示位置正确的数的个数 数字正确且位置正确 而Y表示数字正确而位置不对的数的个数 例如 当谜底为8
  • 将本地的代码上传到github完整版本

    1 注册github账号 2 安装git https git for windows github io 3 进入Github首页 点击New repository新建一个项目 Public Private 仓库权限 公开共享 私有或指定合
  • 1077 Kuchiguse

    PTA 程序设计类实验辅助教学平台 一个测试点没过 不知道哪的原因 include
  • 逍遥子突然辞去阿里一切职务!之前不再担任董事长,现在阿里云CEO也卸了

    金磊 发自 凹非寺量子位 公众号 QbitAI 阿里巴巴史上最大架构重组仅半年后 再次迎来重大变革 原集团CEO张勇 花名 逍遥子 正式卸任 同时辞去阿里云董事长和CEO职务 这一次 阿里巴巴掌门的接力棒交到了蔡崇信和吴泳铭 花名 东邪 手
  • dalle2:hierarchical text-conditional image generation with clip

    DALL E 2 论文精读 哔哩哔哩 bilibili更多论文 https github com mli paper reading 视频播放量 30350 弹幕量 256 点赞数 1767 投硬币枚数 1318 收藏人数 751 转发人数
  • Linux之编辑器强大的vim使用手册

    目录 vim三种模式 vim常用操作 环境参数配置 命令合集 方向命令 插入命令 定位命令 删除命令 复制和剪切命令 替换和取消命令 搜索和搜索替换命令 保存和退出命令 其他命令 使用技巧 把一个文件的内容导入当前文件中光标所在位置 定义快
  • swarm与kubernetes的对比

    前言 docker swarm 与kubernetes都是集群管理工具 一个是docker原生自带 一个是谷歌项目下的容器编排工具 那么到底他们到底有什么有缺点呢 kubernetes kubernetes 是Google多年大规模容器管理
  • Windows10如何添加开机启动项

    在日常生活中 偶尔要求其中的软件在开机时便能自动启动 比如MySQL一般被设置为自启动项 今天将为大家介绍window10中如何添加开机启动项 操作过程 1 按下win R调出运行窗口 并输入 shell startup 即可进入开机启动文
  • KPCA数据降维

    文章目录 效果一览 文章概述 部分源码 参考资料 效果一览 文章概述 KPCA数据降维 Matlab核主成分分析 数据降维 可直接运行 适合作为创新点 部分源码 清空环境变量 warning off 关闭报警信息 close all 关闭开
  • Java【多线程】笔记总结

    多线程 概念 方法间调用 普通方法调用 从哪里来就到那里去 闭合的一条路径 多线程调用 开辟了多条路径 在操作系统中运行的程序就是进程 如看视频 线程就是独立的执行路径 在程序运行时 即使没有自己创建线程 后台也会存在多个线程 如gc 线程
  • git本地仓库与远程仓库同步

    在学习和工作中 我们经常遇到这样的场景 我们已经在本地创建了一个git仓库 并添加了文件和修改记录 后面你又想在github或者gitlab上新建一个空白git仓库 并且让这2个仓库进行远程同步并且保存之前本地仓库的修改记录 这样一来git
  • Java 之 认识String类

    目录 一 String类的重要性 二 常用方法 1 字符串构造 2 String对象的比较 3 字符串查找 4 转化 5 字符串替换 6 字符串拆分 7 字符串截取 8 其他操作方法 9 字符串的不可变性 10 字符串修改 三 String
  • 《动手学深度学习 Pytorch版》 2.7 查阅文档

    2 7 1 查找模块中的所有函数和类 import torch 可以调用 dir 函数查询函数中有哪些模块和类 以 双下划线 开始和结束的函数是 Python 中的特殊对象 以 单下划线 开始的函数是内部函数 通常以上两种函数可以忽略 di