Coverage for src/bob/fusion/base/preprocessor/Tanh.py: 100%

26 statements  

« prev     ^ index     » next       coverage.py v7.6.5, created at 2024-11-14 22:15 +0100

1import numpy as np 

2 

3from sklearn.preprocessing import StandardScaler 

4 

5# to fix the sphinx docs 

6StandardScaler.__module__ = "sklearn.preprocessing" 

7 

8 

9class Tanh(StandardScaler): 

10 """A tanh feature scaler: 

11 

12 .. math:: 

13 

14 0.5 \\left( \\tanh\\left( 0.01 \\cdot \\frac{X - \\mu}{\\sigma}\\right) + 1 \\right) 

15 

16 This scaler is both efficient and is robust to outliers. 

17 

18 The original implementation in ``Hampel, Frank R., et al. "Robust 

19 statistics: the approach based on influence functions." (1986).`` uses an 

20 influence function but this is not used here. 

21 """ 

22 

23 def __init__(self, copy=True, **kwargs): 

24 """Initialize self. See help(type(self)) for accurate signature.""" 

25 super(Tanh, self).__init__( 

26 copy=copy, with_mean=True, with_std=True, **kwargs 

27 ) 

28 

29 def fit(self, X, y=None): 

30 """Estimates the mean and standard deviation of samples. 

31 Only positive samples are used in estimation. 

32 """ 

33 # the fitting is done only on positive samples 

34 if y is not None: 

35 X = np.asarray(X)[y, ...] 

36 return super(Tanh, self).fit(X) 

37 

38 def transform(self, X, copy=None): 

39 """Perform scaling.""" 

40 X = super(Tanh, self).transform(X, copy=copy) 

41 X *= 0.01 

42 X = np.tanh(X, out=X) 

43 X += 1 

44 X *= 0.5 

45 return X 

46 

47 def inverse_transform(self, X, copy=None): 

48 """Perform inverse scaling.""" 

49 copy = copy if copy is not None else self.copy 

50 if copy: 

51 X = X.copy() 

52 X *= 2 

53 X -= 1 

54 X = np.arctanh(X, out=X) 

55 X *= 100 

56 return super(Tanh, self).inverse_transform(X, copy=copy)