Apply into NumpyΒΆ

In following parts, we will show some demos about how to use TreeValue in practice.

For example, now we have a group of structed data in python-dict type, we want to do different operations on differnent key-value pairs inplace, get some statistics such as mean value and task some slices.

In normal cases, we need to unroll multiple for-loop and if-else to implement cooresponding operations on each values, and declare additional temporal variables to save result. All the mentioned contents are executed serially, like the next code examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import numpy as np

T, B = 3, 4


def without_treevalue(batch_):
    mean_b_list = []
    even_index_a_list = []
    for i in range(len(batch_)):
        for k, v in batch_[i].items():
            if k == 'a':
                v = v.astype(np.float32)
                even_index_a_list.append(v[::2])
            elif k == 'b':
                v = v.astype(np.float32)
                transformed_v = np.power(v, 2) + 1.0
                mean_b_list.append(transformed_v.mean())
            elif k == 'c':
                for k1, v1 in v.items():
                    if k1 == 'd':
                        v1 = v1.astype(np.float32)
                    else:
                        print('ignore keys: {}'.format(k1))
            else:
                print('ignore keys: {}'.format(k))
    for i in range(len(batch_)):
        for k in batch_[i].keys():
            if k == 'd':
                batch_[i][k]['noise'] = np.random.random(size=(3, 4, 5))

    mean_b = sum(mean_b_list) / len(mean_b_list)
    even_index_a = np.stack(even_index_a_list, axis=0)
    return batch_, mean_b, even_index_a

However, with the help of TreeValue, all the contents mentioned above can be implemented gracefully and efficiently. Users only need to func_treelize the primitive numpy functions and pack data with FastTreeValue, then execute desired operations just like using standard numpy array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np

from treevalue import FastTreeValue

T, B = 3, 4
power = FastTreeValue.func()(np.power)
stack = FastTreeValue.func(subside=True)(np.stack)
split = FastTreeValue.func(rise=True)(np.split)


def with_treevalue(batch_):
    batch_ = [FastTreeValue(b) for b in batch_]
    batch_ = stack(batch_)
    batch_ = batch_.astype(np.float32)
    batch_.b = power(batch_.b, 2) + 1.0
    batch_.c.noise = np.random.random(size=(B, 3, 4, 5))
    mean_b = batch_.b.mean()
    even_index_a = batch_.a[:, ::2]
    batch_ = split(batch_, indices_or_sections=B, axis=0)
    return batch_, mean_b, even_index_a

And we can run these two demos for comparison:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import copy

import numpy as np
from with_treevalue import with_treevalue
from without_treevalue import without_treevalue

T, B = 3, 4


def get_data():
    return {
        'a': np.random.random(size=(T, 8)),
        'b': np.random.random(size=(6,)),
        'c': {
            'd': np.random.randint(0, 10, size=(1,))
        }
    }


if __name__ == "__main__":
    batch = [get_data() for _ in range(B)]
    batch0, mean0, even_index_a0 = without_treevalue(copy.deepcopy(batch))
    batch1, mean1, even_index_a1 = with_treevalue(copy.deepcopy(batch))

    assert np.abs(mean0 - mean1) < 1e-6
    print('mean0 & mean1:', mean0, mean1)
    print('\n')

    assert np.abs((even_index_a0 - even_index_a1).max()) < 1e-6
    print('even_index_a0:', even_index_a0)
    print('even_index_a1:', even_index_a1)

    assert len(batch0) == B
    assert len(batch1) == B

The final output should be the text below, and all the assertions can be passed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
mean0 & mean1: 1.3955787122249603 1.3955787


even_index_a0: [[[5.1452136e-01 1.8438244e-01 9.3499798e-01 2.5850800e-01 3.6469641e-01
   8.3754748e-01 9.0492517e-01 5.4862177e-01]
  [1.0226905e-01 2.6911643e-01 6.7684621e-02 6.6689344e-04 2.1283401e-02
   9.2628372e-01 6.1325496e-01 5.9466505e-01]]

 [[1.4683020e-01 9.2783970e-01 2.4565086e-01 6.6967320e-01 2.4383368e-01
   6.1040795e-01 2.3651417e-01 1.6267212e-01]
  [2.9862899e-01 9.2607784e-01 9.4328642e-01 3.9998081e-01 9.2372555e-01
   4.1514084e-01 4.9161145e-01 4.7637749e-01]]

 [[7.5572556e-01 1.3772760e-01 7.1126527e-01 3.7145719e-01 6.5381008e-01
   6.8081570e-01 7.9728752e-01 7.7042329e-01]
  [3.3643541e-01 6.3486540e-01 4.9206972e-01 4.7115767e-01 4.7682968e-01
   2.2475363e-01 8.7613118e-01 6.2053466e-01]]

 [[5.9461098e-02 6.7617261e-01 8.6421484e-01 3.7431309e-01 7.0943636e-01
   9.8804891e-01 2.0800132e-01 4.6409270e-01]
  [9.4657131e-03 5.0013828e-01 5.7305139e-01 9.4412142e-01 8.5023439e-01
   3.4462687e-01 6.4292885e-02 4.1164875e-02]]]
even_index_a1: [[[5.1452136e-01 1.8438244e-01 9.3499798e-01 2.5850800e-01 3.6469641e-01
   8.3754748e-01 9.0492517e-01 5.4862177e-01]
  [1.0226905e-01 2.6911643e-01 6.7684621e-02 6.6689344e-04 2.1283401e-02
   9.2628372e-01 6.1325496e-01 5.9466505e-01]]

 [[1.4683020e-01 9.2783970e-01 2.4565086e-01 6.6967320e-01 2.4383368e-01
   6.1040795e-01 2.3651417e-01 1.6267212e-01]
  [2.9862899e-01 9.2607784e-01 9.4328642e-01 3.9998081e-01 9.2372555e-01
   4.1514084e-01 4.9161145e-01 4.7637749e-01]]

 [[7.5572556e-01 1.3772760e-01 7.1126527e-01 3.7145719e-01 6.5381008e-01
   6.8081570e-01 7.9728752e-01 7.7042329e-01]
  [3.3643541e-01 6.3486540e-01 4.9206972e-01 4.7115767e-01 4.7682968e-01
   2.2475363e-01 8.7613118e-01 6.2053466e-01]]

 [[5.9461098e-02 6.7617261e-01 8.6421484e-01 3.7431309e-01 7.0943636e-01
   9.8804891e-01 2.0800132e-01 4.6409270e-01]
  [9.4657131e-03 5.0013828e-01 5.7305139e-01 9.4412142e-01 8.5023439e-01
   3.4462687e-01 6.4292885e-02 4.1164875e-02]]]

In this case, we can see that the TreeValue can be properly applied into the numpy library. The tree-structured matrix calculation can be easily built with TreeValue like using standard numpy array.

Both the simplicity of logic structure and execution efficiency can be improve a lot.

And Last but not least, the only thing you need to do is to wrap the functions in Numpy library, and then use it painlessly like the primitive numpy.