├── README.md └── GAF.py /README.md: -------------------------------------------------------------------------------- 1 | # Gramian-Angular-Field-in-Pytorch 2 | A implementation of Gramian Angular Field (GAF) in Pytorch. 3 | -------------------------------------------------------------------------------- /GAF.py: -------------------------------------------------------------------------------- 1 | import torch 2 | class GramianAngularFieldPytorch(object): 3 | """Gramian Angular Field. 4 | 5 | Parameters 6 | ---------- 7 | method : 'summation' or 'difference' (default = 'summation') 8 | Type of Gramian Angular Field. 's' can be used for 'summation' 9 | and 'd' for 'difference'. 10 | 11 | References 12 | ---------- 13 | .. [1] Z. Wang and T. Oates, "Encoding Time Series as Images for Visual 14 | Inspection and Classification Using Tiled Convolutional Neural 15 | Networks." AAAI Workshop (2015). 16 | 17 | """ 18 | 19 | def __init__(self, method='summation'): 20 | self.method = method 21 | 22 | def min_max_norm(self, X): 23 | min_val = torch.min(X, dim=-1, keepdim=True)[0] 24 | max_val = torch.max(X, dim=-1, keepdim=True)[0] 25 | res = (X - min_val) / (max_val - min_val) 26 | return res * 2 - 1 27 | 28 | @staticmethod 29 | def _gasf(X_cos, X_sin): 30 | 31 | X_cos_L = X_cos.unsqueeze(-1) 32 | X_cos_R = X_cos.unsqueeze(-2) 33 | 34 | X_sin_L = X_sin.unsqueeze(-1) 35 | X_sin_R = X_sin.unsqueeze(-2) 36 | 37 | X_gasf = torch.bmm(X_cos_L, X_cos_R) - torch.bmm(X_sin_L, X_sin_R) 38 | 39 | return X_gasf 40 | 41 | @staticmethod 42 | def _gadf(X_cos, X_sin): 43 | 44 | X_sin_L = X_sin.unsqueeze(-1) 45 | X_cos_R = X_cos.unsqueeze(-2) 46 | 47 | X_cos_L = X_cos.unsqueeze(-1) 48 | X_sin_R = X_sin.unsqueeze(-2) 49 | 50 | X_gadf = torch.bmm(X_sin_L, X_cos_R) - torch.bmm(X_cos_L, X_sin_R) 51 | 52 | return X_gadf 53 | 54 | def transform(self, X): 55 | """Transform each time series into a GAF image. 56 | 57 | Parameters 58 | ---------- 59 | X : array-like, shape = (n_samples, n_timestamps) 60 | 61 | Returns 62 | ------- 63 | X_new : array-like, shape = (n_samples, image_size, image_size) 64 | Transformed data. If ``flatten=True``, the shape is 65 | `(n_samples, image_size * image_size)`. 66 | 67 | """ 68 | X_cos = self.min_max_norm(X) 69 | X_sin = torch.sqrt(torch.clip(1 - X_cos ** 2, 0, 1)) 70 | if self.method in ['s', 'summation']: 71 | X_new = self._gasf(X_cos, X_sin) 72 | else: 73 | X_new = self._gadf(X_cos, X_sin) 74 | return X_new --------------------------------------------------------------------------------