user4061624
user4061624

Reputation:

How to update a Tensor?

I've had some troubles updating a tensor using a previous one. My problem: let's suppose that I have a tensor x1 [Nx1] and a new one calculated through the previous, x2 [Nx1]. Now I want to update the elements of x2 that are less than x1. I'm using dtype=torch.cuda.FloatTensor.

This is the straight code in Python:

import numpy as np
...
index     = np.where(x1 > x2)
x2[index] = x1[index]

Why can I do this using PyTorch with dtype=torch.cuda.FloatTensor? And if the x1 change to [NxD]

Thank you!

Upvotes: 0

Views: 3020

Answers (1)

Manuel Lagunas
Manuel Lagunas

Reputation: 2751

The code looks really similar to numpy:

idx = (x1 > x2)
x2[idx] = x1[idx]

Using some predefined arrays and printing x2:

x1 = torch.from_numpy(np.array([1, 2, 3, 4, 5])).float().cuda()
x2 = torch.from_numpy(np.array([3, 3, 3, 3, 3])).float().cuda()

3 3 3 4 5 [torch.cuda.FloatTensor of size 5 (GPU 0)]

Code would be the same for NxN dimensional tensors. Using:

x1 = torch.from_numpy(np.array([[1, 2, 5], [1, 4, 5]])).float().cuda()
x2 = torch.from_numpy(np.array([[3, 3, 3], [3, 3, 3]])).float().cuda()

3 3 5
3 4 5 [torch.cuda.FloatTensor of size 2x3 (GPU 0)]

Upvotes: 2

Related Questions