Apply into Scikit-Learn

Actually, TreeValue can be used in practice with not only numpy or torch library, such as scikit-learn. In the following part, a demo of PCA to tree-structured arrays will be shown.

In the field of traditional machine learning, PCA (Principal Component Analysis) is often used to preprocess data, by normalizing the data range, and trying to reduce the dimensionality of the data, so as to reduce the complexity of the input data and improve machine learning’s efficiency and quality. Just as the following image

PCA Principle

PCA in a nutshell. Source: Lavrenko and Sutton 2011, slide 13.

In the scikit-learn library, the PCA class is provided to support this function, and the function fit_transform can be used to simplify the data. For a set of np.array format data that presents a tree structure, we can implement the operation support for the tree structure by quickly wrapping the function fit_transform. The specific code is as follows

 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 sklearn.decomposition import PCA

from treevalue import FastTreeValue

fit_transform = FastTreeValue.func()(lambda x: PCA(min(*x.shape)).fit_transform(x))

if __name__ == '__main__':
    data = FastTreeValue({
        'a': np.random.randint(-5, 15, (4, 3)),
        'x': {
            'c': np.random.randint(-15, 5, (5, 4)),
        }
    })
    print("Original int data:")
    print(data)

    pdata = fit_transform(data)
    print("Fit transformed data:")
    print(pdata)

The output should be

 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
Original int data:
<FastTreeValue 0x7fc10d3b7a30>
├── 'a' --> array([[-5,  7,  2],
│                  [ 1, -2, -3],
│                  [ 0,  1,  4],
│                  [ 6, 10, -4]])
└── 'x' --> <FastTreeValue 0x7fc10d66cdf0>
    └── 'c' --> array([[-13, -11, -11,   0],
                       [  1, -12, -14,   4],
                       [ -8,  -3,  -2,  -8],
                       [ -7, -11,  -9,  -8],
                       [ -2,   1,  -8, -10]])

Fit transformed data:
<FastTreeValue 0x7fc10643bd60>
├── 'a' --> array([[-1.92982181,  6.14353815, -1.68678   ],
│                  [-2.73058859, -5.74503184, -1.83057235],
│                  [-4.27676035,  0.0204228 ,  3.00356518],
│                  [ 8.93717076, -0.41892911,  0.51378717]])
└── 'x' --> <FastTreeValue 0x7fc10d698160>
    └── 'c' --> array([[ 5.69860467,  7.13997018, -1.88023972, -1.86853667],
                       [11.18683516, -6.33053723, -0.64532575,  1.11470716],
                       [-8.06639231,  2.33390856, -1.88325158,  2.76035314],
                       [-0.06918246,  2.47137445,  4.75992566,  0.33261058],
                       [-8.74986507, -5.61471595, -0.35110861, -2.33913421]])

For further information, see the links below: