简体   繁体   English

如何在 Keras 中调整(插值)张量的大小?

[英]How to resize (interpolate) a tensor in Keras?

I want to resize a tensor (between layers) of size say (None, 2, 7, 512) to (None, 2, 8, 512), by interpolating it (say using nearest neighbor), similar to this function tf.image.resize_nearest_neighbor available in Tensorflow.我想通过对它进行插值(例如使用最近邻)来调整大小(无,2, 7, 512)到(无,2, 8, 512)的张量(层之间)的大小,类似于此函数tf.image.resize_nearest_neighbor在 Tensorflow 中可用。

Is there any way to do that?有没有办法做到这一点?

I tried directly using the Tensorflow function tf.image.resize_nearest_neighbor and the pass the tensors to the next Keras layer, but with the next layer this error was thrown:我尝试直接使用 Tensorflow 函数tf.image.resize_nearest_neighbor并将张量传递给下一个 Keras 层,但是在下一层抛出此错误:

AttributeError: 'Tensor' object has no attribute '_keras_history' AttributeError: 'Tensor' 对象没有属性 '_keras_history'

I believe this is due to some attributes that are missing in Tensorflow tensors, which makes sense as the layer expects Keras tensors to be passed.我相信这是由于 Tensorflow 张量中缺少一些属性,这是有道理的,因为该层希望通过 Keras 张量。

Surprisingly there is no existing layer/function in keras that does such an interpolation of a tensor (as pointed out by xtof54).令人惊讶的是,keras 中没有现有的层/函数可以对张量进行这种插值(如 xtof54 所指出的)。 So, I implemented it using a lambda layer, and it worked fine.因此,我使用 lambda 层实现了它,并且运行良好。

    def resize_like(input_tensor, ref_tensor): # resizes input tensor wrt. ref_tensor
        H, W = ref_tensor.get_shape()[1], ref_tensor.get_shape()[2]
        return tf.image.resize_nearest_neighbor(input_tensor, [H.value, W.value])

The problem, in the first place, was due to the use of a tensor directly from tensorflow in a Keras layer, as a few additional attributes (required for a keras tensor) that are missing.问题首先是由于在 Keras 层中直接使用了来自 tensorflow 的张量,因为缺少一些附加属性(keras 张量所需)。 In addition, though Lambda layer is quite easy to use, it would be really convenient if keras allows the use of tensors (if possible) from tensorflow directly in keras layers, in the future.此外,虽然 Lambda 层非常易于使用,但如果 keras 允许在未来直接在 keras 层中使用来自 tensorflow 的张量(如果可能),那将非常方便。

I would use Repeat to add one element and implement the interpolation as a new lambda layer.我将使用 Repeat 添加一个元素并将插值实现为一个新的 lambda 层。 I don't think there's an existing layer for this in keras.我不认为在 keras 中有一个现有的层。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM