以十为单位的索引张量指定的切片2d张量

2024-03-29 00:00:08 发布

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

我有一个二维张量,我想从每一行提取一些起始元素。
每个元素的索引必须小于或等于I行 请注意,不同行的列索引不同。
下面的示例使其合并:
二维张量为:

[[4 2 4 4 1 1 1 1 1 1 1 1 1 1 1 1]  
 [4 4 4 4 4 4 4 1 1 1 1 1 1 1 1 1]  
 [4 4 4 5 4 4 4 1 1 1 1 1 1 1 1 1]  
 [4 4 1 4 4 4 4 1 1 1 1 1 1 1 1 1]  
 [4 4 4 4 6 4 4 8 8 1 1 1 1 1 1 1]  
 [3 9 9 9 9 9 9 1 1 1 1 1 1 1 1 1]  
 [3 9 9 9 9 9 9 1 1 1 1 1 1 1 1 1]  
 [1 9 9 9 9 9 9 1 1 1 1 1 1 1 1 1]  
 [3 9 4 9 9 9 9 1 1 1 1 1 1 1 1 1]  
 [3 9 9 6 9 9 9 1 1 1 1 1 1 1 1 1]]  

索引数组是:

^{pr2}$

如何从上面的索引数组中获取以下数组:

[[4 2 4 4 ]  
 [4 4 4 4 4 4 4 ]  
 [4 4 4 5 4 4 4]  
 [4 4 1 4 4 4 4]  
 [4 4 4 4 6 4 4 8 8]  
 [3 9 9 9 9 9 9 ]  
 [3 9 9 9 9 9 9 ]  
 [1 9 9 9 9 9 9 ]  
 [3 9 4 9 9 9 9 ]  
 [3 9 9 6 9 9 9 ]]  

Tags: 元素示例数组pr2
1条回答
网友
1楼 · 发布于 2024-03-29 00:00:08

这里有一种将其作为稀疏张量的方法:

import tensorflow as tf

# Example data
data = [[4, 2, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [4, 4, 4, 5, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [4, 4, 1, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [4, 4, 4, 4, 6, 4, 4, 8, 8, 1, 1, 1, 1, 1, 1, 1],
        [3, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [3, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [3, 9, 4, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [3, 9, 9, 6, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
sizes = [4, 7, 7, 7, 9, 7, 7, 7, 7, 7]

with tf.Graph().as_default():
    # Input data
    data_ph = tf.placeholder(tf.int32, [None, None])
    sizes_ph = tf.placeholder(tf.int32, [None])
    shape = tf.shape(data_ph)
    # Make coordinates grid
    ii, jj = tf.meshgrid(tf.range(shape[0]), tf.range(shape[1]), indexing='ij')
    # Make mask for values
    mask = jj < tf.expand_dims(sizes_ph, 1)
    # Take values and coordinates
    sp_values = tf.boolean_mask(data_ph, mask)
    sp_ii = tf.boolean_mask(ii, mask)
    sp_jj = tf.boolean_mask(jj, mask)
    # Make sparse index
    sp_idx = tf.cast(tf.stack([sp_ii, sp_jj], axis=1), tf.int64)
    # Make sparse tensor
    sp_tensor = tf.sparse.SparseTensor(sp_idx, sp_values, tf.cast(shape, tf.int64))
    # Convert back to dense for testing
    sp_to_dense = tf.sparse.to_dense(sp_tensor)
    # Test
    with tf.Session() as sess:
        sp_to_dense_value = sess.run(sp_to_dense, feed_dict={data_ph: data, sizes_ph: sizes})
        print(sp_to_dense_value)

输出:

^{pr2}$

它并不是绝对理想的,因为它需要在整个坐标网格下运行。在NumPy中,您可能可以先生成索引,然后从稠密张量中只选择所需的值,但我不确定在TensorFlow中是否可行。在

相关问题 更多 >