Master NumPy: Turn Math Formulas into Python Code
This article explains how to use Python's NumPy library to translate common mathematical formulas—such as powers, roots, absolute values, vector and matrix operations—into concise, executable code, covering setup, basic operations, and practical examples for data analysis and machine learning.
Machine learning and data analysis rely heavily on mathematical formulas, yet implementing them in code can be challenging; this guide shows how to convert those formulas into Python using NumPy.
About NumPy
NumPy is the foundational package for scientific computing in Python. It provides a powerful N‑dimensional array object, broadcasting functions, tools to integrate C/C++ and Fortran code, and extensive linear algebra, Fourier transform, and random number capabilities.
Powerful N‑dimensional array object
Advanced broadcasting functions
Integration tools for C/C++ and Fortran
Robust linear algebra, FFT, and random number utilities
Because NumPy offers a concise, intuitive API, it is the most common library for scientific computing in machine‑learning workflows.
Environment Setup
Create a virtual environment (optional) and install NumPy: pip install numpy Test the installation: >> import numpy In the examples below, NumPy is imported as np:
import numpy as npBasic Operations
Power Operations
The exponent operator is **. For example, x**2 computes the square of x, and x**3 computes the cube.
Square roots can be expressed as x**(1/2) or x**0.5, but NumPy provides the convenient function np.sqrt(x).
NumPy also offers np.square(x) for element‑wise squaring.
Absolute Value
The absolute value of a number x is |x|. NumPy computes it with np.abs(x).
Understanding Vectors and Matrices
Vector
A vector is a one‑dimensional array of numbers; geometrically, it represents a point in a coordinate system, with its direction pointing from the origin to that point.
Matrix
A matrix is a collection of vectors, i.e., a two‑dimensional array representing multiple points. Matrix operations correspond to operations on groups of vectors.
Initialization
NumPy can create vectors and matrices from Python lists: m = np.array([(1,2,3),(2,3,4),(3,4,5)]) This creates a 3×3 matrix.
Basic Arithmetic
Addition: x + 2 Subtraction: x - 2 Division:
x / 2Matrix Power
Matrix exponentiation uses the same ** operator. For the matrix m, its square is written as m**2.
Matrix Dot Product
Multiplication of matrices of compatible dimensions is performed with the dot product function:
Code example:
m.dot(n)Sum and Product
Summing all elements of a matrix m is done with m.sum(). Multiplying all elements uses m.prod().
Practice
Compute Mean
The mean of a vector x can be calculated as (1/x.size) * x.sum() or simply x.sum() / x.size:
(1/x.size)*x.sum() x.sum()/x.sizeFrobenius Norm
The Frobenius norm of a matrix m is computed by squaring each element, summing, and taking the square root:
np.sqrt((m**2).sum())Sample Variance
Using the definition, variance can be expressed as:
np.sqrt(((x - (x.sum()/x.size))**2).sum()/(x.size-1))With NumPy's mean helper, the expression simplifies to: np.sqrt(((x - np.mean(x))**2).sum()/(x.size-1)) Standard deviation is directly available via np.std(x).
Euclidean Distance
The Euclidean distance between vectors a and b is np.sqrt(((a-b)**2).sum()), which NumPy also provides as np.linalg.norm(a-b):
np.linalg.norm(a-b)Summary
NumPy is a deep and versatile mathematical library that forms the backbone of scientific computing in Python. By translating formulas into NumPy code, you gain a clear understanding of underlying operations, which accelerates learning and practical work in data analysis, machine learning, and research.
References
https://blog.csdn.net/garfielder007/article/details/51386683
https://blog.csdn.net/robert_chen1988/article/details/102712946
https://mathtocode.com/
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
