[PYTHON] The shape of the one-dimensional array of numpy was complicated

Overview

This is an article for numpy beginners. Shortly after I started using Python, I misunderstood the output of an identity matrix shape. I think it's relatively easy to get caught, so I will share it based on actual examples.

Example

First, take a look at the shape of the array below.

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)

The output looks like this:

(2, 3)

Matrix rows are displayed on the left and columns are displayed on the right. It is understandable because it is mathematically expressed as 2 rows and 3 columns.

\begin{bmatrix}
1 & 2 & 3 \\
4 & 5 & 6
\end{bmatrix}

Reduce the number of lines by one and output the shape again.

b = np.array([1, 2, 3])
print(b.shape)

The output is below.

(3, )

...? I thought that (1, 3) would be output in 1 row and 3 columns, but it wasn't. ..

Try to calculate the matrix product as follows

a = np.array([2, 2])
b = np.array([[1, 2], [3, 4]])
print(np.dot(a, b))
print(np.dot(b, a))

Then the result is

[ 8 12]
[ 6 14]

When calculating the matrix product, it can be seen that it flexibly calculates as a row vector and a column vector according to the shape of another matrix.

Summary

The shape of a one-dimensional array is a tuple with one element and is expressed as (number of elements,). Mathematically, a matrix with only one row is called a row vector, and a matrix with only one column is called a column vector, but there is no distinction between a row vector and a column vector in a one-dimensional array of ndarray.

Recommended Posts

The shape of the one-dimensional array of numpy was complicated
[Python numpy] Dynamically specify the index of the array
I want to judge the authenticity of the elements of numpy array
Combine the overlap of one-dimensional intervals
Distinguishing the agari shape of mahjong
Convert data with shape (number of data, 1) to (number of data,) with numpy.
The inaccuracy of Tensorflow was due to log (0)
Sort the elements of the array by specifying the conditions
I checked the processing speed of numpy one-dimensionalization
Output in the form of a python array
Calculation speed of indexing for numpy quadratic array
NumPy array manipulation (3)
NumPy array manipulation (1)
[Golang] Specify an array in the value of map
The performance of PHP was better than I expected
Generate that shape of the bottom of a PET bottle
The story that the return value of tape.gradient () was None
Convert elements of numpy array from float to int
Create a shape on the trajectory of an object
Create a 2D array by adding a row to the end of an empty array with numpy