Keras:如何仅从张量中提取某些层

时间:2019-01-08 02:38:38

标签: python tensorflow keras

我有一个[6,20,30,6]形状的4-D张量,我想执行以下等价的keras / tensorflow:

new = np.array([old[i,:,:,i] for i in range(6)])

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以扩展old的尺寸,使用理解列表来选择所需的切片并将其沿扩展的尺寸连接起来。例如:

import tensorflow as tf
import numpy as np

tensor_shape = (6, 20, 30, 6)
old = np.arange(np.prod(tensor_shape)).reshape(tensor_shape)
new = np.array([old[i, :, :, i] for i in range(6)])

old_ = tf.placeholder(old.dtype, tensor_shape)
new_ = tf.concat([old[None, i, :, :, i] for i in range(6)], axis=0)

with tf.Session() as sess:
    new_tf = sess.run(new_, feed_dict={old_: old})
    assert (new == new_tf).all()

答案 1 :(得分:1)

感谢@rvinas的回答,我得以将其转换为纯净的喀拉拉邦。

def cc(x):
    return K.backend.stack([x[:,i, :, :, i] for i in range(6)], axis=1)

然后在keras模型定义中:

new=L.Lambda(lambda y: cc(y))(old)