参考:https://www.zhihu.com/question/52684594/answer/297441394 感谢作者
举个简单的例子,要记住,python默认是按行取元素
c = np.array([[1,2,3],[4,5,6]])
输出:
[[1 2 3]
[4 5 6]]
我们看看不同的reshape
print '改成2行3列:'
print c.reshape(2,3)
print '改成3行2列:'
print c.reshape(3,2)
print '我也不知道几行,反正是1列:'
print c.reshape(-1,1)
print '我也不知道几列,反正是1行:'
print c.reshape(1,-1)
print '不分行列,改成1串'
print c.reshape(-1)
输出为:
改成2行3列:
[[1 2 3]
[4 5 6]]
改成3行2列:
[[1 2]
[3 4]
[5 6]]
我也不知道几行,反正是1列:
[[1]
[2]
[3]
[4]
[5]
[6]]
我也不知道几列,反正是1行:
[[1 2 3 4 5 6]]
不分行列,改成1串
[1 2 3 4 5 6]
一串是啥意思?一串就是秩rank()为0的矩阵~
torch.shape[-1]同理
注:其中
print c.reshape(1,-1)
print c.reshape(-1)的区别是:
print c.reshape(1,-1):此时c的shape为(1,6)
print c.reshape(-1):此时c的shape为(6,)
在编程中尽量避免形为(6,)这种一串的秩rank()为0的矩阵,可能会导致一些不易察觉的bug,所以建议
1使用reshape函数使得其形为(1,6)这种;
2利用assert查看以确保得到的是你想要的形状。
作者:cuicuicui
链接:https://www.zhihu.com/question/52684594/answer/297441394
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。