sciml 0.0.9__py3-none-any.whl → 0.0.10__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.
sciml/models.py CHANGED
@@ -1,277 +1,276 @@
1
- import numpy as np
2
- import copy
3
- import itertools
4
- import warnings
5
- from xgboost import XGBRegressor
6
- from sklearn.metrics import mean_squared_error
7
- from sklearn.model_selection import train_test_split
8
-
9
- class SmartForest:
10
- """
11
- SmartForest: A deep, intelligent decision forest model for complex sequential and tabular data.
12
-
13
- SmartForest blends ideas from deep forests (cascade forest structures), LSTM-style forget gates,
14
- and ensemble learning using XGBoost. It is especially suited for time series or structured tabular data
15
- where layer-wise feature expansion and memory-inspired filtering can enhance performance.
16
-
17
- Key Features:
18
- -------------
19
- - Deep cascade of XGBoost regressors
20
- - Optional Multi-Grained Scanning (MGS) for local feature extraction
21
- - Forget-gate-inspired mechanism to regulate information flow across layers
22
- - Early stopping to prevent overfitting
23
- - Full retention of best-performing model (lowest validation RMSE)
24
-
25
- Parameters:
26
- -----------
27
- n_estimators_per_layer : int
28
- Number of XGBoost regressors per layer.
29
-
30
- max_layers : int
31
- Maximum number of layers (depth) in the model.
32
-
33
- early_stopping_rounds : int
34
- Number of layers with no improvement before early stopping is triggered.
35
-
36
- param_grid : dict
37
- Grid of XGBoost hyperparameters to search over.
38
-
39
- use_gpu : bool
40
- If True, use GPU-accelerated training (CUDA required).
41
-
42
- gpu_id : int
43
- ID of GPU to use (if use_gpu=True).
44
-
45
- window_sizes : list of int
46
- Enables Multi-Grained Scanning if non-empty, with specified sliding window sizes.
47
-
48
- forget_factor : float in [0, 1]
49
- Simulates LSTM-style forget gate; higher values forget more past information.
50
-
51
- verbose : int
52
- Verbosity level (0 = silent, 1 = progress updates).
53
-
54
- Methods:
55
- --------
56
- fit(X, y, X_val=None, y_val=None):
57
- Train the SmartForest model layer by layer, using optional validation for early stopping.
58
-
59
- predict(X):
60
- Make predictions on new data using the trained cascade structure.
61
-
62
- get_best_model():
63
- Returns a copy of the best model and the corresponding RMSE from validation.
64
-
65
- Example:
66
- --------
67
- >>> model = SmartForest(n_estimators_per_layer=5, max_layers=10, window_sizes=[2, 3], forget_factor=0.2)
68
- >>> model.fit(X_train, y_train, X_val, y_val)
69
- >>> y_pred = model.predict(X_val)
70
- >>> best_model, best_rmse = model.get_best_model()
71
- """
72
- def __init__(self, n_estimators_per_layer = 5, max_layers = 10, early_stopping_rounds = 3, param_grid = None,
73
- use_gpu = False, gpu_id = 0, window_sizes = [], forget_factor = 0, verbose = 1):
74
- self.n_estimators_per_layer = n_estimators_per_layer
75
- self.max_layers = max_layers
76
- self.early_stopping_rounds = early_stopping_rounds
77
- self.param_grid = param_grid or {
78
- "objective": ["reg:squarederror"],
79
- "random_state": [42],
80
- 'seed': [0],
81
- 'n_estimators': [100],
82
- 'max_depth': [6],
83
- 'min_child_weight': [4],
84
- 'subsample': [0.8],
85
- 'colsample_bytree': [0.8],
86
- 'gamma': [0],
87
- 'reg_alpha': [0],
88
- 'reg_lambda': [1],
89
- 'learning_rate': [0.05],
90
- }
91
- self.use_gpu = use_gpu
92
- self.gpu_id = gpu_id
93
- self.window_sizes = window_sizes
94
- self.forget_factor = forget_factor
95
- self.layers = []
96
- self.best_model = None
97
- self.best_rmse = float("inf")
98
- self.verbose = verbose
99
-
100
- def _get_param_combinations(self):
101
- keys, values = zip(*self.param_grid.items())
102
- return [dict(zip(keys, v)) for v in itertools.product(*values)]
103
-
104
- def _multi_grained_scanning(self, X, y):
105
- new_features = []
106
- for window_size in self.window_sizes:
107
- if X.shape[1] < window_size:
108
- continue
109
- for start in range(X.shape[1] - window_size + 1):
110
- window = X[:, start:start + window_size]
111
- if y is None:
112
- new_features.append(window)
113
- continue
114
-
115
- param_combos = self._get_param_combinations()
116
- for params in param_combos:
117
- if self.use_gpu:
118
- params['tree_method'] = 'hist'
119
- params['device'] = 'cuda'
120
- model = XGBRegressor(**params)
121
- model.fit(window, y)
122
- preds = model.predict(window).reshape(-1, 1)
123
- new_features.append(preds)
124
- return np.hstack(new_features) if new_features else X
125
-
126
- def _apply_forget_gate(self, X, layer_index):
127
- forget_weights = np.random.rand(X.shape[1]) * self.forget_factor
128
- return X * (1 - forget_weights)
129
-
130
- def _fit_layer(self, X, y, X_val=None, y_val=None, layer_index=0):
131
- layer = []
132
- layer_outputs = []
133
- param_combos = self._get_param_combinations()
134
- X = self._apply_forget_gate(X, layer_index)
135
-
136
- for i in range(self.n_estimators_per_layer):
137
- best_rmse = float('inf')
138
- best_model = None
139
-
140
- for params in param_combos:
141
- if self.use_gpu:
142
- params['tree_method'] = 'hist'
143
- params['device'] = 'cuda'
144
-
145
- params = params.copy() # Prevent modification from affecting the next loop iteration
146
- params['random_state'] = i # Use a different random seed for each model to enhance diversity
147
-
148
- model = XGBRegressor(**params)
149
- model.fit(X, y)
150
-
151
- if X_val is not None:
152
- preds_val = model.predict(X_val)
153
- rmse = np.sqrt(mean_squared_error(y_val, preds_val))
154
- if rmse < best_rmse:
155
- best_rmse = rmse
156
- best_model = model
157
- else:
158
- best_model = model
159
-
160
- preds = best_model.predict(X).reshape(-1, 1)
161
- layer.append(best_model)
162
- layer_outputs.append(preds)
163
-
164
- output = np.hstack(layer_outputs)
165
- return layer, output
166
-
167
- def fit(self, X, y, X_val=None, y_val=None):
168
- X_current = self._multi_grained_scanning(X, y)
169
- X_val_current = self._multi_grained_scanning(X_val, y_val) if X_val is not None else None
170
- no_improve_rounds = 0
171
-
172
- for layer_index in range(self.max_layers):
173
- if self.verbose: print(f"Training Layer {layer_index + 1}")
174
- layer, output = self._fit_layer(X_current, y, X_val_current, y_val, layer_index)
175
- self.layers.append(layer)
176
- X_current = np.hstack([X_current, output])
177
-
178
- if X_val is not None:
179
- val_outputs = []
180
- for reg in layer:
181
- n_features = reg.n_features_in_
182
- preds = reg.predict(X_val_current[:, :n_features]).reshape(-1, 1)
183
- val_outputs.append(preds)
184
- val_output = np.hstack(val_outputs)
185
- X_val_current = np.hstack([X_val_current, val_output])
186
-
187
- y_pred = self.predict(X_val)
188
- rmse = np.sqrt(mean_squared_error(y_val, y_pred))
189
- if self.verbose: print(f"Validation RMSE: {rmse:.4f}")
190
-
191
- if rmse < self.best_rmse:
192
- self.best_rmse = rmse
193
- self.best_model = copy.deepcopy(self.layers)
194
- no_improve_rounds = 0
195
- if self.verbose: print(f"✅ New best RMSE: {self.best_rmse:.4f}")
196
- else:
197
- no_improve_rounds += 1
198
- if no_improve_rounds >= self.early_stopping_rounds:
199
- if self.verbose: print("Early stopping triggered.")
200
- break
201
-
202
- def predict(self, X):
203
- X_current = self._multi_grained_scanning(X, None)
204
- X_current = self._apply_forget_gate(X_current, layer_index=-1)
205
-
206
- for layer in self.layers:
207
- layer_outputs = []
208
- for reg in layer:
209
- n_features = reg.n_features_in_
210
- preds = reg.predict(X_current[:, :n_features]).reshape(-1, 1)
211
- layer_outputs.append(preds)
212
- output = np.hstack(layer_outputs)
213
- X_current = np.hstack([X_current, output])
214
-
215
- final_outputs = []
216
- for reg in self.layers[-1]:
217
- n_features = reg.n_features_in_
218
- final_outputs.append(reg.predict(X_current[:, :n_features]).reshape(-1, 1))
219
- return np.mean(np.hstack(final_outputs), axis=1)
220
-
221
- def get_best_model(self):
222
- return self.best_model, self.best_rmse
223
-
224
- """
225
- # ============================== Test Example ==============================
226
- from sklearn.datasets import load_diabetes
227
- from sklearn.datasets import fetch_california_housing
228
- from sklearn.model_selection import train_test_split
229
-
230
-
231
-
232
- warnings.simplefilter('ignore')
233
-
234
- # X, y = load_diabetes(return_X_y=True) # Using diabetes dataset
235
- X, y = fetch_california_housing(return_X_y=True) # Using house price dataset
236
- X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42)
237
-
238
- # Hyperparameter grid
239
- param_grid = {
240
- "objective": ["reg:squarederror"],
241
- "random_state": [42],
242
- 'seed': [0],
243
- 'n_estimators': [100],
244
- 'max_depth': [6],
245
- 'min_child_weight': [4],
246
- 'subsample': [0.8],
247
- 'colsample_bytree': [0.8],
248
- 'gamma': [0],
249
- 'reg_alpha': [0],
250
- 'reg_lambda': [1],
251
- 'learning_rate': [0.05],
252
- }
253
-
254
- # Create the model with Multi-Grained Scanning enabled (with window sizes 2 and 3)
255
- regr = SmartForest(
256
- n_estimators_per_layer = 5,
257
- max_layers = 10,
258
- early_stopping_rounds = 5,
259
- param_grid = param_grid,
260
- use_gpu = False,
261
- gpu_id = 0,
262
- window_sizes = [], # Enables MGS if e.g., [2, 3], else empty disables MGS.
263
- forget_factor = 0., # Set forget factor to simulate forget gate behavior
264
- verbose = 1
265
- )
266
-
267
- regr.fit(X_train, y_train, X_val, y_val)
268
-
269
- # Predict on validation set and evaluate
270
- y_pred = regr.predict(X_val)
271
- rmse = np.sqrt(mean_squared_error(y_val, y_pred))
272
- print("\nFinal RMSE:", rmse)
273
-
274
- # Output best model and RMSE
275
- best_model, best_rmse = regr.get_best_model()
276
- print("\nBest validation RMSE:", best_rmse)
1
+ import numpy as np
2
+ import copy
3
+ import itertools
4
+ import warnings
5
+ from xgboost import XGBRegressor
6
+ from sklearn.metrics import mean_squared_error
7
+ from sklearn.model_selection import train_test_split
8
+
9
+ class SmartForest:
10
+ """
11
+ SmartForest: A deep, intelligent decision forest model for complex sequential and tabular data.
12
+
13
+ SmartForest blends ideas from deep forests (cascade forest structures), LSTM-style forget gates,
14
+ and ensemble learning using XGBoost. It is especially suited for time series or structured tabular data
15
+ where layer-wise feature expansion and memory-inspired filtering can enhance performance.
16
+
17
+ Key Features:
18
+ -------------
19
+ - Deep cascade of XGBoost regressors
20
+ - Optional Multi-Grained Scanning (MGS) for local feature extraction
21
+ - Forget-gate-inspired mechanism to regulate information flow across layers
22
+ - Early stopping to prevent overfitting
23
+ - Full retention of best-performing model (lowest validation RMSE)
24
+
25
+ Parameters:
26
+ -----------
27
+ n_estimators_per_layer : int
28
+ Number of XGBoost regressors per layer.
29
+
30
+ max_layers : int
31
+ Maximum number of layers (depth) in the model.
32
+
33
+ early_stopping_rounds : int
34
+ Number of layers with no improvement before early stopping is triggered.
35
+
36
+ param_grid : dict
37
+ Grid of XGBoost hyperparameters to search over.
38
+
39
+ use_gpu : bool
40
+ If True, use GPU-accelerated training (CUDA required).
41
+
42
+ gpu_id : int
43
+ ID of GPU to use (if use_gpu=True).
44
+
45
+ window_sizes : list of int
46
+ Enables Multi-Grained Scanning if non-empty, with specified sliding window sizes.
47
+
48
+ forget_factor : float in [0, 1]
49
+ Simulates LSTM-style forget gate; higher values forget more past information.
50
+
51
+ verbose : int
52
+ Verbosity level (0 = silent, 1 = progress updates).
53
+
54
+ Methods:
55
+ --------
56
+ fit(X, y, X_val=None, y_val=None):
57
+ Train the SmartForest model layer by layer, using optional validation for early stopping.
58
+
59
+ predict(X):
60
+ Make predictions on new data using the trained cascade structure.
61
+
62
+ get_best_model():
63
+ Returns a copy of the best model and the corresponding RMSE from validation.
64
+
65
+ Example:
66
+ --------
67
+ >>> model = SmartForest(n_estimators_per_layer=5, max_layers=10, window_sizes=[2, 3], forget_factor=0.2)
68
+ >>> model.fit(X_train, y_train, X_val, y_val)
69
+ >>> y_pred = model.predict(X_val)
70
+ >>> best_model, best_rmse = model.get_best_model()
71
+ """
72
+ def __init__(self, n_estimators_per_layer = 5, max_layers = 10, early_stopping_rounds = 3, param_grid = None,
73
+ use_gpu = False, gpu_id = 0, window_sizes = [], forget_factor = 0, verbose = 1):
74
+ self.n_estimators_per_layer = n_estimators_per_layer
75
+ self.max_layers = max_layers
76
+ self.early_stopping_rounds = early_stopping_rounds
77
+ self.param_grid = param_grid or {
78
+ "objective": ["reg:squarederror"],
79
+ "random_state": [42],
80
+ 'seed': [0],
81
+ 'n_estimators': [100],
82
+ 'max_depth': [6],
83
+ 'min_child_weight': [4],
84
+ 'subsample': [0.8],
85
+ 'colsample_bytree': [0.8],
86
+ 'gamma': [0],
87
+ 'reg_alpha': [0],
88
+ 'reg_lambda': [1],
89
+ 'learning_rate': [0.05],
90
+ }
91
+ self.use_gpu = use_gpu
92
+ self.gpu_id = gpu_id
93
+ self.window_sizes = window_sizes
94
+ self.forget_factor = forget_factor
95
+ self.layers = []
96
+ self.best_model = None
97
+ self.best_rmse = float("inf")
98
+ self.verbose = verbose
99
+
100
+ def _get_param_combinations(self):
101
+ keys, values = zip(*self.param_grid.items())
102
+ return [dict(zip(keys, v)) for v in itertools.product(*values)]
103
+
104
+ def _multi_grained_scanning(self, X, y):
105
+ new_features = []
106
+ for window_size in self.window_sizes:
107
+ if X.shape[1] < window_size:
108
+ continue
109
+ for start in range(X.shape[1] - window_size + 1):
110
+ window = X[:, start:start + window_size]
111
+ if y is None:
112
+ new_features.append(window)
113
+ continue
114
+
115
+ param_combos = self._get_param_combinations()
116
+ for params in param_combos:
117
+ if self.use_gpu:
118
+ params['tree_method'] = 'hist'
119
+ params['device'] = 'cuda'
120
+ model = XGBRegressor(**params)
121
+ model.fit(window, y)
122
+ preds = model.predict(window).reshape(-1, 1)
123
+ new_features.append(preds)
124
+ return np.hstack(new_features) if new_features else X
125
+
126
+ def _apply_forget_gate(self, X, layer_index):
127
+ forget_weights = np.random.rand(X.shape[1]) * self.forget_factor
128
+ return X * (1 - forget_weights)
129
+
130
+ def _fit_layer(self, X, y, X_val=None, y_val=None, layer_index=0):
131
+ layer = []
132
+ layer_outputs = []
133
+ param_combos = self._get_param_combinations()
134
+ X = self._apply_forget_gate(X, layer_index)
135
+
136
+ for i in range(self.n_estimators_per_layer):
137
+ best_rmse = float('inf')
138
+ best_model = None
139
+
140
+ for params in param_combos:
141
+ if self.use_gpu:
142
+ params['tree_method'] = 'hist'
143
+ params['device'] = 'cuda'
144
+
145
+ params = params.copy() # Prevent modification from affecting the next loop iteration
146
+ params['random_state'] = i # Use a different random seed for each model to enhance diversity
147
+
148
+ model = XGBRegressor(**params)
149
+ model.fit(X, y)
150
+
151
+ if X_val is not None:
152
+ preds_val = model.predict(X_val)
153
+ rmse = np.sqrt(mean_squared_error(y_val, preds_val))
154
+ if rmse < best_rmse:
155
+ best_rmse = rmse
156
+ best_model = model
157
+ else:
158
+ best_model = model
159
+
160
+ preds = best_model.predict(X).reshape(-1, 1)
161
+ layer.append(best_model)
162
+ layer_outputs.append(preds)
163
+
164
+ output = np.hstack(layer_outputs)
165
+ return layer, output
166
+
167
+ def fit(self, X, y, X_val=None, y_val=None):
168
+ X_current = self._multi_grained_scanning(X, y)
169
+ X_val_current = self._multi_grained_scanning(X_val, y_val) if X_val is not None else None
170
+ no_improve_rounds = 0
171
+
172
+ for layer_index in range(self.max_layers):
173
+ if self.verbose: print(f"Training Layer {layer_index + 1}")
174
+ layer, output = self._fit_layer(X_current, y, X_val_current, y_val, layer_index)
175
+ self.layers.append(layer)
176
+ X_current = np.hstack([X_current, output])
177
+
178
+ if X_val is not None:
179
+ val_outputs = []
180
+ for reg in layer:
181
+ n_features = reg.n_features_in_
182
+ preds = reg.predict(X_val_current[:, :n_features]).reshape(-1, 1)
183
+ val_outputs.append(preds)
184
+ val_output = np.hstack(val_outputs)
185
+ X_val_current = np.hstack([X_val_current, val_output])
186
+
187
+ y_pred = self.predict(X_val)
188
+ rmse = np.sqrt(mean_squared_error(y_val, y_pred))
189
+ if self.verbose: print(f"Validation RMSE: {rmse:.4f}")
190
+
191
+ if rmse < self.best_rmse:
192
+ self.best_rmse = rmse
193
+ self.best_model = copy.deepcopy(self.layers)
194
+ no_improve_rounds = 0
195
+ if self.verbose: print(f"✅ New best RMSE: {self.best_rmse:.4f}")
196
+ else:
197
+ no_improve_rounds += 1
198
+ if no_improve_rounds >= self.early_stopping_rounds:
199
+ if self.verbose: print("Early stopping triggered.")
200
+ break
201
+
202
+ def predict(self, X):
203
+ X_current = self._multi_grained_scanning(X, None)
204
+ X_current = self._apply_forget_gate(X_current, layer_index=-1)
205
+
206
+ for layer in self.layers:
207
+ layer_outputs = []
208
+ for reg in layer:
209
+ n_features = reg.n_features_in_
210
+ preds = reg.predict(X_current[:, :n_features]).reshape(-1, 1)
211
+ layer_outputs.append(preds)
212
+ output = np.hstack(layer_outputs)
213
+ X_current = np.hstack([X_current, output])
214
+
215
+ final_outputs = []
216
+ for reg in self.layers[-1]:
217
+ n_features = reg.n_features_in_
218
+ final_outputs.append(reg.predict(X_current[:, :n_features]).reshape(-1, 1))
219
+ return np.mean(np.hstack(final_outputs), axis=1)
220
+
221
+ def get_best_model(self):
222
+ return self.best_model, self.best_rmse
223
+
224
+ """
225
+ # ============================== Test Example ==============================
226
+ import warnings
227
+ import numpy as np
228
+ from sklearn.datasets import load_diabetes
229
+ from sklearn.datasets import fetch_california_housing
230
+ from sklearn.model_selection import train_test_split
231
+ from sklearn.metrics import mean_squared_error
232
+
233
+ # X, y = load_diabetes(return_X_y=True) # Using diabetes dataset
234
+ X, y = fetch_california_housing(return_X_y=True) # Using house price dataset
235
+ X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42)
236
+
237
+ # Hyperparameter grid
238
+ param_grid = {
239
+ "objective": ["reg:squarederror"],
240
+ "random_state": [42],
241
+ 'seed': [0],
242
+ 'n_estimators': [100],
243
+ 'max_depth': [6],
244
+ 'min_child_weight': [4],
245
+ 'subsample': [0.8],
246
+ 'colsample_bytree': [0.8],
247
+ 'gamma': [0],
248
+ 'reg_alpha': [0],
249
+ 'reg_lambda': [1],
250
+ 'learning_rate': [0.05],
251
+ }
252
+
253
+ # Create the model with Multi-Grained Scanning enabled (with window sizes 2 and 3)
254
+ regr = SmartForest(
255
+ n_estimators_per_layer = 5,
256
+ max_layers = 10,
257
+ early_stopping_rounds = 5,
258
+ param_grid = param_grid,
259
+ use_gpu = False,
260
+ gpu_id = 0,
261
+ window_sizes = [], # Enables MGS if e.g., [2, 3], else empty disables MGS.
262
+ forget_factor = 0., # Set forget factor to simulate forget gate behavior
263
+ verbose = 1
264
+ )
265
+
266
+ regr.fit(X_train, y_train, X_val, y_val)
267
+
268
+ # Predict on validation set and evaluate
269
+ y_pred = regr.predict(X_val)
270
+ rmse = np.sqrt(mean_squared_error(y_val, y_pred))
271
+ print("\nFinal RMSE:", rmse)
272
+
273
+ # Output best model and RMSE
274
+ best_model, best_rmse = regr.get_best_model()
275
+ print("\nBest validation RMSE:", best_rmse)
277
276
  """