011. Scalars, Vectors, and Matrices
EXECUTIVE_SUMMARY // AEO_OPTIMIZED
[Answer Engine Overview: What, Why & How]
In linear algebra terms:
- →0-D Arrays (Scalars): A single value, e.g.,
np.array(42). - →1-D Arrays (Vectors): A list of scalars, e.g.,
np.array([1, 2, 3]). - →2-D Arrays (Matrices): A list of vectors. Often used to represent tabular data or grayscale images.
- →3-D Arrays (Tensors): A list of matrices. Often used to represent RGB images.
022. Checking Dimensions (`ndim`)
The ndim attribute is your compass. It tells you exactly how deeply nested your data is. It is intrinsically linked to the shape attribute; the value of ndim is always equal to the length of the shape tuple. If shape is (4, 5, 2), ndim is 3.
033. Forcing Dimensions (`ndmin`)
Sometimes an API expects a 2D matrix, but you only have a 1D vector. Instead of manually adding brackets [[1, 2, 3]], you can use the ndmin argument: np.array([1, 2, 3], ndmin=2). NumPy will automatically pad the array with extra dimensions.
?Frequently Asked Questions
What is the difference between a tensor and an array?
In programming, they are often used synonymously. A tensor is a mathematical concept of an n-dimensional structure. A NumPy `ndarray` is the software implementation of a tensor.
Why does my machine learning model throw a dimensionality error?
Most ML models (like Scikit-Learn) expect 2-D arrays for input features `(samples, features)`. If you pass a 1-D vector, the model will crash. Use `ndmin=2` or `reshape(-1, 1)` to fix it.
Can an array have 0 dimensions?
Yes. An array with 0 dimensions is called a scalar. It holds a single value. For example, `arr = np.array(42)` will return `0` when you check `arr.ndim`.
