代码之家  ›  专栏  ›  技术社区  ›  Baron Yugovich

边值的Keras-pad张量

  •  2
  • Baron Yugovich  · 技术社区  · 6 年前

    Conv2DTranspose ,我没有统一的尺寸,这是个问题。

    所以我想我应该在中间的张量上加上一行和一列,值和我在边上看到的一样,以减少干扰。我在凯拉斯怎么做,有可能吗?我的选择是什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   benjaminplanche    6 年前

    以Tensorflow为背景,你可以使用 tf.concat() 将行/列的副本添加到张量。

    假设要复制最后一行/列:

    import tensorflow as tf
    from keras.layers import Lambda, Input
    from keras.models import Model
    import numpy as np
    
    def duplicate_last_row(tensor):
        return tf.concat((tensor, tf.expand_dims(tensor[:, -1, ...], 1)), axis=1)
    
    def duplicate_last_col(tensor):
        return tf.concat((tensor, tf.expand_dims(tensor[:, :, -1, ...], 2)), axis=2)
    
    # --------------
    # Demonstrating with TF:
    
    x = tf.convert_to_tensor([[[1, 2, 3], [4, 5, 6]],
                              [[10, 20, 30], [40, 50, 60]]])
    
    x = duplicate_last_row(duplicate_last_col(x))
    with tf.Session() as sess:
        print(sess.run(x))
    # [[[ 1  2  3  3]
    #   [ 4  5  6  6]
    #   [ 4  5  6  6]]
    #
    #  [[10 20 30 30]
    #   [40 50 60 60]
    #   [40 50 60 60]]]
    
    
    # --------------
    # Using as a Keras Layer:
    
    inputs = Input(shape=(5, 5, 3))
    padded = Lambda(lambda t: duplicate_last_row(duplicate_last_col(t)))(inputs)
    
    model = Model(inputs=inputs, outputs=padded)
    model.compile(optimizer="adam", loss='mse', metrics=['mse'])
    batch = np.random.rand(2, 5, 5, 3)
    x = model.predict(batch, batch_size=2)
    print(x.shape)
    # (2, 6, 6, 3)