Issue
I am confused by NumPy concepts of array and vector, let's say we have a 1-D array as below. From the 'shape' method, I can see the dimension. (10,)
means 1 dimension with 10 elements.
a = np.arange(10)
print(a)
a.shape
[0 1 2 3 4 5 6 7 8 9]
(10,)
Now I got to know a method called np.newaxis
, to convert the array in to a row vector. So I am wondering in NumPy do we assume a row or column vector always has 2-dimension? (I think in linear algebra, vector can live in any dimension, or there is a conceptual difference in NumPy and linear algebra when we are referring to 'dimension'?). Since the vector was converted by add 1 dimension by calling np.newaxis
.
print(a[np.newaxis:])
print(a[np.newaxis,:].shape)
[0 1 2 3 4 5 6 7 8 9]
(1, 10)
Solution
Please note that DIMENSION word may take different sense in different context. For example in linear algebra (1, 1) is a vector in the 2D space and (1, 1, 1) is the vector in the 3D space and both of them are 1D arrays in programming langages. The collection of 3D vectors is matrix in linear algebra and 2D array in programming languages.
In terms of linear algebra shape (10,) is 1 10-dimensional vector or 10 scalar values. Shape (10,2) is 2 10-dimensional vectors or 10 2-dimensional vectors.
Let's consider linear algebra matrix multiplication formula:
AB(i,j) = sum(A[i,k] * B[k,j])
This formula remains valid for vectors if we assume that the row vector is a matrix of dimension (1, N), and the column vector is a matrix of dimension (N, 1).
NumPy uses the same approach. But NumPy allows not only 2D arrays, but also 1D, 3D and so on. Such arrays are useful for other computational models. If you are interested in this, you can read more about tensors.
You can rearrange elements of ndarray
with .reshape(...)
method. When changing the shape of the array, all elements remain in place, but the addressing of the elements changes.
If we assume that the row vector and column vector are special objects, we will be forced to complicate the calculation rules, which is very impractical.
Answered By - Sergey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.