如何在 Keras 中按列拆分张量以实现 STFCN

jhu*_*ang 5 deep-learning keras keras-layer

我想在 Keras 中实现时空全卷积网络 (STFCN)。我需要将 3D 卷积输出的每个深度列(例如具有 shape 的张量)(64, 16, 16)作为单独 LSTM 的输入。

为了说明这一点,我有一个(64 x 16 x 16)维度张量(channels, height, width)。我需要将张量(显式或隐式)拆分为 16 * 16 = 256 个 shape 的张量(64 x 1 x 1)

这是 STFCN 论文中的图表,用于说明时空模块。我上面描述的是“空间特征”和“时空模块”之间的箭头。

FCn 和时空模块之间的连接是图中的相关部分。

如何在 Keras 中最好地实现这个想法?

Vad*_* B. 6

您可以使用tf.splitKerasLambda层从 Tensorflow 中使用

使用lambda来形状的张量分裂(64,16,16)(64,1,1,256),然后子集,你需要的任何索引。

import numpy as np
import tensorflow as tf
import keras.backend as K
from keras.models import  Model
from keras.layers import Input, Lambda

# input data
data = np.ones((3,64,16,16))

# define lambda function to split
def lambda_fun(x) : 
    x = K.expand_dims(x, 4)
    split1 = tf.split(x, 16, 2)
    x = K.concatenate(split1, 4)
    split2 = tf.split(x, 16, 3)
    x = K.concatenate(split2, 4)
    return x

## check thet splitting works fine
input = Input(shape= (64,16,16))
ll = Lambda(lambda_fun)(input)
model = Model(inputs=input, outputs=ll)
res = model.predict(data)
print(np.shape(res))    #(3, 64, 1, 1, 256)
Run Code Online (Sandbox Code Playgroud)