最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Map each element of torch.Tensor with it's value in the dict - Stack Overflow

programmeradmin2浏览0评论

Suppose i have a tensor t consisting only zeros and ones:

t = torch.Tensor([1, 0, 0, 1])

And a dict with the weights:

weights = {0: 0.1, 1: 0.9}

I want to form a new tensor new_t, such that every element in tensor t is mapped to the corresponding value in the dict weights:

new_t = torch.Tensor([0.9, 0.1, 0.1, 0.9])

Is there an elegant way to do this without iterating over tensor t? I've heard about torch.apply, but it only works if tensor t is on the CPU, is there any other options?

Suppose i have a tensor t consisting only zeros and ones:

t = torch.Tensor([1, 0, 0, 1])

And a dict with the weights:

weights = {0: 0.1, 1: 0.9}

I want to form a new tensor new_t, such that every element in tensor t is mapped to the corresponding value in the dict weights:

new_t = torch.Tensor([0.9, 0.1, 0.1, 0.9])

Is there an elegant way to do this without iterating over tensor t? I've heard about torch.apply, but it only works if tensor t is on the CPU, is there any other options?

Share Improve this question edited Jan 30 at 16:24 onthebox asked Jan 30 at 15:57 ontheboxonthebox 154 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

If you convert your weights dict into a tensor, you can index directly

t = torch.tensor([1, 0, 0, 1])
weights = torch.tensor([0.1, 0.9])

new_t = weights[t]
new_t
>tensor([0.9000, 0.1000, 0.1000, 0.9000])
发布评论

评论列表(0)

  1. 暂无评论