Python: 3D array image (numpy.array)

I'm not good at imagining a 3D array of numpy with my head, so where does axis = 1 mean? It will be like this every time, so I will summarize my own understanding. Hereafter, "array" refers to np.array.

Trigger

In "Essence of Machine Learning" (Author: Koichi Kato), when there is a two-dimensional array X with seven two-dimensional vectors and cluster_centers with three two-dimensional vectors, the square of the distance between the two vectors Was calculated as follows (extracted from the 3rd edition pp.354-356).

>>> X = np.array([[1, 2],
                  [2, 3],
                  [3, 4],
                  [4, 5],
                  [5, 6],
                  [7, 9]])

>>> cluster_centers = np.array([[1, 1],
                                [2, 2],
                                [3, 3]])

>>> ((X[:, :, np.newaxis]
      - cluster_centers.T[np.newaxis, :, :])**2).sum(axis=1)
array([[  1,   1,   5],
       [  5,   1,   1],
       [ 13,   5,   1],
       [ 25,  13,   5],
       [ 41,  25,  13],
       [ 61,  41,  25],
       [100,  74,  52]])

It was so elegant that I didn't know what I was doing. Crying What is np.newaxis? It starts from what is wrong, and what is it because the position of np.newaxis is different between X and cluster_centers, transposed or summed ... (The book gives a supplementary explanation, Still, the hurdle was too high for me) So here's the way I've come to understand this. Since it has become long, I will divide the article into the first and second half. In this article, the image of the array and what np.newaxis does. The second half is here.

STEP 1. Basic image of the array

review.

One-dimensional array

>>> x = np.array([1, 2, 3])

It is a vector. For now, imagine the horizontal vector $ (1, 2, 3) $ as shown.

>>> y = np.array([1])

Also, even if there is only one element, it is a one-dimensional "array". Since there is a possibility that the number of elements will increase, the image has only one number in the squares lined up side by side. Something like $ (1, \ ldots) $. qiita_array1.png

Two-dimensional array

>>> A = np.array([[1, 2, 3],
                  [4, 5, 6]])

As you can see, the image is that the horizontal vectors are vertically connected. As a matrix

A = \left(
    \begin{array}{ccc}
      1 & 2 & 3 \\
      4 & 5 & 6 \\
    \end{array}
  \right).
>>> B = np.array([[1, 2, 3]])
>>> C = np.array([[1],
                  [2],
                  [3]])

This is also a two-dimensional array. B is an image in which there is only one horizontal vector that should be connected vertically, and numbers are included only in the first row of the squares arranged vertically and horizontally. In C, three horizontal vectors with only one element are lined up vertically. qiita_array2.png How to extract the elements of the array and the image of axis are as follows.

#For the index, specify the second dimension axis (vertical direction) for the first number and the horizontal direction for the second number.
>>> A[1, 2]
6

#If you change the number to a colon, all the axes will be fetched. The dimension goes down by one to become a vector.
>>> A[0, :]  
array([1, 2, 3])

#Even if the vertical axis is taken, it becomes one-dimensional.
>>> A[:, 1]  
array([2, 5])

#The vertical axis (second dimension) is axis=0, horizontal axis (first dimension) is axis=1 (A.sum is the sum for each axis)
>>> A.sum(axis=0)  
array([5, 7, 9])
>>> A.sum(1)  # "axis="Is optional
array([6, 15])

q_ar2_sl.jpg

Three-dimensional array

The three-dimensional array feels like there are many two-dimensional squares in the depth direction.

>>> X = np.array([[[1,  2,  3],
                   [4,  5,  6]],

                  [[7,  8,  9],
                   [10, 11, 12]]])

>>> Y = np.array([[[1]]])

A three-dimensional array like Y. There are squares in the depth, length, and width, but only one is filled. qiita_array3.jpg Just as we were able to extract a one-dimensional array from a two-dimensional array above, we can extract a two-dimensional array from a three-dimensional array by using two colons. However, it is a little difficult to grasp the image.

#The first number is the third dimension axis (depth direction), the second is the second dimension axis (vertical), and the third is the first dimension (horizontal).
>>> X[0, 1, 2]
6

#Depth axis(axis=0)Take out the 0th of
>>> X[0, :, :]
array([[1, 2, 3],
       [4, 5, 6]])

#Vertical axis(axis=1)Take out the first of
>>> X[:, 1, :]
array([[ 4,  5,  6],
       [10, 11, 12]])

#Horizontal axis(axis=2)Take out the second of
>>> X[:, :, 2]
array([[ 3,  6],
       [ 9, 12]])

q_ar3_sl.jpg

STEP 2. Add an axis to the array to raise the dimension

You can also add a new axis to the array to increase its dimension, as opposed to the slicing operation you did above to retrieve the array.

From one dimension to two dimensions

>>> x = np.array([1, 2, 3])

#Np to add axis.Use new axis.
# axis=Added 0 (vertical axis)
>>> x[np.newaxis, :]
array([[1, 2, 3]])

# axis=Add 1 Vertical x element(axis=0)Side by side, horizontal axis(axis=1)make.
>>> x[:, np.newaxis]
array([[1],
       [2],
       [3]])

# np.new axis can be replaced with None
>>> x[None, :]
array([[1, 2, 3]])

q_ar_newax2.jpg

From 2D to 3D

>>> A = np.array([[1, 2, 3],
                  [4, 5, 6]])

# axis=Added 0 (depth axis)
>>> A[np.newaxis, :, :]
array([[[1, 2, 3],
        [4, 5, 6]]])

# axis=Added 1 (vertical axis). Arrange the elements of x on the top surface of the 3D grid.
>>> A[:, np.newaxis, :]
array([[[1, 2, 3]],

       [[4, 5, 6]]])

# axis=Added 2 (horizontal axis). Arrange the elements of x on the side faces of the 3D grid.
>>> A[:, :, np.newaxis]
array([[[1],
        [2],
        [3]],

       [[4],
        [5],
        [6]]])

q_ar_newax3.jpg

Recommended Posts

Python: 3D array image (numpy.array)
Python 2D array trap [Copy array]
python image processing
Python multidimensional array
Python> link> 2D array initialization and assignment
[Beginner] Python array
Python array basics
Calculate 2D IDCT ~ Python
First Python image processing
[Python] Binary Acing 2020D
Image format in Python
python numpy array calculation
Image processing with Python
[python] Array slice operation
python --Export 2D histogram as an array by Matplotlib
Image processing with Python (Part 2)
Python memo (for myself): Array
Quicksort an array in Python 3
Empty multidimensional array in python
Image editing with python OpenCV
Create 3d gif with python3
[Python] Dynamic programming TDPC D
How to transpose a 2D array using only python [Note]
Sorting image files with Python (2)
Sorting image files with Python (3)
python> Handling of 2D arrays
Stumble story with Python array
Solve ABC175 D in Python
Image processing with Python (Part 1)
Tweet with image in Python
Sorting image files with Python
Create a python numpy array
Image processing with Python (Part 3)
Image processing by python (Pillow)
Image Processing Collection in Python
AtCoder ABC 182 Python (A ~ D)
Image data type conversion [Python]
[Python] Image processing with scikit-image
Cut out an image with python
Image capture of firefox using python
[Python] Using OpenCV with Python (Image Filtering)
Subscript access to python numpy array
Implemented image segmentation in python (Union-Find)
3D skeleton structure analysis with Python
[Python] Using OpenCV with Python (Image transformation)
Solve ABC166 A ~ D with Python
Workflow to convert formula (image) to python
Run TensorFlow Docker Image on Python3
Personal notes for python image processing
Image processing with Python 100 knocks # 3 Binarization
Recommended container image for Python applications
Let's do image scraping with Python
python x tensoflow x image face recognition
Python application: Numpy Part 3: Double array
[Python] How to swap array values
Today's python error: image is blank
Compare Python and JavaScript array loops
Find image similarity with Python + OpenCV
I'm addicted to Python 2D lists
Image processing with Python 100 knocks # 2 Grayscale
Introduction to image analysis opencv python