NumPy Arithmetic Operations for Machine Learning
Master NumPy arithmetic operations for efficient array computations in machine learning and AI. Explore element-wise operations and broadcasting.
NumPy Arithmetic Operations
NumPy, the fundamental package for numerical computation in Python, simplifies arithmetic operations on arrays by enabling element-wise computation. This means you can apply operations like addition, subtraction, multiplication, and division directly between arrays of the same or compatible shapes. When shapes differ, NumPy's broadcasting mechanism handles the transformations automatically.
Basic Arithmetic Operations
NumPy allows for intuitive element-wise arithmetic operations directly using standard Python operators.
1. Addition (+
)
Element-wise addition. When arrays have the same shape, corresponding elements are added together.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = a + b
print(result)
Output:
[5 7 9]
2. Subtraction (-
)
Element-wise subtraction.
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
result = a - b
print(result)
Output:
[ 9 18 27]
3. Multiplication (*
)
Element-wise multiplication.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = a * b
print(result)
Output:
[ 4 10 18]
4. Division (/
)
Element-wise division.
a = np.array([10, 20, 30])
b = np.array([1, 2, 5])
result = a / b
print(result)
Output:
[10. 10. 6.]
5. Power Operation (**
or np.power()
)
Element-wise exponentiation.
Using the **
operator:
a = np.array([2, 3, 4])
b = np.array([1, 2, 3])
result = a ** b
print(result)
Output:
[ 2 9 64]
Using np.power()
:
a = np.array([10, 100, 1000])
print(np.power(a, 2))
b = np.array([1, 2, 3])
print(np.power(a, b))
Output:
[ 100 10000 1000000]
[ 10 10000 1000000000]
Advanced Arithmetic Operations
NumPy provides additional functions for more specific arithmetic computations.
6. Modulo Operation (%
or np.mod()
, np.remainder()
)
Element-wise modulo operation, which returns the remainder of the division.
Using the %
operator:
a = np.array([10, 20, 30])
b = np.array([3, 7, 8])
result = a % b
print(result)
Output:
[1 6 6]
Using np.mod()
and np.remainder()
:
a = np.array([10, 20, 30])
b = np.array([3, 5, 7])
print(np.mod(a, b))
print(np.remainder(a, b))
Output:
[1 0 2]
[1 0 2]
Note: np.mod()
and np.remainder()
behave identically for positive divisors.
7. Floor Division (//
)
Element-wise floor division, which returns the quotient of the division, discarding any fractional part.
a = np.array([10, 20, 30])
b = np.array([3, 7, 8])
result = a // b
print(result)
Output:
[3 2 3]
Broadcasting in Arithmetic Operations
Broadcasting is a powerful mechanism that allows NumPy to perform arithmetic operations on arrays of different shapes. When operating on arrays with different shapes, NumPy attempts to "broadcast" the smaller array across the larger array so that they have compatible shapes for element-wise operations.
Scalar with Array
When an array is operated on with a scalar, the scalar is effectively broadcast to match the shape of the array, and the operation is applied element-wise.
a = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 10
result = a + scalar
print(result)
Output:
[[11 12 13]
[14 15 16]]
Arrays with Different Shapes
Broadcasting rules apply when arrays have different dimensions or sizes. For broadcasting to occur, the shape of the smaller array must be compatible with the shape of the larger array. Compatibility means that for each dimension, either the sizes are equal, or one of the sizes is 1.
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20, 30]) # Shape (3,)
result = a + b
print(result)
In this example, b
(shape (3,)
) is broadcast to match the rows of a
(shape (2, 3)
). Effectively, b
is treated as:
[[10, 20, 30], [10, 20, 30]]
Output:
[[11 22 33]
[14 25 36]]
Aggregation Functions in NumPy
NumPy also provides functions to perform aggregations (like sum or mean) across array elements, often along specific axes.
NumPy Sum Operation (np.sum()
)
Calculates the sum of array elements.
a = np.array([[1, 2, 3], [4, 5, 6]])
# Sum of all elements
print(np.sum(a))
# Sum along axis 0 (columns)
print(np.sum(a, axis=0))
# Sum along axis 1 (rows)
print(np.sum(a, axis=1))
Output:
21
[5 7 9]
[ 6 15]
NumPy Mean Operation (np.mean()
)
Calculates the arithmetic mean of array elements.
a = np.array([[1, 2, 3], [4, 5, 6]])
# Mean of all elements
print(np.mean(a))
# Mean along axis 0 (columns)
print(np.mean(a, axis=0))
# Mean along axis 1 (rows)
print(np.mean(a, axis=1))
Output:
3.5
[2.5 3.5 4.5]
[2. 5.]
Operations with Complex Numbers
NumPy handles complex numbers and provides specific functions for their manipulation.
a = np.array([-5.6j, 0.2j, 11., 1+1j])
print(np.real(a)) # Real part
print(np.imag(a)) # Imaginary part
print(np.conj(a)) # Complex conjugate
print(np.angle(a)) # Angle in radians
print(np.angle(a, deg=True)) # Angle in degrees
Output:
[ 0. 0. 11. 1.]
[-5.6 0.2 0. 1. ]
[ 0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ]
[-1.57079633 1.57079633 0. 0.78539816]
[-90. 90. 0. 45.]
NumPy Arithmetic Function Reference
Function | Description |
---|---|
numpy.add() | Element-wise addition |
numpy.subtract() | Element-wise subtraction |
numpy.multiply() | Element-wise multiplication |
numpy.divide() | Element-wise division |
numpy.power() | Element-wise exponentiation |
numpy.mod() | Element-wise modulo operation |
numpy.remainder() | Element-wise remainder |
numpy.divmod() | Computes (a // b, a % b) element-wise |
numpy.abs() | Absolute value (for signed numbers) |
numpy.fabs() | Absolute value (for floating-point only) |
numpy.sign() | Sign of elements |
numpy.conj() | Complex conjugate |
numpy.exp() | Exponential (e^x ) |
numpy.expm1() | Computes e^x – 1 |
numpy.log() | Natural logarithm (ln(x) ) |
numpy.log1p() | Logarithm of 1+x (ln(1+x) ) |
numpy.log2() | Logarithm base 2 |
numpy.log10() | Logarithm base 10 |
numpy.sqrt() | Square root |
numpy.square() | Square (x^2 ) |
numpy.cbrt() | Cube root |
numpy.reciprocal() | Reciprocal (1/x ) |
SEO Keywords: NumPy arithmetic operations tutorial, Element-wise array operations in Python, NumPy broadcasting examples, NumPy addition subtraction multiplication division, NumPy complex number operations, NumPy aggregation functions, NumPy sum and mean with axis, Advanced NumPy functions list, NumPy array math operations.
NumPy Array Stacking for ML & AI: A Deep Dive
Master NumPy array stacking (stack, vstack, hstack, dstack, column_stack) for efficient ML/AI data manipulation and model building.
NumPy Binary Operations: Element-wise Math for ML
Master NumPy binary operations for efficient element-wise calculations in machine learning. Explore addition, subtraction, bitwise logic & shifting for data preprocessing.