How to create a tensor in Python

To define a multidimensional array (tensor) of size n in python, we can use the array method of NumPy.

numpy.array([M1,M2,...,Mn])

Alternatively, the Pytorch tensor method.

torch.tensor([M1,M2,...,Mn])

The arguments M1,M2,...,Mn are arrays of size n-1.

Both methods create a tensor of n dimensions.

What is a tensor? A tensor is a multidimensional array. For example, a three-dimensional tensor is a cubic matrix composed of 27 elements arranged in a three-dimensional vector space.

Example

Exercise 1 (numpy array)

Import the numpy library into python

import numpy as np

Create a 3x3x3 tensor with the array() function

The argument is a list of three square matrices 3x3

Y=np.array([[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]],[[19,20,21],[22,23,24],[25,26,27]]])

The output is a cubic matrix composed of three 3x3 square matrices.

In total, the tensor has 27 elements arranged in a three-dimensional space (x, y, z).

>>>Y
array([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],

[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]],

[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]])

To read the element with coordinates (2,1,0).

>>> Y[0,1,2]
6

Exercise 2 (torch tensor)

Import the torch module in python

import torch as th

Create a three-dimensional tensor by tensor() function.

The argument is a list of three square matrices 3x3 (two-dimensional array)

Y=th.tensor([[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]],[[19,20,21],[22,23,24],[25,26,27]]])

The tensor () function creates a three-dimensional array (tensor).

It's composed of 27 elements in a three-dimensional vector space.

>>> Y
tensor([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],

[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]],

[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]])

To read the element with coordinates (2,1,0).

>>> Y[2,1,0]
tensor(22)

https://how.okpedia.org/en/python/how-to-create-a-tensor-in-python

Report us an error or send a suggestion to improve this page

FAQ

Matrix in Python