在神經(jīng)網(wǎng)絡(luò)計(jì)算過程中,經(jīng)常會(huì)遇到需要將矩陣中的某些元素取出并且單獨(dú)進(jìn)行計(jì)算的步驟(例如MLE,Attention等操作)。那么在 tensorflow 的 Variable 類型中如何做到這一點(diǎn)呢?
首先假設(shè) Variable 是一個(gè)一維數(shù)組 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 中,如果我們只想取出數(shù)組 A 中的某一個(gè)元素,則 B 的設(shè)定為:
1
2
3
|
b = np.array([ 3 ]) B = tf.placeholder(dtype = tf.int32, shape = [ 1 ]) |
由于我們的索引坐標(biāo)只有一維,所以 shape=1。
取出元素然后組合成tensor C 的操作如下:
1
|
C = tf.gather_nd(A, B) |
運(yùn)行:
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 ] |
如果我們想取出一維數(shù)組中的多個(gè)元素,則需要把每一個(gè)想取出的元素索引都單獨(dú)放一行:
1
2
3
|
b = np.array([[ 3 ], [ 2 ], [ 5 ], [ 0 ]]) B = tf.placeholder(dtype = tf.int32, shape = [ 4 , 1 ]) |
此時(shí)由于我們想要從一維數(shù)組中索引 4 個(gè)數(shù),所以 shape=[4, 1]
再次運(yùn)行得到:
1
|
[ 4 3 6 1 ] |
////////////////////////////////////////////////////////////////////////////////////華麗麗的分割線
假設(shè) Variable 是一個(gè)二維矩陣 A:
1
2
3
|
a = np.array([[ 1 , 2 , 3 , 4 ], [ 5 , 6 , 7 , 8 ], [ 9 , 10 , 11 , 12 ]]) A = tf.Variable(a) |
首先我們先取出 A 中的一個(gè)元素,需要給定該元素的行列坐標(biāo),存到 B 中:
1
2
3
|
b = np.array([ 2 , 3 ]) B = tf.placeholder(dtype = tf.int32, shape = [ 2 ]) |
注意由于我們輸入的索引坐標(biāo)變成了二維,所以shape也變?yōu)?。
取出元素然后組合成tensor C:
1
|
C = tf.gather_nd(A, B) |
運(yùn)行:
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 ] |
同樣的,如果我們想取出二維矩陣中的多個(gè)元素,則需要把每一個(gè)想取出的元素的索引都單獨(dú)放一行:
1
2
3
|
b = np.array([[ 2 , 3 ], [ 1 , 0 ], [ 2 , 2 ], [ 0 , 1 ]]) B = tf.placeholder(dtype = tf.int32, shape = [ 4 , 2 ]) |
此時(shí)由于我們想要從二維矩陣中索引出 4 個(gè)數(shù),所以 shape=[4, 2]
再次運(yùn)行得到:
1
|
[ 12 5 11 2 ] |
////////////////////////////////////////////////////////////////////////////////////華麗麗的分割線
推廣到 n 維矩陣中:
假設(shè) A 是 Variable 類型的 n 維矩陣,我們想取出矩陣中的 m 個(gè)元素,那么首先每個(gè)元素的索引坐標(biāo)要表示成列表的形式:
1
|
index = [x1, x2, x3, ..., xn] |
其中 xj 代表該元素在 n 維矩陣中第 j 維的位置。
其次每個(gè)坐標(biāo)要單獨(dú)占索引矩陣的一行:
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() 函數(shù)替換即可:
1
|
result = tf.gather_nd(A, index_matrix) |
////////////////////////////////////////////////////////////////////////////////////華麗麗的分割線
[注] 問題出自:https://stackoverflow.com/questions/44793286/slicing-tensorflow-tensor-with-tensor
以上這篇將tensorflow.Variable中的某些元素取出組成一個(gè)新的矩陣示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qq_32492561/article/details/78316742