Runoob Tutorial ArchiveEnglish

Data Shapes — Scalar, Vector, Matrix, Tensor

Data Shapes -- Scalar, Vector, Matrix, Tensor

In the world of AI, all data—whether it's an image, a piece of text, or a piece of audio—is ultimately organized into a unified form: a Tensor.

Tensor is a general term; it has different names depending on its dimensions.

From Zero-Dimensional to Multi-Dimensional: Layered Data Structures

Scalar

26

0D: A single number

No coordinate positioning

Vector

[22, 23, 24, 26]

1D: an ordered sequence of numbers

1 coordinate: which one?

Matrix

2D table

2D: a table composed of rows and columns

Two coordinates: which row? which column?

Tensor

Data cube

3D and above: stacking multiple tables

Locating a number with 3+ coordinates

Another way to understand it is "nesting"—a scalar is innermost, wrapping it in another layer makes it a vector, wrapping it again makes it a matrix, and continuing to wrap makes it a higher-dimensional tensor.

Tensor: a stack of tables

Matrix: a single table

Vector: a row of numbers

Scalar: a single number

In deep learning frameworks like PyTorch and TensorFlow, all data is uniformly represented by a "Tensor".

A scalar is a 0-dimensional tensor, a vector is a 1-dimensional tensor, and a matrix is a 2-dimensional tensor—they are special cases of tensors.

Understanding data shape with Dimensions

Scalar (0-dimensional)

is just a single number. For example, a temperature of 26°C. In NumPy, the shape is displayed as an empty tuple().

Vector (1D)

An ordered sequence of numbers. For example, hourly temperature records for a day. Shape is(n,), where n is the number of elements.

Matrix (2D)

A table with rows and columns. For example, a temperature table for seven days in a week, with 24 hours per day. Shape is(行数, 列数).

Tensor (3D and higher)

Stacked multi-layer data. For example, temperature for 300 cities across the country, 7 days per city per week, and 24 hours per day. Shape is(城市数, 天数, 小时数)That is(300, 7, 24).

Dimension can be simply understood as: how many "coordinates" you need to lock down a specific number.


Life example

Below, we use a progressive scenario to consolidate understanding.

**Scenario one: Recording the current temperature

You only need to write one number:26This is a scalar. It has no dimension, just a single value.

**Scenario two: recording daily temperature changes

You measure it once every hour from morning to night, getting 24 numbers:[22, 23, 24, 26, 28, ...].

This is a vector. You need a coordinate (which hour) to locate a specific temperature value.

**Scenario three: recording weekly temperature

You arrange the seven days of data into a table: each row is a day, and each column is an hour.

This is a 7-row, 24-column matrix. You need two coordinates (which day, which hour) to locate.

**Scenario Four: Recording the temperature of cities across the country

There are 300 cities nationwide, and each city has a 7x24 table.

These 300 tables stacked together form a 3D tensor. You need three coordinates (which city, which day, which hour).


Mathematical definition

Scalar

A scalar is a single number, denoted as ( a = 26 ), or ( x \in \mathbb{R} ) (x belongs to the set of real numbers).

Vector

A vector is an ordered set of numbers, usually written vertically (column vector):

[ \mathbf{v} = \begin{bmatrix} v_1 \ v_2 \ \vdots \ v_n \end{bmatrix} \in \mathbb{R}^{n} ]

( \mathbb{R}^{n} ) indicates that this is an n-dimensional real vector, ( v_1 ) is the first component, and ( v_n ) is the n-th component.

Matrix

A matrix is a rectangular array with m rows and n columns:

[ \mathbf{A} = \begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \ a_{21} & a_{22} & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \ a_{m1} & a_{m2} & \cdots & a_{mn} \end{bmatrix} \in \mathbb{R}^{m \times n} ]

Denoted as an m×n matrix (m rows and n columns), where ( a_{ij} ) represents the element in the i-th row and j-th column.

Tensor

A tensor is a generalization of vectors and matrices to arbitrary dimensions.

The shape of a k-dimensional tensor is denoted as ( (d_1, d_2, \dots, d_k) ), containing a total of ( d_1 \times d_2 \times \cdots \times d_k ) elements.

Comparison quick reference

Name Dimension Shape example Coordinate number Mathematical symbol
Scalar 0 () 0 ( x \in \mathbb{R} )
Vector 1 (n,) 1 ( \mathbf{v} \in \mathbb{R}^{n} )
Matrix 2 (m, n) 2 ( \mathbf{A} \in \mathbb{R}^{m \times n} )
3D tensor 3 (d1, d2, d3) 3 ( \mathcal{T} \in \mathbb{R}^{d_1 \times d_2 \times d_3} )

Python Hands-on

Below, we use NumPy to create and view these data structures. The shape attribute is key to understanding data dimensions.

Instance

import

numpy

as

np

Scalar (0-dimensional tensor): shape = ()

scalar

=

np.

array

(

26

)

Vector (1D tensor): shape = (n,)

vector

=

np.

array

(

[

22

,

23

,

24

,

26

,

28

,

30

,

31

,

29

]

)

Matrix (2D tensor): shape = (number of rows, number of columns)

matrix

=

np.

array

(

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

]

)

3D tensor: shape = (number of layers, number of rows, number of columns)

tensor_3d

=

np.

array

(

[

[

[

1

,

2

,

3

]

,

[

4

,

5

,

6

]

]

,

[

[

7

,

8

,

9

]

,

[

10

,

11

,

12

]

]

]

)

4D tensor: simulating 3 single-channel 2x2 pixel images

batch_images

=

np.

array

(

[

   

[

[

[

10

]

,

[

20

]

]

,

[

[

30

]

,

[

40

]

]

]

,

   

[

[

[

50

]

,

[

60

]

]

,

[

[

70

]

,

[

80

]

]

]

,

   

[

[

[

90

]

,

[

100

]

]

,

[

[

110

]

,

[

120

]

]

]

]

)

print

(

scalar: shape="

,

scalar.

shape

,

" ndim="

,

scalar.

ndim

)

print

(

"Vector: shape="

,

vector.

shape

,

" ndim="

,

vector.

ndim

)

print

(

"matrix: shape="

,

matrix.

shape

,

" ndim="

,

matrix.

ndim

)

print

(

"3D tensor: shape="

,

tensor_3d.

shape

,

" ndim="

,

tensor_3d.

ndim

)

print

(

"4D tensor: shape="

,

batch_images.

shape

,

" ndim="

,

batch_images.

ndim

)

Runtime output:

Original prompt (Chinese, left untranslated)



标量:    shape= ()        ndim= 0

向量:    shape= (8,)      ndim= 1

矩阵:    shape= (2, 3)    ndim= 2

3D 张量: shape= (2, 2, 3) ndim= 3

4D 张量: shape= (3, 2, 2, 1) ndim= 4

Rules of the Shape attribute

Attribute Meaning Scalar Vector (8 elements) Matrix (2x3) 3D (2x2x3)
.shape Size of each dimension () (8,) (2, 3) (2, 2, 3)
.ndim Number of dimensions = len(shape) 0 1 2 3
.size Total number of elements 1 8 6 12

When debugging deep learning code and encountering a shape mismatch error, the first step is to print the shape to check the data dimensions.

Understanding shape is the first skill when learning NumPy and all deep learning frameworks.


3D Tensor Visualization

Below, a 3x3x3 tensor is drawn as 27 points in space: three coordinate axes correspond to "row, column, channel," and the color intensity of each point represents the magnitude of the value at that position. You can rotate the view by dragging the mouse.

Spatial distribution of a 3x3x3 tensor · Brighter color represents a larger value

Note the observation: keeping the "channel" layer fixed, you will see a 3x3 plane—that is a second-order tensor (matrix). This is why we say "a matrix is a special case of a tensor."


Application scenarios in AI

Image Classification: From 3D to 4D Tensors

In ImageNet classification tasks, input images are uniformly resized to 224×224 pixels. A single color image is a 3D tensor with shape(224, 224, 3).

During actual training, the GPU processes one batch at a time (e.g., 32 images), and the data becomes a 4D tensor(32, 224, 224, 3).

Note that different frameworks have different conventions for channel placement: TensorFlow/Keras uses(N, H, W, C)(channels last), while PyTorch uses(N, C, H, W)(channels first).

When you see the error "shape mismatch: (32, 224, 224, 3) vs (32, 3, 224, 224)", it is caused by an inconsistent channel position—you can fix it by using.permute()or.transpose()making adjustments.

Natural Language Processing: Embedding Matrix

The vocabulary size of the BERT model is 30522, and the hidden dimension is 768. Its word embedding matrix shape is(30522, 768)—each row is a 768-dimensional vector for a word.

The GPT series is similar: GPT-2 has a vocabulary of 50257, with embedding dimensions ranging from 768 (small model) to 1600 (large model).

When you input a piece of text, the model first looks up the table to convert each word ID into its corresponding embedding vector; this is "lookup by row"—a matrix indexing operation.

Fully connected layer: The core role of matrix multiplication

A classic MNIST handwritten digit recognition network: Input is 784 dimensions (28x28 pixels flattened), the first hidden layer is 256 dimensions.

The shape of the weight matrix W₁ is(256, 784). Each forward pass calculatesh = W₁ @ x, which is a 256x784 matrix multiplication with a 784-dimensional vector.

The forward propagation of the entire neural network is essentially an alternation of matrix multiplications and activation functions layer by layer.

Video data: 5D tensor

Video can be understood as a sequence of multiple image frames. A 16-frame 224x224 color video clip has a shape of(16, 224, 224, 3).

Becomes a 5D tensor after adding the batch dimension(8, 16, 224, 224, 3)This is the standard input for video classification models (such as 3D-ResNet).