gpt4 book ai didi

python - 只是 reshape 和 reshape 和获得转置之间的区别?

转载 作者:行者123 更新时间:2023-12-04 07:17:03 28 4
gpt4 key购买 nike

我目前正在学习 CS231 作业,我意识到一些令人困惑的事情。在计算梯度时,当我第一次 reshape x 然后得到转置时,我得到了正确的结果。

x_r=x.reshape(x.shape[0],-1)
dw= x_r.T.dot(dout)
enter image description here
但是,当我直接将形状 reshape 为 X.T 形状时,它不会返回正确的结果。
dw = x.reshape(-1,x.shape[0]).dot(dout)
enter image description here
有人可以解释以下问题吗?
使用 np.reshape() 获取元素的顺序如何变化?
将 (N,d1,d2..dn) 形状的数组重新整形为 N,D 数组与通过转置获得 (D,N) 的重新整形数组有何不同。

最佳答案

虽然您的两种方法都会产生相同形状的数组,但由于 numpy 读取/写入元素的方式,元素的顺序会有所不同。默认情况下,reshape使用类似 C 的索引顺序,这意味着元素被读取/写入,最后一个轴索引变化最快,回到第一个轴索引变化最慢(取自 documentation )。
这是一个在实践中意味着什么的例子。让我们假设以下数组 x :

x = np.asarray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])

print(x.shape) # (2, 3, 2)

print(x)
# output
[[[ 1 2]
[ 3 4]
[ 5 6]]

[[ 7 8]
[ 9 10]
[11 12]]]
现在让我们通过以下两种方式 reshape 这个数组:
opt1 = x.reshape(x.shape[0], -1)
opt2 = x.reshape(-1, x.shape[0])

print(opt1.shape) # outptu: (2, 6)
print(opt2.shape) # output: (6, 2)

print(opt1)
# output:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]

print(opt2)
# output:
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]
reshape首先推断出新数组的形状,然后返回一个 View ,在该 View 中以类似 C 的索引顺序读取元素。
opt1 上举例说明这一点: 由于原始数组 x有 12 个元素,它推断新数组 opt1形状必须为 (2, 6) (因为 2*6=12)。现在, reshape返回一个 View ,其中:
opt1[0][0] == x[0][0][0] 
opt1[0][1] == x[0][0][1]
opt1[0][2] == x[0][1][0]
opt1[0][3] == x[0][1][1]
opt1[0][4] == x[0][2][0]
opt1[0][5] == x[0][2][1]
opt1[1][0] == x[1][0][0]
...
opt1[1][5] == x[1][2][1]
所以如上所述,最后一个轴索引变化最快,第一个轴索引变化最慢。同样, opt2 的输出将被计算。
您现在可以验证转置第一个选项将导致相同的形状但不同的元素顺序:
opt1 = opt1.T

print(opt1.shape) # output: (6, 2)

print(opt1)
# output:
[[ 1 7]
[ 2 8]
[ 3 9]
[ 4 10]
[ 5 11]
[ 6 12]]
显然,由于元素排序,这两种方法不会产生相同的数组,即使它们具有相同的形状。

关于python - 只是 reshape 和 reshape 和获得转置之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68700008/

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