在神經網絡計算過程中,經常會遇到需要將矩陣中的某些元素取出并且單獨進行計算的步驟(例如MLE,Attention等操作)。那么在 tensorflow 的 Variable 類型中如何做到這一點呢?
首先假設 Variable 是一個一維數組 A:
1
2
3
4
5
6
7
|
import numpy as np import tensorflow as tf a = np.array([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]) A = tf.Variable(a) |
我們把我們想取出的元素的索引存到 B 中,如果我們只想取出數組 A 中的某一個元素,則 B 的設定為:
1
2
3
|
b = np.array([ 3 ]) B = tf.placeholder(dtype = tf.int32, shape = [ 1 ]) |
由于我們的索引坐標只有一維,所以 shape=1。
取出元素然后組合成tensor C 的操作如下:
1
|
C = tf.gather_nd(A, B) |
運行:
1
2
3
4
5
6
7
|
init = tf.global_variables_initializer() with tf.Session() as sess: init.run() feed_dict = {B: b} result = sess.run([C], feed_dict = feed_dict) print result |
得到:
1
|
[ 4 ] |
如果我們想取出一維數組中的多個元素,則需要把每一個想取出的元素索引都單獨放一行:
1
2
3
|
b = np.array([[ 3 ], [ 2 ], [ 5 ], [ 0 ]]) B = tf.placeholder(dtype = tf.int32, shape = [ 4 , 1 ]) |
此時由于我們想要從一維數組中索引 4 個數,所以 shape=[4, 1]
再次運行得到:
1
|
[ 4 3 6 1 ] |
////////////////////////////////////////////////////////////////////////////////////華麗麗的分割線
假設 Variable 是一個二維矩陣 A:
1
2
3
|
a = np.array([[ 1 , 2 , 3 , 4 ], [ 5 , 6 , 7 , 8 ], [ 9 , 10 , 11 , 12 ]]) A = tf.Variable(a) |
首先我們先取出 A 中的一個元素,需要給定該元素的行列坐標,存到 B 中:
1
2
3
|
b = np.array([ 2 , 3 ]) B = tf.placeholder(dtype = tf.int32, shape = [ 2 ]) |
注意由于我們輸入的索引坐標變成了二維,所以shape也變為2。
取出元素然后組合成tensor C:
1
|
C = tf.gather_nd(A, B) |
運行:
1
2
3
4
5
6
7
|
init = tf.global_variables_initializer() with tf.Session() as sess: init.run() feed_dict = {B: b} result = sess.run([C], feed_dict = feed_dict) print result |
得到:
1
|
[ 12 ] |
同樣的,如果我們想取出二維矩陣中的多個元素,則需要把每一個想取出的元素的索引都單獨放一行:
1
2
3
|
b = np.array([[ 2 , 3 ], [ 1 , 0 ], [ 2 , 2 ], [ 0 , 1 ]]) B = tf.placeholder(dtype = tf.int32, shape = [ 4 , 2 ]) |
此時由于我們想要從二維矩陣中索引出 4 個數,所以 shape=[4, 2]
再次運行得到:
1
|
[ 12 5 11 2 ] |
////////////////////////////////////////////////////////////////////////////////////華麗麗的分割線
推廣到 n 維矩陣中:
假設 A 是 Variable 類型的 n 維矩陣,我們想取出矩陣中的 m 個元素,那么首先每個元素的索引坐標要表示成列表的形式:
1
|
index = [x1, x2, x3, ..., xn] |
其中 xj 代表該元素在 n 維矩陣中第 j 維的位置。
其次每個坐標要單獨占索引矩陣的一行:
1
2
3
4
5
6
7
8
9
|
index_matrix = [[x11, x12, x13, ..., x1n], [x21, x22, x23, ..., x2n], [x31, x32, x33, ..., x3n], ......................................., [xm1, xm2, xm3, ..., xmn]] |
最后用 tf.gather_nd() 函數替換即可:
1
|
result = tf.gather_nd(A, index_matrix) |
////////////////////////////////////////////////////////////////////////////////////華麗麗的分割線
[注] 問題出自:https://stackoverflow.com/questions/44793286/slicing-tensorflow-tensor-with-tensor
以上這篇將tensorflow.Variable中的某些元素取出組成一個新的矩陣示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_32492561/article/details/78316742