Artificial Intelligence • Programming and Computational Foundations • 13 min read

NumPy, Arrays, and Tensors

Artificial intelligence works extensively with numerical data. A dataset may contain thousands of rows, an image may contain millions of pixel values, and a neural network may process many examples at once. Efficiently representing and manipulating these values is a basic skill for AI development.

NumPy is a Python library for numerical computing. Its main data structure, the ndarray, stores elements in a multidimensional array and supports operations on entire collections of values. A tensor, in the broad mathematical and machine-learning sense, is a multidimensional arrangement of values with an associated shape. NumPy arrays can represent such arrangements, while libraries such as PyTorch provide tensors with additional capabilities used for neural-network training.

This article builds on Python for Artificial Intelligence and the mathematical ideas introduced in Vectors and Matrices.

First intuition: a spreadsheet becomes numbers

Imagine five students taking three quizzes. A Python list can store one student’s three scores, but a two-dimensional array can store all fifteen scores at once. Each row represents a student and each column represents a quiz. This is the same arrangement that many machine-learning algorithms expect: examples by features.

import numpy as np

scores = np.array([[70, 80, 90], [65, 75, 85], [90, 88, 92], [50, 65, 70], [78, 82, 84]])
print(scores.shape)        # (5, 3): five students, three quizzes
print(scores.mean(axis=0)) # average score for each quiz
print(scores.mean(axis=1)) # average score for each student

The shape tells us how values are organized, and the axis tells NumPy which dimension an operation acts across. Understanding these two ideas prevents many errors in later neural-network code. The rest of this article develops the underlying rules and extends them to arrays with more dimensions.

From scalars to multidimensional arrays

The number of axes in an array is its number of dimensions, sometimes called its rank in programming libraries. This use of rank is different from matrix rank in linear algebra, which measures linear independence.

RepresentationExample shapeInterpretation
Scalar (0-D)()One numerical value
Vector (1-D)(4,)Four values along one axis
Matrix (2-D)(3, 4)Three rows, four columns
3-D array(2, 3, 4)Two matrices, each with three rows and four columns
Higher-dimensional array(8, 28, 28, 1)A batch of eight grayscale images, using height-width-channel ordering

An array’s shape gives the size of every axis. Its size is the total number of elements, equal to the product of its shape dimensions. Its data type, or dtype, describes the type used to store its elements.

A scalar, one-dimensional vector, two-dimensional matrix, and stack of matrices representing a three-dimensional array.
Each additional axis lets an array represent another dimension of organization, such as multiple examples in a batch.

Why NumPy matters in AI

Ordinary Python lists are useful for general programming, but a list does not automatically behave like a mathematical vector or matrix. NumPy arrays support numerical computation with compact storage and optimized operations that often avoid explicit Python-level loops.

For example, Python list addition concatenates lists, whereas NumPy array addition performs elementwise addition:

import numpy as np

python_a = [1, 2, 3]
python_b = [4, 5, 6]
print(python_a + python_b)  # [1, 2, 3, 4, 5, 6]

array_a = np.array([1, 2, 3])
array_b = np.array([4, 5, 6])
print(array_a + array_b)    # [5 7 9]

This difference matters. NumPy lets code express mathematical operations directly, but it does not remove the need to check whether those operations have the intended meaning.

Creating arrays and inspecting their properties

Install NumPy in your Python environment with:

python -m pip install numpy

Then create arrays from sequences or built-in constructors:

import numpy as np

scores = np.array([82, 91, 76, 88])
features = np.array([
    [170, 65],
    [162, 58],
    [180, 78],
])

print(scores.shape)     # (4,)
print(scores.ndim)      # 1
print(scores.size)      # 4
print(features.shape)   # (3, 2)
print(features.ndim)    # 2
print(features.size)    # 6
print(features.dtype)   # Integer dtype; exact width is platform-dependent

zeros = np.zeros((2, 3))
ones = np.ones((2, 3))
sequence = np.arange(0, 10, 2)
spacing = np.linspace(0.0, 1.0, 5)

The shape (3, 2) means three samples with two features each if the rows represent samples. Array shapes do not inherently carry that meaning; the programmer or library must establish the axis convention.

Data types and numerical precision

Common numerical dtypes include int32, int64, float32, and float64. The dtype affects the range of representable values, memory use, and numerical precision. For many ML systems, float32 is common, although different devices and models may use lower or higher precision.

weights = np.array([0.1, 0.2, 0.3], dtype=np.float32)
print(weights.dtype)   # float32
print(weights.itemsize)  # 4 bytes per element

Explicitly choosing a dtype can improve consistency, but converting to a narrower dtype may lose information. Integer overflow and floating-point rounding are genuine constraints, not programming bugs that can be ignored.

Indexing, slicing, and selecting data

NumPy uses zero-based indexing. For two-dimensional arrays, the first index selects a row and the second selects a column.

import numpy as np

x = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90],
])

print(x[0, 1])   # 20
print(x[1])      # [40 50 60]
print(x[:, 0])   # [10 40 70] (first column)
print(x[0:2, 1:3])
# [[20 30]
#  [50 60]]

print(x[x >= 50])  # [50 60 70 80 90]

A slice selects a range of positions. A Boolean mask selects elements satisfying a condition. Such selection is useful for filtering data and identifying invalid values.

An important distinction: basic slicing typically returns a view, so modifying the result may change the original array. Advanced indexing, including Boolean indexing, generally returns a copy. Use .copy() when you require independent data.

original = np.array([1, 2, 3, 4])
view = original[1:3]
view[0] = 99
print(original)  # [ 1 99  3  4]

independent = original[1:3].copy()
independent[0] = 0
print(original)  # Unchanged by the last assignment

Elementwise operations and vectorization

Vectorization means expressing operations on entire arrays rather than writing a separate Python loop for each element. Many NumPy operations execute their core work in optimized compiled code.

measurements = np.array([5.0, 7.0, 9.0])

print(measurements + 2)  # [ 7.  9. 11.]
print(measurements * 3)  # [15. 21. 27.]
print(measurements ** 2) # [25. 49. 81.]
print(np.sqrt(measurements))

Addition, multiplication, and exponentiation in these examples operate element by element. That does not mean * is matrix multiplication. For matrices, * performs elementwise multiplication; @ performs matrix multiplication.

Broadcasting

Broadcasting is NumPy’s method for applying elementwise operations to arrays with compatible shapes, sometimes without physically copying the smaller array.

Two dimensions are compatible when they are equal or one of them is 1. NumPy compares shapes from right to left; missing leading dimensions are treated as 1.

samples = np.array([
    [1.0, 2.0, 3.0],
    [4.0, 5.0, 6.0],
])                           # shape (2, 3)

bias = np.array([0.1, 0.2, 0.3])  # shape (3,)
result = samples + bias

print(result)
# [[1.1 2.2 3.3]
#  [4.1 5.2 6.3]]

Conceptually, the same three-element bias vector is added to every row. This resembles how a neural-network layer applies a learned bias across a batch.

Broadcasting a three-element bias vector across two rows of a matrix.
Broadcasting aligns compatible dimensions; it does not mean arbitrary arrays can be combined.

For example, adding arrays shaped (2, 3) and (2,) fails because the final dimensions, 3 and 2, do not match and neither is 1. Broadcasting errors are often shape-design errors.

Reshaping and changing axes

The shape tells NumPy how to interpret the arrangement of elements. Reshaping changes this arrangement without changing the total number of elements.

values = np.arange(12)
grid = values.reshape(3, 4)
print(grid.shape)       # (3, 4)

batch = grid.reshape(2, 2, 3)
print(batch.shape)      # (2, 2, 3)

flattened = grid.reshape(-1)
print(flattened.shape)  # (12,)

The placeholder -1 asks NumPy to infer one dimension from the element count. Reshaping a twelve-element array into (5, 3) is impossible because that shape would need fifteen values.

A transpose permutes axes. For a matrix, .T swaps rows and columns:

matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.shape)    # (2, 3)
print(matrix.T.shape)  # (3, 2)

Reshaping and transposing are different operations. A transpose changes which axis represents rows or columns; a reshape rearranges the interpretation of element positions in the array’s traversal order. See Vector and Matrix Operations for the related linear algebra.

Reductions and axes

A reduction combines multiple values into fewer values, for example by calculating a sum or mean. Specifying axis determines which dimension is reduced.

scores = np.array([
    [80, 90, 70],
    [60, 75, 95],
])

print(scores.mean())        # 78.33333333333333
print(scores.mean(axis=0))  # [70.  82.5 82.5] (column means)
print(scores.mean(axis=1))  # [80.         76.66666667] (row means)
print(scores.sum(axis=0))   # [140 165 165]

Here rows are students and columns are subjects. axis=0 collapses the student dimension and retains one result per subject; axis=1 collapses the subject dimension and retains one result per student.

Other common reductions include np.min, np.max, np.std, np.argmin, and np.argmax. Always check whether a function returns a value, an index, or an array of values.

Dot products and matrix multiplication

The dot product combines two vectors of equal length into a scalar:

a⋅b=∑i=1naibi.\mathbf{a}\cdot\mathbf{b}=\sum_{i=1}^{n}a_ib_i.

For example:

inputs = np.array([2.0, 3.0, 4.0])
weights = np.array([0.5, -1.0, 2.0])

score = inputs @ weights
print(score)  # 6.0

The result is (2)(0.5)+(3)(−1)+(4)(2)=6(2)(0.5)+(3)(-1)+(4)(2)=6.

For matrices AA of shape (m,n)(m,n) and BB of shape (n,p)(n,p), the product ABAB has shape (m,p)(m,p):

(AB)ij=∑k=1nAikBkj.(AB)_{ij}=\sum_{k=1}^{n}A_{ik}B_{kj}.

This operation is central to neural networks. Suppose X contains four examples, each with three features, and W contains three weights per output for two outputs:

X = np.array([
    [1.0, 2.0, 3.0],
    [4.0, 5.0, 6.0],
    [7.0, 8.0, 9.0],
    [2.0, 1.0, 0.0],
])                  # (4, 3)
W = np.ones((3, 2))  # (3, 2)
b = np.array([0.5, -0.5])  # (2,)

output = X @ W + b
print(output.shape)  # (4, 2)
print(output[0])    # [6.5 5.5]

The matrix multiplication produces a value for each example and output. Broadcasting then adds the bias vector to each row. This is a basic affine transformation used in dense neural-network layers, before an optional activation function is applied.

How tensors relate to NumPy arrays

In machine learning, the word tensor is often used for multidimensional numerical data, including scalars, vectors, matrices, and higher-dimensional arrays. Strictly speaking, mathematical tensors have additional transformation properties; in practical ML discussions the term commonly refers to the multidimensional array representation.

FeatureNumPy ndarrayPyTorch tensor
Multidimensional numerical dataYesYes
Array shapes and broadcastingYesYes
CPU operationsYesYes
Accelerator executionNot part of the ordinary NumPy ndarray interfaceSupported on compatible devices
Automatic differentiation for model trainingNot provided by NumPy itselfAvailable through autograd for supported operations

For example, a tensor shaped (32, 3, 224, 224) might represent a batch of 32 images with 3 color channels and spatial dimensions of 224 by 224, using the NCHW convention. Other libraries and workflows use NHWC, with channels last. Neither shape can be interpreted correctly without knowing the axis convention.

NumPy is an excellent place to learn shape reasoning, array computation, and linear algebra before working with deep-learning frameworks.

Worked example: standardizing numerical features

Consider three observations with two features. The first feature is measured on a larger numerical scale than the second:

import numpy as np

X = np.array([
    [10.0, 100.0],
    [20.0, 200.0],
    [30.0, 300.0],
])

means = X.mean(axis=0)
stds = X.std(axis=0)

X_scaled = (X - means) / stds

print(means)    # [ 20. 200.]
print(stds)     # [ 8.16496581 81.64965809]
print(np.round(X_scaled, 3))
# [[-1.225 -1.225]
#  [ 0.     0.   ]
#  [ 1.225  1.225]]

The transformation is applied separately to each feature:

zij=xij−μjσj.z_{ij}=\frac{x_{ij}-\mu_j}{\sigma_j}.

Here μj\mu_j is the mean of feature jj and σj\sigma_j is its standard deviation. Broadcasting makes it possible to subtract the feature means and divide by the feature standard deviations without writing loops.

Two practical safeguards:

  1. If a feature has zero standard deviation, division by zero must be handled, for example by leaving that feature unchanged or removing it when appropriate.
  2. In a real supervised-learning workflow, calculate the means and standard deviations from the training set only, then reuse those training statistics for validation, test, and future examples. Computing statistics from the full dataset before splitting can cause data leakage.

See Feature Engineering, Encoding, and Scaling and Data Splitting, Labeling, and Leakage for those steps in context.

Common mistakes and limitations

  • Confusing elementwise and matrix multiplication: A * B and A @ B have different meanings.
  • Ignoring axis conventions: A shape such as (100, 28, 28) is not meaningful until the axis roles are known.
  • Unexpected broadcasting: An operation may succeed but align dimensions differently than intended. Inspect intermediate shapes.
  • Changing a view unintentionally: Basic slices may share memory with the original array.
  • Assuming floating-point arithmetic is exact: Rounding and precision differences can affect results.
  • Ignoring memory cost: Large arrays and intermediate results may use substantial RAM. Vectorization is not automatically memory-efficient for every problem.
  • Using NumPy instead of a training framework without considering requirements: NumPy alone does not provide an automatic differentiation system for modern neural-network training.

Check your understanding

  1. What is the difference between the shape (5,) and (5, 1)?
  2. If X.shape == (100, 4) and w.shape == (4,), what is the shape of X @ w?
  3. Why can an array of shape (3, 4) be added to an array of shape (4,), but not one of shape (3,)?
  4. What does axis=0 mean when computing the mean of a 2-D dataset with samples in rows?
  5. Why must feature-scaling statistics be calculated using only training examples?
Show worked answers
  1. (5,) has one axis with five elements; (5, 1) has two axes, five rows and one column. These shapes may behave differently under broadcasting and matrix multiplication.
  2. (100,): each of the 100 rows is combined with the four weights to produce one value.
  3. Broadcasting matches dimensions from the right. (4,) matches the last dimension of (3, 4), but (3,) does not.
  4. It reduces the row/sample axis, leaving one mean per column/feature.
  5. Statistics from validation or test data would reveal information that should be unavailable during model development, leading to data leakage and misleading evaluation.

References and further reading

Related articles in

Image preview

Fit