【问题标题】:How to concat the matrix with intervals in tensorflow如何在张量流中将矩阵与间隔连接起来
【发布时间】:2019-07-31 08:16:50
【问题描述】:

我的英语很差。我会尽力澄清我的问题。

所以,我有两个矩阵:

matrix1=[[1,3],[5,7]]

matrix2 =[[2,4],[6,8]]

我想将它们连接起来并像下面的矩阵一样对它们进行排序:

matrix3=[[1,2,3,4],[5,6,7,8]]

我试过这个方法:

matrix1=[[1,3],[5,7]];  
matrix2 =[[2,4],[6,8]];

with tf.Session() as sess:
   input1=tf.placeholder(tf.float32,[2,2])
   input2=tf.placeholder(tf.float32,[2,2])
   output=how_to_concat(input1,input2)
   sess.run(tf.global_variables_initializer())
   [matrix3] = sess.run([output], feed_dict={input1:matrix1, input2: matrix2})

我想实现how_to_concat 来连接矩阵并将两个(2, 2) 矩阵排序为一个(2, 4) 矩阵。我尝试了下面的代码,但它没有像例外一样工作:

def how_to_concat(input1,input2)
    output=tf.Variable(tf.zeros((2,4)))
    output=tf.assign(output[:,::2],input1)
    output=tf.assign(output[:,1::2],input2)
    return output

【问题讨论】:

标签: python tensorflow


【解决方案1】:

您可以使用基础 python 来做到这一点,或者 Numpy 库来实现这一点。 按照这个答案,我可以按照您的要求工作:https://stackoverflow.com/a/41859635/6809926

因此,对于 tensorflow,您可以使用 top_k 方法,此处对此进行了解释:https://stackoverflow.com/a/40850305/6809926。 你会发现下面的代码。

import numpy as np
matrix1=[[1,3],[5,7]]  
matrix2 =[[2,4],[6,8]]

res = []
# Basic python
for i in range(len(matrix1)):
    new_array = matrix1[i] + matrix2[i] 
    res.append(sorted(new_array))
print("Concatenate with Basic python: ", res)

# Using Numpy 
res = np.concatenate((matrix1, matrix2), axis=1)
print("Concatenate with Numpy: ", np.sort(res))

sess = tf.Session()
# Using Tensorflow
def how_to_concat(input1,input2):
    array_not_sorted = tf.concat(axis=1, values=[input1, input2])
    row_size = array_not_sorted.get_shape().as_list()[-1]
    top_k = tf.nn.top_k(-array_not_sorted, k=row_size)
    return top_k
res = how_to_concat(matrix1, matrix2)

print("Concatenate with TF: ", sess.run(-res.values))

输出

与基本 python 连接:[[1,2,3,4],[5,6,7,8]]

与 Numpy 连接:[[1,2,3,4],[5,6,7,8]]

与 TF 连接:[[1,2,3,4],[5,6,7,8]]

【讨论】:

  • 感谢您的回复。这是我的问题。 【一】。我想用间隔连接矩阵,所以 matrix3 是 [[1,2,3,4],[5,6,7,8]],而不是 [ matrix1, matrix2 ],所以 tf.concat 可能没用. 【2】在我的代码中,how_to_concat包含了关于input1和input2的其他操作。你提到我可以使用 numpy.但我不知道如何将 tf.plcaeholders 转移到 numpy 数组?能具体说明一下吗?
  • 我不明白你所说的“用间隔连接矩阵”是什么意思。你的“matrix3 is [[1,2,3,4],[5,6,7,8]]”和地雷有什么区别?
  • 如果使用tf.concat,结果是[matrix1,matrix2]=[[1,3,2,4],[5,7,6,8]],不是预期的matrix3 =[[1,2,3,4],[5,6,7,8]].
  • 好的,感谢您的更好理解,我更新了答案以使其正常工作。
猜你喜欢
  • 2020-09-26
  • 2018-11-19
  • 2018-12-09
  • 2017-12-02
  • 2019-12-26
  • 2019-09-29
  • 2018-05-24
  • 2020-11-07
  • 2013-10-21
相关资源
最近更新 更多