sciml 0.0.8__tar.gz → 0.0.9__tar.gz

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.
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2021 Zhu
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Zhu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,13 +1,13 @@
1
- Metadata-Version: 2.1
2
- Name: sciml
3
- Version: 0.0.8
4
- Summary: draw and basic calculations/conversions
5
- Home-page: https://github.com/soonyenju/sciml
6
- Author: Songyan Zhu
7
- Author-email: zhusy93@gmail.com
8
- License: MIT Licence
9
- Keywords: Scientific machine learning wrappers
10
- Platform: any
11
- License-File: LICENSE
12
-
13
- coming soon
1
+ Metadata-Version: 2.1
2
+ Name: sciml
3
+ Version: 0.0.9
4
+ Summary: draw and basic calculations/conversions
5
+ Home-page: https://github.com/soonyenju/sciml
6
+ Author: Songyan Zhu
7
+ Author-email: zhusy93@gmail.com
8
+ License: MIT Licence
9
+ Keywords: Scientific machine learning wrappers
10
+ Platform: any
11
+ License-File: LICENSE
12
+
13
+ coming soon
@@ -1,7 +1,7 @@
1
- # SCIentific Machine Learning (sciml)
2
-
3
- Author: Dr. Songyan Zhu University of Southampton
4
-
5
- Contact: Songyan.Zhu@ed.soton.uk
6
-
7
- Website: https://sites.google.com/view/uflux
1
+ # SCIentific Machine Learning (sciml)
2
+
3
+ Author: Dr. Songyan Zhu University of Southampton
4
+
5
+ Contact: Songyan.Zhu@ed.soton.uk
6
+
7
+ Website: https://sites.google.com/view/uflux
@@ -0,0 +1,2 @@
1
+ # coding: utf-8
2
+ __all__ = ["utils", "pipelines", "models"]
@@ -1,269 +1,277 @@
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
- model = XGBRegressor(**params)
146
- model.fit(X, y)
147
-
148
- if X_val is not None:
149
- preds_val = model.predict(X_val)
150
- rmse = np.sqrt(mean_squared_error(y_val, preds_val))
151
- if rmse < best_rmse:
152
- best_rmse = rmse
153
- best_model = model
154
- else:
155
- best_model = model
156
-
157
- preds = best_model.predict(X).reshape(-1, 1)
158
- layer.append(best_model)
159
- layer_outputs.append(preds)
160
-
161
- output = np.hstack(layer_outputs)
162
- return layer, output
163
-
164
- def fit(self, X, y, X_val=None, y_val=None):
165
- X_current = self._multi_grained_scanning(X, y)
166
- X_val_current = self._multi_grained_scanning(X_val, y_val) if X_val is not None else None
167
- no_improve_rounds = 0
168
-
169
- for layer_index in range(self.max_layers):
170
- if self.verbose: print(f"Training Layer {layer_index + 1}")
171
- layer, output = self._fit_layer(X_current, y, X_val_current, y_val, layer_index)
172
- self.layers.append(layer)
173
- X_current = np.hstack([X_current, output])
174
-
175
- if X_val is not None:
176
- val_outputs = []
177
- for reg in layer:
178
- n_features = reg.n_features_in_
179
- preds = reg.predict(X_val_current[:, :n_features]).reshape(-1, 1)
180
- val_outputs.append(preds)
181
- val_output = np.hstack(val_outputs)
182
- X_val_current = np.hstack([X_val_current, val_output])
183
-
184
- y_pred = self.predict(X_val)
185
- rmse = np.sqrt(mean_squared_error(y_val, y_pred))
186
- if self.verbose: print(f"Validation RMSE: {rmse:.4f}")
187
-
188
- if rmse < self.best_rmse:
189
- self.best_rmse = rmse
190
- self.best_model = copy.deepcopy(self.layers)
191
- no_improve_rounds = 0
192
- if self.verbose: print(f"✅ New best RMSE: {self.best_rmse:.4f}")
193
- else:
194
- no_improve_rounds += 1
195
- if no_improve_rounds >= self.early_stopping_rounds:
196
- if self.verbose: print("Early stopping triggered.")
197
- break
198
-
199
- def predict(self, X):
200
- X_current = self._multi_grained_scanning(X, None)
201
- X_current = self._apply_forget_gate(X_current, layer_index=-1)
202
-
203
- for layer in self.layers:
204
- layer_outputs = []
205
- for reg in layer:
206
- n_features = reg.n_features_in_
207
- preds = reg.predict(X_current[:, :n_features]).reshape(-1, 1)
208
- layer_outputs.append(preds)
209
- output = np.hstack(layer_outputs)
210
- X_current = np.hstack([X_current, output])
211
-
212
- final_outputs = []
213
- for reg in self.layers[-1]:
214
- n_features = reg.n_features_in_
215
- final_outputs.append(reg.predict(X_current[:, :n_features]).reshape(-1, 1))
216
- return np.mean(np.hstack(final_outputs), axis=1)
217
-
218
- def get_best_model(self):
219
- return self.best_model, self.best_rmse
220
-
221
- """
222
- # ============================== Test Example ==============================
223
- from sklearn.datasets import load_diabetes
224
-
225
- warnings.simplefilter('ignore')
226
-
227
- X, y = load_diabetes(return_X_y=True)
228
- X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42)
229
-
230
- # Hyperparameter grid
231
- param_grid = {
232
- "objective": ["reg:squarederror"],
233
- "random_state": [42],
234
- 'seed': [0],
235
- 'n_estimators': [100],
236
- 'max_depth': [6],
237
- 'min_child_weight': [4],
238
- 'subsample': [0.8],
239
- 'colsample_bytree': [0.8],
240
- 'gamma': [0],
241
- 'reg_alpha': [0],
242
- 'reg_lambda': [1],
243
- 'learning_rate': [0.05],
244
- }
245
-
246
- # Create the model with Multi-Grained Scanning enabled (with window sizes 2 and 3)
247
- df_reg = SmartForest(
248
- n_estimators_per_layer = 5,
249
- max_layers = 10,
250
- early_stopping_rounds = 5,
251
- param_grid = param_grid,
252
- use_gpu = False,
253
- gpu_id = 0,
254
- window_sizes = [], # Enables MGS if e.g., [2, 3], else empty disables MGS.
255
- forget_factor = 0., # Set forget factor to simulate forget gate behavior
256
- verbose = 1
257
- )
258
-
259
- df_reg.fit(X_train, y_train, X_val, y_val)
260
-
261
- # Predict on validation set and evaluate
262
- y_pred = df_reg.predict(X_val)
263
- rmse = np.sqrt(mean_squared_error(y_val, y_pred))
264
- print("\nFinal RMSE:", rmse)
265
-
266
- # Output best model and RMSE
267
- best_model, best_rmse = df_reg.get_best_model()
268
- 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
+ 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)
269
277
  """