You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于一维数组笛卡尔积创建配对类型Torch张量矩阵

解决方法

可以通过广播生成行列对比矩阵,直接基于条件赋值,实现更简洁高效,完全匹配需求:

import numpy as np
import torch

# 原数组
arr = np.array(['A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'])

# 将字符串映射为类别索引:A→0,B→1,C→2
_, idx = np.unique(arr, return_inverse=True)
idx = torch.tensor(idx)

# 生成行矩阵(8×1)和列矩阵(1×8),广播为8×8的行列对比矩阵
row = idx.unsqueeze(1)  # shape: (8,1)
col = idx.unsqueeze(0)  # shape: (1,8)

# 初始化全0结果张量
result = torch.zeros((8,8), dtype=torch.int32)

# 按条件赋值
result[(row == 0) & (col == 1)] = 1  # A→B的位置设1
result[(row == 1) & (col == 2)] = 2  # B→C的位置设2

print(result)

输出结果:

tensor([[0, 1, 1, 1, 0, 0, 0, 0],
        [0, 0, 0, 0, 2, 2, 2, 2],
        [0, 0, 0, 0, 2, 2, 2, 2],
        [0, 0, 0, 0, 2, 2, 2, 2],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]], dtype=torch.int32)

思路说明:

  1. 类别索引映射:先用np.unique把字符串转换成连续整数索引,方便后续条件判断;
  2. 广播构建对比矩阵:通过unsqueeze分别扩展行和列的维度,利用PyTorch的广播机制自动生成8×8的行列元素对比矩阵,避免了笛卡尔积的繁琐转换;
  3. 条件赋值:直接通过布尔索引定位目标位置,精准赋值1和2,其余位置保持初始的0,逻辑清晰直观,计算效率也更高。

内容的提问来源于stack exchange,提问作者Xaume

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:22:39