unbind
好的!我们来详细讲解 unbind(dim=1) 的作用,并通过示例代码展示它的具体用法。
unbind 详解
unbind(dim=n) 会沿着指定维度 n 进行拆分,并返回一个 元组,其中包含若干个 tensor。这些 tensor 是沿着该维度的切片,每个切片会 减少一个维度。
示例
假设你的 final_TCPConfidence 形状是 [16, 61, 2],其中:
16:表示batch_size61:表示ts_d(变量数)2:表示最终的logit或confidence值
你想遍历 ts_d=61 这个维度,获取 每个变量对应的 [16, 2] 张量。
代码
import torch
# 假设 final_TCPConfidence 是一个随机张量,形状为 [16, 61, 2]
final_TCPConfidence = torch.randn(16, 61, 2)
# 使用 unbind(dim=1) 沿着 ts_d 维度拆分,得到 61 个张量,每个形状为 [16, 2]
tsd_tensors = final_TCPConfidence.unbind(dim=1)
# 遍历 tsd_tensors,每个 ts_conf 形状都是 [16, 2]
for i, ts_conf in enumerate(tsd_tensors):
print(f"Variable {i}: Shape {ts_conf.shape}")
unbind(dim=1) 的作用
unbind(dim=1) 拆分 final_TCPConfidence,返回一个长度为 61(即 ts_d 数量)的 元组:
tsd_tensors = final_TCPConfidence.unbind(dim=1)
- 这个
tsd_tensors是 61 个[16, 2]的张量 组成的元组。 tsd_tensors[i]就是第i个变量的[16, 2]张量。
具体执行过程
假设 final_TCPConfidence 是:
Shape: [16, 61, 2]
unbind(dim=1) 的效果相当于把它 切成 61 份,每份形状为 [16, 2]:
final_TCPConfidence[:, 0, :] → Shape [16, 2] (变量 0)
final_TCPConfidence[:, 1, :] → Shape [16, 2] (变量 1)
final_TCPConfidence[:, 2, :] → Shape [16, 2] (变量 2)
...
final_TCPConfidence[:, 60, :] → Shape [16, 2] (变量 60)
因此,你可以直接用 enumerate(tsd_tensors) 遍历所有变量的 [16, 2] 张量。
打印示例
假设 final_TCPConfidence 是:
tensor([
[[0.1, 0.2], [0.3, 0.4], ..., [0.5, 0.6]], # batch 0
[[0.7, 0.8], [0.9, 1.0], ..., [1.1, 1.2]], # batch 1
...
[[1.3, 1.4], [1.5, 1.6], ..., [1.7, 1.8]] # batch 15
])
那么 unbind(dim=1) 拆分后,每个 ts_conf 是:
Variable 0: tensor([[0.1, 0.2], [0.7, 0.8], ..., [1.3, 1.4]]) # Shape [16, 2]
Variable 1: tensor([[0.3, 0.4], [0.9, 1.0], ..., [1.5, 1.6]]) # Shape [16, 2]
...
Variable 60: tensor([[0.5, 0.6], [1.1, 1.2], ..., [1.7, 1.8]]) # Shape [16, 2]
总结
unbind(dim=1)可以用于按ts_d变量数(61)拆分,得到 61 个形状[16, 2]的张量。- 使用
enumerate(unbind(dim=1))可以高效遍历所有ts_d变量对应的[16, 2]信息。
这就是 unbind 的详细用法,清晰吗?😃

浙公网安备 33010602011771号