【问题标题】:How to reshape 5D tensor to a 4D tensor, preserving the order of the last dimension, using keras.layers.permutate and keras.layers.reshape如何使用 keras.layers.permutate 和 keras.layers.reshape 将 5D 张量重塑为 4D 张量,保留最后一维的顺序
【发布时间】:2020-03-18 16:10:22
【问题描述】:

我正在尝试将具有 10 个内核 (output_dim = (None, 14, 14, 3, 10)) 的 keras Conv3D 层的输出重塑为所需的输出 (None, 14, 14, 30, 1) 所以我可以对所有组合的内核执行另一个 3D 卷积。我想在重塑的张量中保留前 10 个内核的空间关系/顺序,就像将它们“粘贴”在一起一样。

由于 keras.layers.reshape 使用 'row-major c-style' 来重塑张量,我会在这里放松内核的顺序。关于如何将 numpy.reshape 和 numpy.permutate 用于 numpy 矩阵,很容易有一个全面的解释,并假设 keras 将类似地工作,因为我也可以使用 keras.layers.permutate。问题是,在用 keras.layers.reshape 重塑以保留顺序之前,我根本无法理解在这种情况下我需要什么排列。

Intuition and idea behind reshaping 4D array to 2D array in NumPy

我总是可以对张量进行切片和连接,但这需要更多的 keras.layers 并减慢我的程序。非常感谢 keras.layers.Permutate() --> keras.layers.Reshape() 的“花式”组合!

【问题讨论】:

  • 提问时尽量具体。尝试给出一个“可重现”的示例stackoverflow.com/questions/5963269/… 通过使用通用数据集并显示您的代码,这对所有人来说都更容易。所以。最好用于特定的代码问题,而不是让其他人编写代码的地方。先试试吧……

标签: python tensorflow keras permutation reshape


【解决方案1】:

重塑不应该改变任何东西的顺序(因为改变顺序的计算成本很高,而重塑只是告诉如何划分)

最好的测试方法是简单地做它并查看结果,但你会得到这些:

如果你重塑这个(2,5)

[
 [1,2,3,4,5],
 [6,7,8,9,10]
]

进入(10,),你会得到和之前一样的顺序:

[1,2,3,4,5,6,7,8,9,10]

如果出于某种原因您想要 [1,6,2,7,3,8,4,9,5,10],那么您可以置换最后两个维度。

也就是说,当您的 (None, 14, 14, 3, 10) 重整为 (None, 14, 14, 30) 时,将保持最后 10 个的顺序在一起。

[[1,2,3,4,5,6,7,8,9,10],
 [11,12,13,14,15,16,17,18,19,20],
 [21,22,23,24,25,26,27,28,29,30]]

becomes

 [1,2,3,4,5,6,7,8,9,10,11,12...]

如果您想获得以下内容,请排列:

outs = Permute((1,2,4,3))(ins)
outs = Reshape((14,14,30))(outs)
---> [[1,11,21], [2,12,22], [3,13,23]...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多