如何从张量中获取一列? [英] How to get a column from a tensor?

查看:82
本文介绍了如何从张量中获取一列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个由 1 和 0 组成的张量,如下所示.如何获取特定列的索引以替换新值?如果我想用 [3.,4.,5.,6.] 替换第 1 列的值,我该如何实现?

Let's say I have a tensor consisting of 1 and 0's as shown below. How can I get the index of a specific column to replace with new values ? If I want to replace the values of column 1 with the [3.,4.,5.,6.], how do I accomplish this ?

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 张量.

Calling them 'columns' is a bit tricky, given that this is a 3D tensor.

这将满足您的需求,将列"1 设置为您提供的值.

This will do what you need, setting 'column' 1 to the values you gave.

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.]]])

这篇关于如何从张量中获取一列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆