如何迭代3维张量

时间:2018-04-29 01:13:54

标签: numpy iteration tensor

我有张量说:

y_true = np.array([[[1.], [0.], [3.]], [[5.], [0.], [0.]]])

我想迭代y_true访问所有不确定的值。我想在java中执行以下操作:

for(i=0;i<y_true.length;i++){
    arr2 = y_true[i];
    for(j=0;j<arr2.length;j++){
        print(arr2[j][0])
    }
}. 

3 个答案:

答案 0 :(得分:0)

您是否正在寻找[:,:,0]切片?

>>> y_true[:,:,0]
array([[1., 0., 3.],
       [5., 0., 0.]])

答案 1 :(得分:0)

有两种情况:

  1. 您知道示例y_true数组中创建的numpy数组的等级(维度)等级为3,您可以检查y_true.shape属性,该属性应该为您提供精确的大小y_true的每个维度,然后您可以为y_true的等级编写多个循环,并分别输出每个元素,例如:

    import numpy as np
    
    y_true = np.array([[[1.], [0.], [3.]], [[5.], [0.], [0.]]])
    dims = y_true.shape
    for i in range(dims[0]):
        for j in range(dims[1]):
            for k in range(dims[2]):
                print("Element of np array with indices {} is equal to {}".format([i, j, k], y_true[i, j, k]))
    
  2. 如果您不知道要打印的张量的等级,那么您可以编写将打印所有元素的递归函数,例如:

    import numpy as np    
    
    
    def recursively_print_elems(np_arr, idx, pos):
        if pos >= len(np_arr.shape):
            print("Element of np array with indeces {} is equal to: {}".format(idx, np_arr[tuple(idx)]))
            return
        for i in range(np_arr.shape[pos]):
            idx[pos] = i
            recursively_print_elems(np_arr, idx, pos + 1)
    
    
    def print_elems(np_arr):
        idx = [0] * len(np_arr.shape)
        recursively_print_elems(np_arr, idx, 0)
    
    
    y_true = np.array([[[1.], [0.], [3.]], [[5.], [0.], [0.]]])
    print_elems(y_true)
    
  3. 第二种方法更为通用,它适用于任何尺寸张量。

答案 2 :(得分:0)

你的阵列:

In [19]: y_true
Out[19]: 
array([[[1.],
        [0.],
        [3.]],

       [[5.],
        [0.],
        [0.]]])
In [20]: y_true.shape
Out[20]: (2, 3, 1)

如果最后一个尺寸为1,我们可以重塑它

In [21]: y_true.reshape(2,3)
Out[21]: 
array([[1., 0., 3.],
       [5., 0., 0.]])

选择该指数同样如此。

但是你可以通过raveling / flattening来按顺序访问所有值:

In [22]: y_true.ravel()
Out[22]: array([1., 0., 3., 5., 0., 0.])

或者获得1个迭代器:

In [23]: yiter = y_true.flat
In [24]: yiter?
Type:            flatiter
String form:     <numpy.flatiter object at 0x1fdd200>
Length:          6
File:            ~/.local/lib/python3.6/site-packages/numpy/__init__.py
Docstring:       <no docstring>
Class docstring:
Flat iterator object to iterate over arrays.

A `flatiter` iterator is returned by ``x.flat`` for any array `x`.
It allows iterating over the array as if it were a 1-D array,
either in a for-loop or by calling its `next` method.
...

因此,不是为每个维度构造迭代器,而是可以迭代这个平面:

In [25]: for item in yiter:print(item)
1.0
0.0
3.0
5.0
0.0
0.0

ndenumerate使用这个平面迭代器,并返回坐标和值:

In [26]: list(np.ndenumerate(y_true))
Out[26]: 
[((0, 0, 0), 1.0),
 ((0, 1, 0), 0.0),
 ((0, 2, 0), 3.0),
 ((1, 0, 0), 5.0),
 ((1, 1, 0), 0.0),
 ((1, 2, 0), 0.0)]

对此的变体是ndindex

In [27]: indexs = np.ndindex(y_true.shape)
In [28]: for ijk in indexs:
    ...:     print(ijk, y_true[ijk])
    ...:     
(0, 0, 0) 1.0
(0, 1, 0) 0.0
(0, 2, 0) 3.0
(1, 0, 0) 5.0
(1, 1, 0) 0.0
(1, 2, 0) 0.0

但是在可能的情况下,最好对整个阵列进行操作,而不是迭代。这些全数组操作在编译代码中进行迭代。