2017-06-21 789 views
0

我有两个形状张量[1,4]说,Keras自定义合并两个张量

[1,2,3,4] [0.2,0.3,0.4,0.5]

现在我要合并它们合并层(可能使用使用Tensorflow后端一些自定义功能),使他们成为

[1,0.2,2,0.3,3,0.4,4,0.5]

我如何能实现这个?张量的形状是固定的。感谢您的时间。

回答

0

使用Tensorflow,您可以使用重塑和concat。 keras后端也提供这些操作。

a = tf.constant([1,2,3,4]) 
b = tf.constant([10,20,30,40]) 

c = tf.reshape(tf.concat([tf.reshape(a,(-1,1)), tf.reshape(b, (-1,1))], 1), (-1,)) 

我不知道是否存在一个更直接的方法来实现这一点。

编辑:存在一个更简单的解决方案,使用tf.stack而不是tf.concat

c = tf.reshape(tf.stack([a, b], 1),(-1,)) 
+0

这是非常精确的,但我不能够计算出所述-1的含义作为轴的值。你能解释一下吗?但是解决方案正在工作。 –

+0

在这种情况下,'(-1,)'与'[-1]'相同。根据TF doc的说法:“如果形状的一个分量是特殊值-1,则计算该维度的大小,使得总大小保持不变,特别是,[-1]的形状变为1-D。形状的大部分组件可以是-1。“ –

+0

谢谢。晶莹剔透。 –

1

的可能解决方案是连接的张量沿着轴线0,然后根据该指标收集的值,像

import tensorflow as tf 
from itertools import chain 

A = tf.constant([1, 2, 3, 4]) 
B = tf.constant([0.2, 0.3, 0.4, 0.5]) 

# Cast A to be compatible with B 
A = tf.cast(A, tf.float32) 

# Concat AB one next to the other 
AB = tf.concat([A, B], axis=0) 

# Generate a list of values in this sequence 
# 0, 4, 1, 5, ... in other to indicize the tensors 
# use gather to collect values in the specified positions 
NEW = tf.gather(AB, 
       list(
        chain.from_iterable((i, i + A.shape[0].value) 
             for i in range(A.shape[0].value)))) 

with tf.Session() as sess: 
    print(sess.run([NEW])) 
+0

谢谢。它工作正常。 –

+0

不客气!如果我解决了您的问题,请记住将答案标记为已接受! – nessuno