pytorch - 如何从张量中获取列?
问题描述
假设我有一个由 1 和 0 组成的张量,如下所示。如何获取特定列的索引以替换为新值?如果我想用 [3.,4.,5.,6.] 替换第 1 列的值,我该如何完成呢?
a = torch.tensor([[[1., 0., 0., 0.]],
[[0., 1., 0., 0.]],
[[1., 0., 0., 0.]],
[[0., 0., 0., 1.]],
[[1., 0., 0., 0.]],
[[0., 0., 0., 1.]],
[[1., 0., 0., 0.]]])
解决方案
考虑到这是一个 3D 张量,称它们为“列”有点棘手。
这将满足您的需要,将 'column' 1 设置为您提供的值。
a = torch.tensor([[[1., 0., 0., 0.]],
[[0., 1., 0., 0.]],
[[1., 0., 0., 0.]],
[[0., 0., 0., 1.]],
[[1., 0., 0., 0.]],
[[0., 0., 0., 1.]],
[[1., 0., 0., 0.]]])
# Change values in 'column' 1 (zero-indexed):
# The 0 is there because of the size-1 second dimension.
a[1, 0, :] = torch.tensor([3., 4., 5., 6.])
print(a)
# tensor([[[1., 0., 0., 0.]],
# [[3., 4., 5., 6.]],
# [[1., 0., 0., 0.]],
# [[0., 0., 0., 1.]],
# [[1., 0., 0., 0.]],
# [[0., 0., 0., 1.]],
# [[1., 0., 0., 0.]]])
推荐阅读
- git - 如何将提交还原为分支中的新提交
- amazon-web-services - 无法使用 .ebextensions 方法增加 client_max_body_size
- php - php - 更新内部的 foreach 变量
- snowflake-cloud-data-platform - 如何将暂存文件夹中的文件放入表中
- angular - 如何在 Angular 8 路由器中获取父参数
- python - 无法从评估的 lambda 函数中获取源代码
- python-3.x - Python Pandas 前向填充特定时间范围内的缺失数据
- python - 查找从一个版本到另一个版本的 pandas 方法更改的映射
- python - 如何将打印的值保存在 Excel 中?
- javascript - “webview”不是电子角度应用程序中的已知元素