【问题标题】:Tensorflow: How to slice tensor with number of dimension not changed?Tensorflow:如何在维数不变的情况下对张量进行切片?
【发布时间】:2018-08-03 09:57:11
【问题描述】:

例如,如果我们有:

a = tf.constant(np.eye(5))
a
<tf.Tensor 'Const:0' shape=(5, 5) dtype=float64>
a[0,:]
<tf.Tensor 'strided_slice:0' shape=(5,) dtype=float64>

张量切片a会将原来的维数2减少到1

我怎么能直接得到排名不变的切片:?

a[0,:]
<tf.Tensor 'strided_slice:0' shape=(1,5) dtype=float64>

tf.expand_dims(a[0,:], axis=0) 可以,但是有没有更直接更简单的方法?)

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    至少有两种直接方式,与 NumPy (related question) 中可用的方式非常相似。

    1. 获取该轴上大小为 1 的范围:a[x:x+1]
    2. None添加一个轴:a[None, x]
    a[0:1]
    
    <tf.Tensor 'strided_slice_1:0' shape=(1, 5) dtype=float64>
    

    一些实际的张量运行显示了预期的结果。

    with tf.Session() as sess:
        sess.run(a[0])
        sess.run(a[0:1])
        sess.run(a[None, 0])
    
    array([1., 0., 0., 0., 0.])
    array([[1., 0., 0., 0., 0.]])
    array([[1., 0., 0., 0., 0.]])
    

    【讨论】:

      猜你喜欢
      • 2018-02-24
      • 2016-05-22
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2017-06-02
      • 2019-08-06
      • 1970-01-01
      相关资源
      最近更新 更多