import numpy as np
NumPy Universal Functions (ufuncs)ΒΆ
Universal functions are NumPyβs mechanism for applying mathematical operations to every element of an array in a single call, without writing explicit Python loops. Under the hood, ufuncs dispatch to optimized C implementations, making them orders of magnitude faster than equivalent Python loops. Common ufuncs include np.sqrt(), np.exp(), np.log(), np.abs(), np.sin(), np.cos(), and many more. These are the building blocks for implementing mathematical formulas β from loss functions in machine learning to signal processing transforms.
# Numpy Universal Function
np1 = np.array([-3,-2,-1,0,1,2,3,4,5,6,7,8,9])
print(np1)
Square Root β np.sqrt()ΒΆ
The np.sqrt() universal function computes the square root of each element in the array. Universal functions (ufuncs) operate element-wise, applying the same operation to every value without explicit loops. Note that square roots of negative numbers produce nan values β in data science, you may need to handle these with np.nan_to_num() or filter them out first.
Absolute Value β np.absolute()ΒΆ
np.absolute() (or its alias np.abs()) returns the absolute value of each element, converting negatives to positives. This is useful in error calculation (mean absolute error), distance metrics, and when you need magnitudes regardless of direction. In signal processing and physics simulations, absolute values help extract amplitude from signed waveform data.
Exponential β np.exp()ΒΆ
np.exp() computes Eulerβs number e raised to the power of each element (e^x). The exponential function is central to machine learning: it appears in the softmax function (converting raw scores to probabilities), the sigmoid activation function, probability distributions, and growth/decay models. Exponentials grow extremely fast, so large input values can produce inf β a consideration when implementing these functions numerically.
Min and Max β np.min() / np.max()ΒΆ
np.min() and np.max() find the smallest and largest values in an array, respectively. These are fundamental for understanding data range, detecting anomalies, and performing min-max normalization ((x - min) / (max - min)), which scales features to a [0, 1] range. Both accept an axis parameter to operate along a specific dimension β for example, finding the maximum value in each column of a feature matrix.
Sign Function β np.sign()ΒΆ
np.sign() returns -1, 0, or 1 depending on whether each element is negative, zero, or positive. This is useful for extracting the direction of a value independently of its magnitude β for example, determining the direction of gradient updates, classifying positive vs. negative sentiment scores, or implementing custom activation functions.
# Trig Functions sin cos log
print(np.log(np1))