gpt4 book ai didi

python - 为什么 (X.shape[0], -1) 在矩阵 X 上使用 reshape 函数时用作参数?

转载 作者:行者123 更新时间:2023-12-04 01:46:56 26 4
gpt4 key购买 nike

一边做deeplearning.ai当然,我需要立即使用 numpy.reshape() .然而,在这样做的同时,我在类(class)笔记本中被指示以特定的方式去做。
目的是将 4 维向量转换为 2 维向量。

//
指示:

为方便起见,您现在应该在形状为 (num_px ∗∗ num_px ∗∗ 3, 1) 的 numpy 数组中 reshape 形状 (num_px, num_px, 3) 的图像。 .在此之后,我们的训练(和测试)数据集是一个 numpy 数组,其中每一列代表一个展平的图像。应该有 m_train(分别是 m_test)列。

练习: reshape 训练和测试数据集,使图像大小为 (num_px, num_px, 3)被展平为形状 (num_px ∗∗ num_px ∗∗ 3, 1) 的单个向量.

当您想将形状为 (a,b,c,d) 的矩阵 X 展平为形状为 (b∗∗c∗∗d, a) 的矩阵 X_flatten 时,一个技巧是使用:

X_flatten = X.reshape(X.shape[0], -1).T  


(X.T is the transpose of X)

我无法理解为什么以这种方式给出参数?
此外,在玩代码时,将“-1”更改为任何负整数,并没有改变输出。

最佳答案

我假设您正在使用 MNIST 数据集,因此您有 n 个大小为 m*m*3 的图像,假设 n 为 100,m 为 8。因此您有 100 个大小为 8*8 的 RGB 图像(3 个 channel ) ,从而使您的数据形状为 100,8,8,3。现在您想要展平 100 张图像中的每一张,因此您可以循环遍历数据集,并逐个图像展平它,或者您可以 reshape 它。

您决定通过以下方式 reshape 它:

X.reshape(X.shape[0], -1).T

让我们再解开一点, X.shape[0]给你 100. shape 将返回一个 (100,8,8,3) 元组,因为这是你的数据集的形状,你访问它的第 0 个元素,即 100,所以你得到
X.reshape(100, -1).T

那么它的作用是 reshape 数组但确保您仍然有 100 张图像,并且 -1 表示您不关心结果将被 reshape 为什么形状,因此它会自动从原始形状推断形状形状。以前你有一个形状为 100,8,8,3 的 4-D 数组,但现在你想把它 reshape 成一个 2-D 数组,你指定 100 应该是形状的 0 维,所以 numpy 推断出要 reshape 它变成这样的二维形状,它必须将其展平,因此 100,8*8*3 是输出形状。

之后你只需转置它

此外,这就是 numpy 文档说明的内容

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

关于python - 为什么 (X.shape[0], -1) 在矩阵 X 上使用 reshape 函数时用作参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54919419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com