[英]How to concat the matrix with intervals in tensorflow
我的英文程度不高。 我會盡力澄清我的問題。
所以,我有兩個矩陣:
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來做到這一點,或者使用Numpy libs來實現這一點。 按照這個答案,我按照你的意願讓它工作: 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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.