为 -1 选项找出正确的 numpy.reshape

Figuring out the proper numpy.reshape for -1 option

我有一个(希望)快速的 Numpy 问题,我希望你能帮助我。 我想使用 numpy.reshape 将 (5000, 32, 32, 3) 转换为 (5000, 3072),而我得到的唯一线索是:

# Reshape each image data into a 1-dim array
print (X_train.shape, X_test.shape) # Should be: (5000, 32, 32, 3) (500, 32, 32, 3)
#####################################################################
# TODO (2):                                                         #
# Reshape the image data to one dimension.                          #
#                                                                   #
# Hint: Look at the numpy reshape function and have a look at -1    # 
#       option                                                      #
#####################################################################
X_train = 
X_test = 
#####################################################################
#                       END OF YOUR CODE                            #
#####################################################################
print (X_train.shape, X_test.shape) # Should be: (5000, 3072) (500, 3072)

我花了最后一天时间搜索 Google 的例子,但显然这太微不足道了,不值得提问。帮忙?

你可以简单地做:

X_train = np.reshape(X_train, (5000, -1))
X_test = np.reshape(X_test, (500, -1))

工作示例:

import numpy as np
a = np.zeros((5000,32,32,3))
b = np.reshape(a, (5000, -1))

print(a.shape)
print(b.shape)

# Output
# (5000, 32, 32, 3)
# (5000, 3072)

numpy.reshape 将尝试将源数组 a 放入第一维长度为 5000 的数组中。 - 1告诉reshape根据源数组的总长度调整第二个维度的长度a.