# 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([M _{1},M_{2},...,M_{n}])**

Alternatively, the Pytorch tensor method.

**torch.tensor([M _{1},M_{2},...,M_{n}])**

The arguments M_{1},M_{2},...,M_{n} 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)

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

__FAQ__