Usage of .shape[0] and .reshape(X.shape[0], -1) and X.reshape(X.shape[0], -1).T in python

 shape[0] is the number of rows in the first column

Example 1: Suppose the shape of x is (209, 64, 64, 3)

>>> X.shape
(209, 64, 64, 3)

>>> X.shape[0]
209

 Re-establish the dimension through reshape, the first dimension is X.shape[0], which is the normal reshape operation; the second dimension is -1, we know what the shape attribute of X is (209, 64, 64, 3), but I want X to become 209 rows, and I don’t know the number of columns, so it is 209 * 64 * 64 * 3 / 209, which is 64 * 64 * 3.
 

>>> X.reshape(X.shape[0], -1)
(209, 64*64*3) 

X.reshape(X.shape[0], -1).T can transform a matrix with dimensions (a,b,c,d) into a matrix with dimensions (b∗c∗d, a).

>>> X.reshape(X.shape[0], -1).T
(64*64*3, 209)

reshape(1,-1) into 1 line:

reshape(2,-1) translates into two lines:

reshape(-1,1) into 1 column:

reshape(-1,2) into two columns

reshape(2,8) is converted into two rows and eight columns

test = [[1,2,3],[2,3,4]]
test_x = np.reshape(test_x, (2, 1, 3)) # convert 2D to 3D


Summarize:

Parameter -1 is the parameter used when the number of rows or columns is not known, so first determine other parameters except parameter -1, and then pass (calculation of total parameters) / (determine the parameters other than parameter -1 other parameters) = parameters for how much the position should be.

Example: Suppose we don't know the shape attribute of z, but we want z to have only one column and the number of rows is unknown. Through z.reshape(-1,1), Numpy automatically calculates that there are 8 rows.

import numpy as np

z = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8]])
c = z.reshape(-1, 1)
print("c:",c)

> c: [[1]
       [2]
       [3]
      [4]
      [5]
      [6]
      [7]
      [8]]

I want to make z into 2 columns, but I don’t know how many rows, Numpy automatically calculates that there are 4 rows, and the array shape attribute is (2, 4) matching the original (1, 8).

import numpy as np

z = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8]])
d = z.reshape(-1, 2)
print("d:",d)

> d: [[1 2]
      [3 4]
      [5 6]
      [7 8]]

Guess you like

Origin blog.csdn.net/weixin_61745097/article/details/127983309