PyTorch Tensor Assignment With Different Dimension: An Introduction – PyTorch Tutorial

By | May 5, 2022

Tensor assignment is common operation in pytorch, in this tutorial, we will use some examples to show you some useful tips for it.

Tensor assignment with induce

We can change the value of a tensor by element index.

For example:

import torch

x = torch.randn((4,4))
print(x)
x[0][1] = 1.0
print(x)

In this code, we will change the value of x[0][1] by its index [0][1]

Run this code, we will get:

tensor([[-1.1796, -1.5611,  0.7719,  1.3305],
        [ 0.7196, -2.0247, -0.2770,  0.0850],
        [-0.3170,  0.5208,  1.0010,  0.2459],
        [ 1.0589, -0.4917,  0.6044, -0.2896]])
tensor([[-1.1796,  1.0000,  0.7719,  1.3305],
        [ 0.7196, -2.0247, -0.2770,  0.0850],
        [-0.3170,  0.5208,  1.0010,  0.2459],
        [ 1.0589, -0.4917,  0.6044, -0.2896]])

We can find x[0][1] is modified.

Tensor assignment with induce

Tensor assignment with dimension

We also can change value of some elements in a tensor with one step.

For example:

import torch

x = torch.randn((4,4))
print(x)
x[1] = torch.tensor([1.0, 2.0, 3.0, 4.0])
print(x)

Run this code, we will see:

tensor([[-0.2586,  0.0762, -0.1772, -0.7537],
        [-0.8662,  0.1238,  1.5165,  0.2657],
        [ 0.8116,  1.5711, -0.1200,  1.4773],
        [ 1.0380,  0.4567,  0.6346, -0.0553]])
tensor([[-0.2586,  0.0762, -0.1772, -0.7537],
        [ 1.0000,  2.0000,  3.0000,  4.0000],
        [ 0.8116,  1.5711, -0.1200,  1.4773],
        [ 1.0380,  0.4567,  0.6346, -0.0553]])

The value of 4 elements x[1][0], x[1][1], x[1][2], x[1][3] are changed.

Tensor assignment with dimension

We also can change some elements values with more dimensions.

For example:

import torch

x = torch.randn((4,4))
print(x)
x[:,:3] = torch.rand((4,3))
print(x)

Run this code, we will get:

tensor([[-0.1115,  1.9321,  1.1295, -0.4853],
        [-1.4261,  0.0057,  1.5695, -0.5299],
        [ 0.2769,  1.2843, -0.6458, -0.1931],
        [-0.0881, -0.3809, -1.6388, -2.0469]])
tensor([[ 0.3011,  0.0573,  0.7376, -0.4853],
        [ 0.8213,  0.9051,  0.1921, -0.5299],
        [ 0.8075,  0.9165,  0.2625, -0.1931],
        [ 0.1846,  0.1207,  0.1634, -2.0469]])

Here we will update elements values on 3 dimensions.

Tensor assignment with more dimensions

Leave a Reply