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
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 0x7f2c16ebe7c0> ├── a --> array([[12, 6, 7], │ [14, -3, 0], │ [11, 10, 4], │ [-2, 3, -3]]) └── x --> <FastTreeValue 0x7f2c16f13ee0> └── c --> array([[ -6, 1, 3, -2], [ -6, -4, -4, -11], [ -3, -3, 3, 2], [ -6, -9, -12, -13], [ 1, -13, -13, -5]]) Fit transformed data: <FastTreeValue 0x7f2c16ebea30> ├── a --> array([[-5.42687701, -2.43213506, 2.04846893], │ [-2.73785511, 8.53273298, -0.50903573], │ [-3.70364751, -5.30224485, -1.79769148], │ [11.86837963, -0.79835306, 0.25825828]]) └── x --> <FastTreeValue 0x7f2c16017e80> └── c --> array([[ 10.73865999, -1.84402027, -0.7800411 , -0.65750032], [ -0.94859843, -5.62047827, 1.19926763, -0.17928235], [ 10.35410991, 4.30291895, 0.25195567, 0.75750571], [-10.22775372, -4.07719699, -0.80209088, 0.53494737], [ -9.91641775, 7.23877659, 0.13090868, -0.45567041]]) |
For further information, see the links below: