Tensorflow:从张量中选择每行中的一系列列
Tensorflow : Choosing a range of columns in each row from a Tensor
我只想选择张量每一行中的特定列,将其用于 RNN
seq_len=[11,12,20,30] #This is the sequence length, assume 4 sequences
array=tf.ones([4,30]) #Assuming this is the array I want to index from
function(array,seq_len) #apply required function
Output=(first 11 elements from row 0, first 12 from row 2, first 20 from row 3 etc), perhaps obtained as a flat tensor
您可以使用 tf.sequence_mask
and tf.boolean_mask
将它们压平:
mask = tf.sequence_mask(seq_len, MAX_LENGTH) # Replace MAX_LENGTH with the size of array on the right dimension, 30 in your case
output= tf.boolean_mask(array, mask=mask)
tensorflow 中的张量可以像 numpy 数组一样被切片,然后连接成一个张量。假设您从第一个元素开始测量序列长度。
使用[row_idx,column_idx]对张量进行切片。 slice = array[0,:]
会将第一行分配给切片。
flat_slices = tf.concat([slice,slice])
会将它们展平为一个张量。
import tensorflow as tf
seq_len = [11,12,20,30]
array = tf.ones([4,30])
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
flatten = array[0,:seq_len[0]]
for i in range(1,len(seq_len)):
row = array[i,:seq_len[i]]
flatten = tf.concat([flatten, row])
print(sess.run(flatten))
我只想选择张量每一行中的特定列,将其用于 RNN
seq_len=[11,12,20,30] #This is the sequence length, assume 4 sequences
array=tf.ones([4,30]) #Assuming this is the array I want to index from
function(array,seq_len) #apply required function
Output=(first 11 elements from row 0, first 12 from row 2, first 20 from row 3 etc), perhaps obtained as a flat tensor
您可以使用 tf.sequence_mask
and tf.boolean_mask
将它们压平:
mask = tf.sequence_mask(seq_len, MAX_LENGTH) # Replace MAX_LENGTH with the size of array on the right dimension, 30 in your case
output= tf.boolean_mask(array, mask=mask)
tensorflow 中的张量可以像 numpy 数组一样被切片,然后连接成一个张量。假设您从第一个元素开始测量序列长度。
使用[row_idx,column_idx]对张量进行切片。 slice = array[0,:]
会将第一行分配给切片。
flat_slices = tf.concat([slice,slice])
会将它们展平为一个张量。
import tensorflow as tf
seq_len = [11,12,20,30]
array = tf.ones([4,30])
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
flatten = array[0,:seq_len[0]]
for i in range(1,len(seq_len)):
row = array[i,:seq_len[i]]
flatten = tf.concat([flatten, row])
print(sess.run(flatten))