tirex-mirror 2025.11.29__py3-none-any.whl → 2025.12.16__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ # Copyright (c) NXAI GmbH.
2
+ # This software may be used and distributed according to the terms of the NXAI Community License Agreement.
3
+
4
+ import torch
5
+
6
+ from .base_tirex import BaseTirexEmbeddingModel
7
+
8
+
9
+ class BaseTirexClassifier(BaseTirexEmbeddingModel):
10
+ """Abstract base class for TiRex classification models."""
11
+
12
+ @torch.inference_mode()
13
+ def predict(self, x: torch.Tensor) -> torch.Tensor:
14
+ """Predict class labels for input time series data.
15
+
16
+ Args:
17
+ x: Input time series data as torch.Tensor with shape
18
+ (batch_size, num_variates, seq_len).
19
+ Returns:
20
+ torch.Tensor: Predicted class labels with shape (batch_size,).
21
+ """
22
+ emb = self._compute_embeddings(x)
23
+ return torch.from_numpy(self.head.predict(emb)).long()
24
+
25
+ @torch.inference_mode()
26
+ def predict_proba(self, x: torch.Tensor) -> torch.Tensor:
27
+ """Predict class probabilities for input time series data.
28
+
29
+ Args:
30
+ x: Input time series data as torch.Tensor with shape
31
+ (batch_size, num_variates, seq_len).
32
+ Returns:
33
+ torch.Tensor: Class probabilities with shape (batch_size, num_classes).
34
+ """
35
+ emb = self._compute_embeddings(x)
36
+ return torch.from_numpy(self.head.predict_proba(emb))
@@ -0,0 +1,23 @@
1
+ # Copyright (c) NXAI GmbH.
2
+ # This software may be used and distributed according to the terms of the NXAI Community License Agreement.
3
+
4
+ import torch
5
+
6
+ from .base_tirex import BaseTirexEmbeddingModel
7
+
8
+
9
+ class BaseTirexRegressor(BaseTirexEmbeddingModel):
10
+ """Abstract base class for TiRex regression models."""
11
+
12
+ @torch.inference_mode()
13
+ def predict(self, x: torch.Tensor) -> torch.Tensor:
14
+ """Predict values for input time series data.
15
+
16
+ Args:
17
+ x: Input time series data as torch.Tensor with shape
18
+ (batch_size, num_variates, seq_len).
19
+ Returns:
20
+ torch.Tensor: Predicted values with shape (batch_size,).
21
+ """
22
+ emb = self._compute_embeddings(x)
23
+ return torch.from_numpy(self.head.predict(emb)).float()
@@ -0,0 +1,109 @@
1
+ # Copyright (c) NXAI GmbH.
2
+ # This software may be used and distributed according to the terms of the NXAI Community License Agreement.
3
+
4
+ from abc import ABC, abstractmethod
5
+
6
+ import numpy as np
7
+ import torch
8
+
9
+ from tirex.util import train_val_split
10
+
11
+ from ..embedding import TiRexEmbedding
12
+
13
+
14
+ class BaseTirexEmbeddingModel(ABC):
15
+ """Abstract base class for TiRex models.
16
+
17
+ This base class provides common functionality for all TiRex classifier and regression models,
18
+ including embedding model initialization and a consistent interface.
19
+
20
+ """
21
+
22
+ def __init__(
23
+ self, data_augmentation: bool = False, device: str | None = None, compile: bool = False, batch_size: int = 512
24
+ ) -> None:
25
+ """Initializes a base TiRex model.
26
+
27
+ This base class initializes the embedding model and common configuration
28
+ used by both classification and regression models.
29
+
30
+ Args:
31
+ data_augmentation : bool
32
+ Whether to use data_augmentation for embeddings (sample statistics and first-order differences of the original data). Default: False
33
+ device : str | None
34
+ Device to run the embedding model on. If None, uses CUDA if available, else CPU. Default: None
35
+ compile: bool
36
+ Whether to compile the frozen embedding model. Default: False
37
+ batch_size : int
38
+ Batch size for embedding calculations. Default: 512
39
+ """
40
+
41
+ # Set device
42
+ if device is None:
43
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
44
+ self.device = device
45
+ self._compile = compile
46
+
47
+ self.batch_size = batch_size
48
+ self.data_augmentation = data_augmentation
49
+ self.emb_model = TiRexEmbedding(
50
+ device=self.device,
51
+ data_augmentation=self.data_augmentation,
52
+ batch_size=self.batch_size,
53
+ compile=self._compile,
54
+ )
55
+
56
+ @abstractmethod
57
+ def fit(self, train_data: tuple[torch.Tensor, torch.Tensor]) -> None:
58
+ """Abstract method for model training"""
59
+ pass
60
+
61
+ def _compute_embeddings(self, x: torch.Tensor) -> np.ndarray:
62
+ """Compute embeddings for input time series data.
63
+
64
+ Args:
65
+ x: Input time series data as torch.Tensor with shape
66
+ (batch_size, num_variates, seq_len).
67
+
68
+ Returns:
69
+ np.ndarray: Embeddings with shape (batch_size, embedding_dim).
70
+ """
71
+ self.emb_model.eval()
72
+ x = x.to(self.device)
73
+ return self.emb_model(x).cpu().numpy()
74
+
75
+ def _create_train_val_datasets(
76
+ self,
77
+ train_data: tuple[torch.Tensor, torch.Tensor],
78
+ val_data: tuple[torch.Tensor, torch.Tensor] | None = None,
79
+ val_split_ratio: float = 0.2,
80
+ stratify: bool = False,
81
+ seed: int | None = None,
82
+ ) -> tuple[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor, torch.Tensor]]:
83
+ if val_data is None:
84
+ train_data, val_data = train_val_split(
85
+ train_data=train_data, val_split_ratio=val_split_ratio, stratify=stratify, seed=seed
86
+ )
87
+ return train_data, val_data
88
+
89
+ @abstractmethod
90
+ def save_model(self, path: str) -> None:
91
+ """Save model to file.
92
+
93
+ Args:
94
+ path: File path where the model should be saved.
95
+ """
96
+ pass
97
+
98
+ @classmethod
99
+ @abstractmethod
100
+ def load_model(cls, path: str):
101
+ """Load model from file.
102
+
103
+ Args:
104
+ path: File path to the saved model checkpoint.
105
+
106
+ Returns:
107
+ Instance of the model class with loaded weights and configuration.
108
+ """
109
+ pass
@@ -1,8 +1,8 @@
1
- # classification/__init__.py
2
- from .linear_classifier import TirexClassifierTorch
1
+ # Copyright (c) NXAI GmbH.
2
+ # This software may be used and distributed according to the terms of the NXAI Community License Agreement.
3
+
4
+ from .gbm_classifier import TirexGBMClassifier
5
+ from .linear_classifier import TirexLinearClassifier
3
6
  from .rf_classifier import TirexRFClassifier
4
7
 
5
- __all__ = [
6
- "TirexClassifierTorch",
7
- "TirexRFClassifier",
8
- ]
8
+ __all__ = ["TirexLinearClassifier", "TirexRFClassifier", "TirexGBMClassifier"]
@@ -0,0 +1,188 @@
1
+ # Copyright (c) NXAI GmbH.
2
+ # This software may be used and distributed according to the terms of the NXAI Community License Agreement.
3
+
4
+ import joblib
5
+ import torch
6
+ from lightgbm import LGBMClassifier, early_stopping
7
+
8
+ from ..base.base_classifier import BaseTirexClassifier
9
+
10
+
11
+ class TirexGBMClassifier(BaseTirexClassifier):
12
+ """
13
+ A Gradient Boosting classifier that uses time series embeddings as features.
14
+
15
+ This classifier combines a pre-trained embedding model for feature extraction with a
16
+ Gradient Boosting classifier.
17
+
18
+ Example:
19
+ >>> from tirex.models.classification import TirexGBMClassifier
20
+ >>>
21
+ >>> # Create model with custom LightGBM parameters
22
+ >>> model = TirexGBMClassifier(
23
+ ... data_augmentation=True,
24
+ ... n_estimators=50,
25
+ ... random_state=42
26
+ ... )
27
+ >>>
28
+ >>> # Prepare data (can use NumPy arrays or PyTorch tensors)
29
+ >>> X_train = torch.randn(100, 1, 128) # 100 samples, 1 number of variates, 128 sequence length
30
+ >>> y_train = torch.randint(0, 3, (100,)) # 3 classes
31
+ >>>
32
+ >>> # Train the model
33
+ >>> model.fit((X_train, y_train))
34
+ >>>
35
+ >>> # Make predictions
36
+ >>> X_test = torch.randn(20, 1, 128)
37
+ >>> predictions = model.predict(X_test)
38
+ >>> probabilities = model.predict_proba(X_test)
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ data_augmentation: bool = False,
44
+ device: str | None = None,
45
+ compile: bool = False,
46
+ batch_size: int = 512,
47
+ early_stopping_rounds: int | None = 10,
48
+ min_delta: float = 0.0,
49
+ val_split_ratio: float = 0.2,
50
+ stratify: bool = True,
51
+ # LightGBM kwargs
52
+ **lgbm_kwargs,
53
+ ) -> None:
54
+ """Initializes Embedding Based Gradient Boosting Classification model.
55
+
56
+ Args:
57
+ data_augmentation : bool
58
+ Whether to use data_augmentation for embeddings (sample statistics and first-order differences of the original data). Default: False
59
+ device : str | None
60
+ Device to run the embedding model on. If None, uses CUDA if available, else CPU. Default: None
61
+ compile: bool
62
+ Whether to compile the frozen embedding model. Default: False
63
+ batch_size : int
64
+ Batch size for embedding calculations. Default: 512
65
+ early_stopping_rounds: int | None
66
+ Number of rounds without improvement of all metrics for Early Stopping. Default: 10
67
+ min_delta: float
68
+ Minimum improvement in score to keep training. Default 0.0
69
+ val_split_ratio : float
70
+ Proportion of training data to use for validation, if validation data are not provided. Default: 0.2
71
+ stratify : bool
72
+ Whether to stratify the train/validation split by class labels. Default: True
73
+ **lgbm_kwargs
74
+ Additional keyword arguments to pass to LightGBM's LGBMClassifier.
75
+ Common options include n_estimators, max_depth, learning_rate, random_state, etc.
76
+ """
77
+ super().__init__(data_augmentation=data_augmentation, device=device, compile=compile, batch_size=batch_size)
78
+
79
+ # Early Stopping callback
80
+ self.early_stopping_rounds = early_stopping_rounds
81
+ self.min_delta = min_delta
82
+
83
+ # Data split parameters:
84
+ self.val_split_ratio = val_split_ratio
85
+ self.stratify = stratify
86
+
87
+ # Extract random_state for train_val_split if provided
88
+ self.random_state = lgbm_kwargs.get("random_state", None)
89
+
90
+ self.head = LGBMClassifier(**lgbm_kwargs)
91
+
92
+ @torch.inference_mode()
93
+ def fit(
94
+ self,
95
+ train_data: tuple[torch.Tensor, torch.Tensor],
96
+ val_data: tuple[torch.Tensor, torch.Tensor] | None = None,
97
+ ) -> None:
98
+ """Train the LightGBM classifier on embedded time series data.
99
+
100
+ This method generates embeddings for the training data using the embedding
101
+ model, then trains the LightGBM classifier on these embeddings.
102
+
103
+ Args:
104
+ train_data: Tuple of (X_train, y_train) where X_train is the input time
105
+ series data (torch.Tensor) and y_train is a torch.Tensor
106
+ of class labels.
107
+ val_data: Optional tuple of (X_val, y_val) for validation where X_train is the input time
108
+ series data (torch.Tensor) and y_train is a torch.Tensor
109
+ of class labels. If None, validation data will be automatically split from train_data (20% split).
110
+ """
111
+
112
+ (X_train, y_train), (X_val, y_val) = self._create_train_val_datasets(
113
+ train_data=train_data,
114
+ val_data=val_data,
115
+ val_split_ratio=self.val_split_ratio,
116
+ stratify=self.stratify,
117
+ seed=self.random_state,
118
+ )
119
+
120
+ X_train = X_train.to(self.device)
121
+ X_val = X_val.to(self.device)
122
+
123
+ embeddings_train = self._compute_embeddings(X_train)
124
+ embeddings_val = self._compute_embeddings(X_val)
125
+
126
+ y_train = y_train.detach().cpu().numpy() if isinstance(y_train, torch.Tensor) else y_train
127
+ y_val = y_val.detach().cpu().numpy() if isinstance(y_val, torch.Tensor) else y_val
128
+
129
+ self.head.fit(
130
+ embeddings_train,
131
+ y_train,
132
+ eval_set=[(embeddings_val, y_val)],
133
+ callbacks=[early_stopping(stopping_rounds=self.early_stopping_rounds, min_delta=self.min_delta)]
134
+ if self.early_stopping_rounds is not None
135
+ else None,
136
+ )
137
+
138
+ def save_model(self, path: str) -> None:
139
+ """This method saves the trained LightGBM classifier head (joblib format) and embedding information.
140
+
141
+ Args:
142
+ path: File path where the model should be saved (e.g., 'model.joblib').
143
+ """
144
+
145
+ payload = {
146
+ "data_augmentation": self.data_augmentation,
147
+ "compile": self._compile,
148
+ "batch_size": self.batch_size,
149
+ "early_stopping_rounds": self.early_stopping_rounds,
150
+ "min_delta": self.min_delta,
151
+ "val_split_ratio": self.val_split_ratio,
152
+ "stratify": self.stratify,
153
+ "head": self.head,
154
+ }
155
+ joblib.dump(payload, path)
156
+
157
+ @classmethod
158
+ def load_model(cls, path: str) -> "TirexGBMClassifier":
159
+ """Load a saved model from file.
160
+
161
+ This reconstructs the model with the embedding configuration and loads
162
+ the trained LightGBM classifier from a checkpoint file created by save_model().
163
+
164
+ Args:
165
+ path: File path to the saved model checkpoint.
166
+ Returns:
167
+ TirexGBMClassifier: The loaded model with trained Gradient Boosting, ready for inference.
168
+ """
169
+ checkpoint = joblib.load(path)
170
+
171
+ # Create new instance with saved configuration
172
+ model = cls(
173
+ data_augmentation=checkpoint["data_augmentation"],
174
+ compile=checkpoint["compile"],
175
+ batch_size=checkpoint["batch_size"],
176
+ early_stopping_rounds=checkpoint["early_stopping_rounds"],
177
+ min_delta=checkpoint["min_delta"],
178
+ val_split_ratio=checkpoint["val_split_ratio"],
179
+ stratify=checkpoint["stratify"],
180
+ )
181
+
182
+ # Load the trained LightGBM head
183
+ model.head = checkpoint["head"]
184
+
185
+ # Extract random_state from the loaded head if available
186
+ model.random_state = getattr(model.head, "random_state", None)
187
+
188
+ return model
@@ -1,12 +1,15 @@
1
+ # Copyright (c) NXAI GmbH.
2
+ # This software may be used and distributed according to the terms of the NXAI Community License Agreement.
3
+
1
4
  from dataclasses import asdict
2
5
 
3
6
  import torch
4
7
 
5
- from .embedding import TiRexEmbedding
6
- from .trainer import TrainConfig, Trainer
8
+ from ..base.base_classifier import BaseTirexClassifier
9
+ from ..trainer import TrainConfig, Trainer, TrainingMetrics
7
10
 
8
11
 
9
- class TirexClassifierTorch(torch.nn.Module):
12
+ class TirexLinearClassifier(BaseTirexClassifier, torch.nn.Module):
10
13
  """
11
14
  A PyTorch classifier that combines time series embeddings with a linear classification head.
12
15
 
@@ -16,10 +19,10 @@ class TirexClassifierTorch(torch.nn.Module):
16
19
 
17
20
  Example:
18
21
  >>> import torch
19
- >>> from tirex.models.classification import TirexClassifierTorch
22
+ >>> from tirex.models.classification import TirexLinearClassifier
20
23
  >>>
21
- >>> # Create model with TIREX embeddings
22
- >>> model = TirexClassifierTorch(
24
+ >>> # Create model with TiRex embeddings
25
+ >>> model = TirexLinearClassifier(
23
26
  ... data_augmentation=True,
24
27
  ... max_epochs=2,
25
28
  ... lr=1e-4,
@@ -43,8 +46,9 @@ class TirexClassifierTorch(torch.nn.Module):
43
46
  self,
44
47
  data_augmentation: bool = False,
45
48
  device: str | None = None,
49
+ compile: bool = False,
46
50
  # Training parameters
47
- max_epochs: int = 50,
51
+ max_epochs: int = 10,
48
52
  lr: float = 1e-4,
49
53
  weight_decay: float = 0.01,
50
54
  batch_size: int = 512,
@@ -62,11 +66,13 @@ class TirexClassifierTorch(torch.nn.Module):
62
66
 
63
67
  Args:
64
68
  data_augmentation : bool | None
65
- Whether to use data_augmentation for embeddings (stats and first-order differences of the original data). Default: False
69
+ Whether to use data_augmentation for embeddings (sample statistics and first-order differences of the original data). Default: False
66
70
  device : str | None
67
- Device to run the model on. If None, uses CUDA if available, else CPU. Default: None
71
+ Device to run the embedding model on. If None, uses CUDA if available, else CPU. Default: None
72
+ compile: bool
73
+ Whether to compile the frozen embedding model. Default: False
68
74
  max_epochs : int
69
- Maximum number of training epochs. Default: 50
75
+ Maximum number of training epochs. Default: 10
70
76
  lr : float
71
77
  Learning rate for the optimizer. Default: 1e-4
72
78
  weight_decay : float
@@ -91,15 +97,9 @@ class TirexClassifierTorch(torch.nn.Module):
91
97
  Dropout probability for the classification head. If None, no dropout is used. Default: None
92
98
  """
93
99
 
94
- super().__init__()
95
-
96
- if device is None:
97
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
98
- self.device = device
100
+ torch.nn.Module.__init__(self)
99
101
 
100
- # Create embedding model
101
- self.emb_model = TiRexEmbedding(device=self.device, data_augmentation=data_augmentation, batch_size=batch_size)
102
- self.data_augmentation = data_augmentation
102
+ super().__init__(data_augmentation=data_augmentation, device=device, compile=compile, batch_size=batch_size)
103
103
 
104
104
  # Head parameters
105
105
  self.dropout = dropout
@@ -115,6 +115,7 @@ class TirexClassifierTorch(torch.nn.Module):
115
115
  lr=lr,
116
116
  weight_decay=weight_decay,
117
117
  class_weights=class_weights,
118
+ task_type="classification",
118
119
  batch_size=batch_size,
119
120
  val_split_ratio=val_split_ratio,
120
121
  stratify=stratify,
@@ -132,9 +133,7 @@ class TirexClassifierTorch(torch.nn.Module):
132
133
 
133
134
  @torch.inference_mode()
134
135
  def _identify_head_dims(self, x: torch.Tensor, y: torch.Tensor) -> None:
135
- self.emb_model.eval()
136
- sample_emb = self.emb_model(x[:1])
137
- self.emb_dim = sample_emb.shape[-1]
136
+ self.emb_dim = self._compute_embeddings(x[:1]).shape[-1]
138
137
  self.num_classes = len(torch.unique(y))
139
138
 
140
139
  def forward(self, x: torch.Tensor) -> torch.Tensor:
@@ -155,7 +154,7 @@ class TirexClassifierTorch(torch.nn.Module):
155
154
 
156
155
  def fit(
157
156
  self, train_data: tuple[torch.Tensor, torch.Tensor], val_data: tuple[torch.Tensor, torch.Tensor] | None = None
158
- ) -> dict[str, float]:
157
+ ) -> TrainingMetrics:
159
158
  """Train the classification head on the provided data.
160
159
 
161
160
  This method initializes the classification head based on the data dimensions,
@@ -221,6 +220,7 @@ class TirexClassifierTorch(torch.nn.Module):
221
220
  {
222
221
  "head_state_dict": self.head.state_dict(), # need to save only head, embedding is frozen
223
222
  "data_augmentation": self.data_augmentation,
223
+ "compile": self._compile,
224
224
  "emb_dim": self.emb_dim,
225
225
  "num_classes": self.num_classes,
226
226
  "dropout": self.dropout,
@@ -230,7 +230,7 @@ class TirexClassifierTorch(torch.nn.Module):
230
230
  )
231
231
 
232
232
  @classmethod
233
- def load_model(cls, path: str) -> "TirexClassifierTorch":
233
+ def load_model(cls, path: str) -> "TirexLinearClassifier":
234
234
  """Load a saved model from file.
235
235
 
236
236
  This reconstructs the model architecture and loads the trained weights from
@@ -239,7 +239,7 @@ class TirexClassifierTorch(torch.nn.Module):
239
239
  Args:
240
240
  path: File path to the saved model checkpoint.
241
241
  Returns:
242
- TirexClassifierTorch: The loaded model with trained weights, ready for inference.
242
+ TirexLinearClassifier: The loaded model with trained weights, ready for inference.
243
243
  """
244
244
  checkpoint = torch.load(path)
245
245
 
@@ -248,6 +248,7 @@ class TirexClassifierTorch(torch.nn.Module):
248
248
 
249
249
  model = cls(
250
250
  data_augmentation=checkpoint["data_augmentation"],
251
+ compile=checkpoint["compile"],
251
252
  dropout=checkpoint["dropout"],
252
253
  max_epochs=train_config_dict.get("max_epochs", 50),
253
254
  lr=train_config_dict.get("lr", 1e-4),
@@ -1,12 +1,14 @@
1
+ # Copyright (c) NXAI GmbH.
2
+ # This software may be used and distributed according to the terms of the NXAI Community License Agreement.
3
+
1
4
  import joblib
2
- import numpy as np
3
5
  import torch
4
6
  from sklearn.ensemble import RandomForestClassifier
5
7
 
6
- from .embedding import TiRexEmbedding
8
+ from ..base.base_classifier import BaseTirexClassifier
7
9
 
8
10
 
9
- class TirexRFClassifier:
11
+ class TirexRFClassifier(BaseTirexClassifier):
10
12
  """
11
13
  A Random Forest classifier that uses time series embeddings as features.
12
14
 
@@ -15,7 +17,6 @@ class TirexRFClassifier:
15
17
  time series, which are then used to train the Random Forest.
16
18
 
17
19
  Example:
18
- >>> import numpy as np
19
20
  >>> from tirex.models.classification import TirexRFClassifier
20
21
  >>>
21
22
  >>> # Create model with custom Random Forest parameters
@@ -43,6 +44,7 @@ class TirexRFClassifier:
43
44
  self,
44
45
  data_augmentation: bool = False,
45
46
  device: str | None = None,
47
+ compile: bool = False,
46
48
  batch_size: int = 512,
47
49
  # Random Forest parameters
48
50
  **rf_kwargs,
@@ -51,24 +53,18 @@ class TirexRFClassifier:
51
53
 
52
54
  Args:
53
55
  data_augmentation : bool
54
- Whether to use data_augmentation for embeddings (stats and first-order differences of the original data). Default: False
56
+ Whether to use data_augmentation for embeddings (sample statistics and first-order differences of the original data). Default: False
55
57
  device : str | None
56
58
  Device to run the embedding model on. If None, uses CUDA if available, else CPU. Default: None
59
+ compile: bool
60
+ Whether to compile the frozen embedding model. Default: False
57
61
  batch_size : int
58
62
  Batch size for embedding calculations. Default: 512
59
63
  **rf_kwargs
60
64
  Additional keyword arguments to pass to sklearn's RandomForestClassifier.
61
65
  Common options include n_estimators, max_depth, min_samples_split, random_state, etc.
62
66
  """
63
-
64
- # Set device
65
- if device is None:
66
- device = "cuda:0" if torch.cuda.is_available() else "cpu"
67
- self.device = device
68
-
69
- self.emb_model = TiRexEmbedding(device=self.device, data_augmentation=data_augmentation, batch_size=batch_size)
70
- self.data_augmentation = data_augmentation
71
-
67
+ super().__init__(data_augmentation=data_augmentation, device=device, compile=compile, batch_size=batch_size)
72
68
  self.head = RandomForestClassifier(**rf_kwargs)
73
69
 
74
70
  @torch.inference_mode()
@@ -80,7 +76,7 @@ class TirexRFClassifier:
80
76
 
81
77
  Args:
82
78
  train_data: Tuple of (X_train, y_train) where X_train is the input time
83
- series data (torch.Tensor) and y_train is a numpy array
79
+ series data (torch.Tensor) and y_train is a torch.Tensor
84
80
  of class labels.
85
81
  """
86
82
  X_train, y_train = train_data
@@ -88,35 +84,10 @@ class TirexRFClassifier:
88
84
  if isinstance(y_train, torch.Tensor):
89
85
  y_train = y_train.detach().cpu().numpy()
90
86
 
91
- embeddings = self.emb_model(X_train).cpu().numpy()
92
- self.head.fit(embeddings, y_train)
93
-
94
- @torch.inference_mode()
95
- def predict(self, x: torch.Tensor) -> torch.Tensor:
96
- """Predict class labels for input time series data.
97
-
98
- Args:
99
- x: Input time series data as torch.Tensor or np.ndarray with shape
100
- (batch_size, num_variates, seq_len).
101
- Returns:
102
- torch.Tensor: Predicted class labels with shape (batch_size,).
103
- """
104
-
105
- embeddings = self.emb_model(x).cpu().numpy()
106
- return torch.from_numpy(self.head.predict(embeddings)).long()
107
-
108
- @torch.inference_mode()
109
- def predict_proba(self, x: torch.Tensor) -> torch.Tensor:
110
- """Predict class probabilities for input time series data.
87
+ X_train = X_train.to(self.device)
88
+ embeddings = self._compute_embeddings(X_train)
111
89
 
112
- Args:
113
- x: Input time series data as torch.Tensor or np.ndarray with shape
114
- (batch_size, num_variates, seq_len).
115
- Returns:
116
- torch.Tensor: Class probabilities with shape (batch_size, num_classes).
117
- """
118
- embeddings = self.emb_model(x).cpu().numpy()
119
- return torch.from_numpy(self.head.predict_proba(embeddings))
90
+ self.head.fit(embeddings, y_train)
120
91
 
121
92
  def save_model(self, path: str) -> None:
122
93
  """This method saves the trained Random Forest classifier head and embedding information in joblib format
@@ -126,6 +97,8 @@ class TirexRFClassifier:
126
97
  """
127
98
  payload = {
128
99
  "data_augmentation": self.data_augmentation,
100
+ "compile": self._compile,
101
+ "batch_size": self.batch_size,
129
102
  "head": self.head,
130
103
  }
131
104
  joblib.dump(payload, path)
@@ -147,6 +120,8 @@ class TirexRFClassifier:
147
120
  # Create new instance with saved configuration
148
121
  model = cls(
149
122
  data_augmentation=checkpoint["data_augmentation"],
123
+ compile=checkpoint["compile"],
124
+ batch_size=checkpoint["batch_size"],
150
125
  )
151
126
 
152
127
  # Load the trained Random Forest head
@@ -1,27 +1,29 @@
1
- import inspect
1
+ # Copyright (c) NXAI GmbH.
2
+ # This software may be used and distributed according to the terms of the NXAI Community License Agreement.
2
3
 
3
- import numpy as np
4
4
  import torch
5
5
  import torch.nn as nn
6
6
  import torch.nn.functional as F
7
7
 
8
8
  from tirex import load_model
9
-
10
- from .utils import nanmax, nanmin, nanstd
9
+ from tirex.util import nanmax, nanmin, nanstd
11
10
 
12
11
 
13
12
  class TiRexEmbedding(nn.Module):
14
- def __init__(self, device: str | None = None, data_augmentation: bool = False, batch_size: int = 512) -> None:
13
+ def __init__(
14
+ self, device: str | None = None, data_augmentation: bool = False, batch_size: int = 512, compile: bool = False
15
+ ) -> None:
15
16
  super().__init__()
16
17
  self.data_augmentation = data_augmentation
17
18
  self.number_of_patches = 8
18
19
  self.batch_size = batch_size
19
20
 
20
21
  if device is None:
21
- device = "cuda" if torch.cuda.is_available() else "cpu"
22
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
22
23
  self.device = device
24
+ self._compile = compile
23
25
 
24
- self.model = load_model(path="NX-AI/TiRex", device=self.device)
26
+ self.model = load_model(path="NX-AI/TiRex", device=self.device, compile=self._compile)
25
27
 
26
28
  def _gen_emb_batched(self, data: torch.Tensor) -> torch.Tensor:
27
29
  batches = list(torch.split(data, self.batch_size))