​ torch.chunk(tensor, chunks, dim)​

torch.chunk函数用于将张量在指定维度上分割成多个块,chunks参数定义了块的数量。例如,将一个3x3的张量按列分成3块,会得到3个1x3的张量;按行分成2块,会得到2个3x2的张量。当块数为偶数且张量维度为奇数时,最后一块可能会包含多一列的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 torch.chunk(tensor, chunks, dim)

含义:在给定维度上对所给张量进行分块。

参数解释

  • Tensor         -- 要进行分快的张量
  • chunks        -- 分块个数
  • dim              -- 维度,按照此维度进行分块

如下代码:

import torch
x = torch.randn(3, 3)
x
tensor([[ 0.5149,  1.0009, -0.7242],
        [-0.9385, -0.1157, -1.6772],
        [ 1.0187, -2.3512,  1.0539]])


torch.chunk(x, 3, dim = 0)
(tensor([[ 0.5149,  1.0009, -0.7242]]),
 tensor([[-0.9385, -0.1157, -1.6772]]),
 tensor([[ 1.0187, -2.3512,  1.0539]]))


torch.chunk(x, 3, dim = 1)
(tensor([[ 0.5149],
         [-0.9385],
         [ 1.0187]]),
 tensor([[ 1.0009],
         [-0.1157],
         [-2.3512]]),
 tensor([[-0.7242],
         [-1.6772],
         [ 1.0539]]))


torch.chunk(x, 2, dim = 1)       # 注意当chunks为偶数时,而原始张量为所分维数为奇数时的变化
(tensor([[ 0.5149,  1.0009],
         [-0.9385, -0.1157],
         [ 1.0187, -2.3512]]),
 tensor([[-0.7242],
         [-1.6772],
         [ 1.0539]]))


# 另外也可以这么使用
x.chunk(2, dim = 1)
(tensor([[ 0.5149,  1.0009],
         [-0.9385, -0.1157],
         [ 1.0187, -2.3512]]),
 tensor([[-0.7242],
         [-1.6772],
         [ 1.0539]]))

### PyTorch 中 `torch.normal` 和 `torch.distributions` 的功能及用法 #### 功能概述 `torch.normal` 是用于生成服从正态分布的随机数的一个函数。而 `torch.distributions` 则是一个模块,提供了多种概率分布类及其相关操作的方法。 对于 `torch.distributions` 模块中的具体实现,比如 Gamma 分布可以通过如下方式创建: ```python from torch.distributions import Gamma concentration = torch.tensor([0.6], dtype=torch.float) rate = torch.tensor([3.0], dtype=torch.float) gamma_dist = Gamma(concentration, rate)[^2] ``` 上述代码展示了如何利用给定的浓度参数(shape parameter)和速率参数(rate parameter)来实例化一个Gamma对象。 而对于简单的正态分布采样需求,则可以使用更便捷的方式通过 `torch.normal` 函数完成: ```python import torch mean = 0. stddev = 1. samples = torch.normal(mean=mean, std=stddev, size=(1,)) print(samples) ``` 这段代码实现了从均值为 mean、标准差为 stddev 的正态分布中抽取样本并打印出来[^3]。 当涉及到复杂的统计计算时,如求解某个特定数值的概率密度或对数似然度(log probability),则推荐采用 `torch.distributions.Normal` 类来进行处理: ```python from torch.distributions import Normal mu = torch.tensor(0., dtype=torch.float) sigma = torch.tensor(1., dtype=torch.float) normal_distribution = Normal(mu, sigma) value_to_evaluate = torch.tensor(2.5, dtype=torch.float) probability_density_at_value = normal_distribution.log_prob(value_to_evaluate).exp() log_probability_of_sampled_data = normal_distribution.log_prob(normal_distribution.sample()) ``` 这里不仅演示了怎样获取指定位置处的概率密度估计值,还说明了如何评估所抽样的数据点对应的对数概率。 值得注意的是,在某些情况下可能会遇到额外项的存在影响最终的结果解释,例如公式 \( \frac{1}{2} + \frac{\pi}{2} + log(\sigma)\) 可能会出现在一些具体的上下文中作为调整因子或其他目的的一部分[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值