tf.slice 和 tf.strided_sli

2024-06-03 04:21:25 发布

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

试着理解张量流跨步切片

x = tf.constant(np.array(   [[[111, 112, 113], [121, 122, 123]],
                            [[211, 212, 213], [221, 222, 223]],
                            [[311, 312, 313], [321, 322, 323]]]))
with tf.Session() as sess:
    print("tf.shape ------------------")
    print(sess.run(tf.shape(x)))
    print("tf.slice ------------------------")
    print(sess.run((tf.slice(x, [1, 0, 0], [2, 1, 3]) )))
    print("tf.strided_slice ------------------------")
    print(sess.run(tf.strided_slice(x, [1, 0, 0], [2, 1, 3], [1, 1, 1])))
    print(sess.run(tf.strided_slice(x, [1, -1, 0], [2, -3, 3], [1, -1, 1])))
    print(sess.run(x[1,-1,0]))
    print(sess.run(x[2,-3,3]))

输出

^{pr2}$

为tf.切片我知道我们必须提到每个维度的切片大小,因此超出范围的值是有意义的。但在跨步切片的末尾是张量本身的一个张量索引,怎么出来的大小值是有效的。在

示例取自 https://www.tensorflow.org/api_docs/python/tf/strided_slice

尝试从纸张A Convolutional Neural Network for Modelling Sentences实现折叠层部分

In the formulation of the network so far, feature detectors applied to an individual row of the sentence matrix s can have many orders and create complex dependencies across the same rows in multiple feature maps. Feature detectors in different rows, however, are independent of each other until the top fully connected layer. Full dependence between different rows could be achieved by making M in Eq. 5 a full matrix instead of a sparse matrix of diagonals. Here we explore a simpler method called folding that does not introduce any additional parameters. After a convolutional layer and before (dynamic) k-max pooling, one just sums every two rows in a feature map component-wise. For a map of d rows, folding returns a map of d/2 rows, thus halving the size of the representation. With a folding layer, a feature detector of the i-th order depends now on two rows of feature values in the lower maps of order i − 1. This ends the description of the DCNN.


Tags: oftheruninlayertf切片slice
1条回答
网友
1楼 · 发布于 2024-06-03 04:21:25

产生的ValueError与前2次对striped_Slice的调用无关。在中,您对跨行切片操作的使用是正确的

print(sess.run(tf.strided_slice(x, [1, 0, 0], [2, 1, 3], [1, 1, 1])))

print(sess.run(tf.strided_slice(x, [1, -1, 0], [2, -3, 3], [1, -1, 1])))

你的问题是

print(sess.run(x[2,-3,3]))

python数组中的负索引在数组中反向迭代。在

例如,给定一个这样的数组

arr = ['a', 'b', 'c', 'd', 'e', 'f']

调用arr[-1]将产生“f”。类似地,对arr[-4]的调用将产生“c”。如果我们试着打给arr[-7]会怎么样?这将尝试访问索引-1,这将引发一个错误。在

请记住,Python中的数组具有基于0的索引。对x[2,-3,3]的调用首先访问外部数组中索引2(第3个元素)处的元素,它是

^{pr2}$

现在,在这个外部数组中,有两个元素。但是,调用x[2,-3,3]试图访问索引-1处的元素,因为它从数组的末尾迭代。这就是产生错误的原因

slice index -1 of dimension 1 out of bounds

注意:您在x[2,-3,3]中尝试访问的最后一个索引也会产生ValueError,因为它试图访问不在数组中的索引。要解决这个问题,您可以调用x[2,-2,2]。在

以下是一些关于Python中的跨步切片、切片和数组索引的链接: https://www.tensorflow.org/api_docs/python/tf/strided_slice

https://www.tensorflow.org/api_docs/python/tf/slice

Negative list index?

相关问题 更多 >