如何用十的区间来表示矩阵

2024-06-28 20:03:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我的英语很差。我将尽力澄清我的问题。你知道吗

我有两个矩阵:

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

Tags: tooutput排序tf矩阵placeholderhowsess
1条回答
网友
1楼 · 发布于 2024-06-28 20:03:54

您可以使用基本的python来实现这一点,也可以使用numpylibs来实现这一点。 按照这个答案,我得到了你想要的工作: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))

输出

Concatenate with basic python: [[1,2,3,4],[5,6,7,8]]

Concatenate with Numpy: [[1,2,3,4],[5,6,7,8]]

Concatenate with TF: [[1,2,3,4],[5,6,7,8]]

相关问题 更多 >