aboutsummaryrefslogtreecommitdiff
path: root/code/sunlab/common/scaler/quantile_scaler.py
blob: a0f53fd391e8e57cecb5c15a68b4ab11f4c2bd04 (plain)
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
42
43
44
45
46
47
48
49
50
51
52
from .adversarial_scaler import AdversarialScaler


class QuantileScaler(AdversarialScaler):
    """# QuantileScaler

    Scale the data based on the quantile distributions of each column"""

    def __init__(self, base_directory):
        """# QuantileScaler initialization

        - Initialize the base directory of the model where it will live
        - Initialize the scaler model"""
        super().__init__(base_directory)
        from sklearn.preprocessing import QuantileTransformer as QS

        self.scaler_base = QS()
        self.scaler = None

    def init(self, data):
        """# Scaler initialization

        Initialize the scaler transformation with the data"""
        self.scaler = self.scaler_base.fit(data)
        return self

    def load(self):
        """# Scaler loading

        Load the data scaler model from a file"""
        from pickle import load

        with open(
            f"{self.base_directory}/portable/quantile_scaler.pkl", "rb"
        ) as fhandle:
            self.scaler = load(fhandle)
        return self

    def save(self):
        """# Scaler saving

        Save the data scaler model"""
        from pickle import dump

        with open(
            f"{self.base_directory}/portable/quantile_scaler.pkl", "wb"
        ) as fhandle:
            dump(self.scaler, fhandle)

    def __call__(self, *args, **kwargs):
        """# Scale the given data"""
        return self.scaler.transform(*args, **kwargs)