hdmrlib 0.1.0__tar.gz → 0.1.2__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.
- {hdmrlib-0.1.0/hdmrlib.egg-info → hdmrlib-0.1.2}/PKG-INFO +40 -42
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/README.md +39 -39
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib/__init__.py +1 -1
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib/backends/__init__.py +53 -41
- hdmrlib-0.1.2/hdmrlib/backends/base.py +13 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib/backends/numpy_backend.py +34 -49
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib/backends/tensorflow_backend.py +34 -49
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib/backends/torch_backend.py +36 -52
- hdmrlib-0.1.2/hdmrlib/empr.py +25 -0
- hdmrlib-0.1.2/hdmrlib/hdmr.py +25 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2/hdmrlib.egg-info}/PKG-INFO +40 -42
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib.egg-info/requires.txt +0 -2
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/pyproject.toml +70 -74
- hdmrlib-0.1.2/requirements.txt +1 -0
- hdmrlib-0.1.0/hdmrlib/backends/base.py +0 -20
- hdmrlib-0.1.0/hdmrlib/empr.py +0 -14
- hdmrlib-0.1.0/hdmrlib/hdmr.py +0 -14
- hdmrlib-0.1.0/requirements.txt +0 -6
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/LICENSE +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/MANIFEST.in +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/examples/README.md +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/examples/advanced_usage.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/examples/backend_comparison.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/examples/basic_usage.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/examples/gpu_acceleration.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib/metrics.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib.egg-info/SOURCES.txt +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib.egg-info/dependency_links.txt +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/hdmrlib.egg-info/top_level.txt +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/setup.cfg +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/tests/__init__.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/tests/test_backends.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/tests/test_empr.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/tests/test_hdmr.py +0 -0
- {hdmrlib-0.1.0 → hdmrlib-0.1.2}/tests/test_metrics.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: hdmrlib
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.2
|
|
4
4
|
Summary: High Dimensional Model Representation (HDMR) and Enhanced Multivariate Products Representation (EMPR) library
|
|
5
5
|
Author: HDMR-Lib Contributors
|
|
6
6
|
Author-email: Muhammed Enis Sen <m.enis.97@gmail.com>, Bugra Eyidogan <bugra.eyidogan@gmail.com>, Pinar Guler <yalcin.pinar2@gmail.com>
|
|
@@ -21,8 +21,6 @@ Requires-Python: >=3.8
|
|
|
21
21
|
Description-Content-Type: text/markdown
|
|
22
22
|
License-File: LICENSE
|
|
23
23
|
Requires-Dist: numpy>=1.22
|
|
24
|
-
Requires-Dist: torch>=2.2
|
|
25
|
-
Requires-Dist: tensorflow>=2.14
|
|
26
24
|
Provides-Extra: torch
|
|
27
25
|
Requires-Dist: torch>=2.2; extra == "torch"
|
|
28
26
|
Provides-Extra: tensorflow
|
|
@@ -119,17 +117,17 @@ tensor = np.random.rand(5, 5, 5)
|
|
|
119
117
|
set_backend('numpy')
|
|
120
118
|
|
|
121
119
|
# EMPR Decomposition
|
|
122
|
-
empr_model = EMPR(tensor)
|
|
123
|
-
empr_result = empr_model.
|
|
124
|
-
empr_components = empr_model.components
|
|
120
|
+
empr_model = EMPR(tensor, order=2)
|
|
121
|
+
empr_result = empr_model.reconstruct()
|
|
122
|
+
empr_components = empr_model.components # dict of components
|
|
125
123
|
|
|
126
124
|
# HDMR Decomposition
|
|
127
|
-
hdmr_model = HDMR(tensor)
|
|
128
|
-
hdmr_result = hdmr_model.
|
|
129
|
-
hdmr_components = hdmr_model.components
|
|
125
|
+
hdmr_model = HDMR(tensor, order=2)
|
|
126
|
+
hdmr_result = hdmr_model.reconstruct()
|
|
127
|
+
hdmr_components = hdmr_model.components
|
|
130
128
|
|
|
131
129
|
print(f"EMPR MSE: {np.mean((tensor - empr_result) ** 2):.6e}")
|
|
132
|
-
print(f"Available components: {list(empr_components.keys())}")
|
|
130
|
+
print(f\"Available EMPR components: {list(empr_components.keys())}\")
|
|
133
131
|
```
|
|
134
132
|
|
|
135
133
|
---
|
|
@@ -169,14 +167,14 @@ empr_das = EMPR(tensor, supports='das') # Data-Adaptive Supports (recommende
|
|
|
169
167
|
empr_ones = EMPR(tensor, supports='ones') # Uniform supports
|
|
170
168
|
|
|
171
169
|
# Decompose at different orders
|
|
172
|
-
result_order1 = empr_das.
|
|
173
|
-
result_order2 = empr_das.
|
|
174
|
-
result_order3 = empr_das.
|
|
170
|
+
result_order1 = empr_das.reconstruct(order=1) # Main effects only
|
|
171
|
+
result_order2 = empr_das.reconstruct(order=2) # Main effects + 2-way interactions
|
|
172
|
+
result_order3 = empr_das.reconstruct(order=3) # Full decomposition
|
|
175
173
|
|
|
176
|
-
# Extract components
|
|
177
|
-
components = empr_das.components
|
|
174
|
+
# Extract components (all stored in the underlying model)
|
|
175
|
+
components = empr_das.components
|
|
178
176
|
print("Available components:", list(components.keys()))
|
|
179
|
-
#
|
|
177
|
+
# Example: ['g_1', 'g_2', 'g_3', 'g_1,2', 'g_1,3', 'g_2,3', 'g_1,2,3']
|
|
180
178
|
|
|
181
179
|
# Component interpretation:
|
|
182
180
|
# g1, g2, g3: Main effects (univariate)
|
|
@@ -192,17 +190,17 @@ HDMR uses weighted support vectors for enhanced numerical stability:
|
|
|
192
190
|
from hdmrlib import HDMR
|
|
193
191
|
|
|
194
192
|
# Initialize HDMR with different weight types
|
|
195
|
-
hdmr_avg = HDMR(tensor, weight='avg') # Average weights (default)
|
|
196
|
-
hdmr_gauss = HDMR(tensor, weight='gaussian') # Gaussian weights
|
|
197
|
-
hdmr_cheb = HDMR(tensor, weight='chebyshev') # Chebyshev weights
|
|
193
|
+
hdmr_avg = HDMR(tensor, order=2, weight='avg') # Average weights (default)
|
|
194
|
+
hdmr_gauss = HDMR(tensor, order=2, weight='gaussian') # Gaussian weights
|
|
195
|
+
hdmr_cheb = HDMR(tensor, order=2, weight='chebyshev') # Chebyshev weights
|
|
198
196
|
|
|
199
197
|
# Custom weights
|
|
200
198
|
custom_weights = [np.ones((6, 1)), np.ones((6, 1)), np.ones((6, 1))]
|
|
201
199
|
hdmr_custom = HDMR(tensor, weight='custom', custom_weights=custom_weights)
|
|
202
200
|
|
|
203
201
|
# Decompose and analyze
|
|
204
|
-
result = hdmr_avg.
|
|
205
|
-
components = hdmr_avg.components
|
|
202
|
+
result = hdmr_avg.reconstruct(order=2)
|
|
203
|
+
components = hdmr_avg.components
|
|
206
204
|
|
|
207
205
|
# Calculate reconstruction quality
|
|
208
206
|
mse = np.mean((tensor - result) ** 2)
|
|
@@ -222,8 +220,8 @@ custom_supports = [
|
|
|
222
220
|
]
|
|
223
221
|
|
|
224
222
|
# Use custom supports
|
|
225
|
-
empr_custom = EMPR(tensor, supports='custom', custom_supports=custom_supports)
|
|
226
|
-
result = empr_custom.
|
|
223
|
+
empr_custom = EMPR(tensor, supports='custom', order=2, custom_supports=custom_supports)
|
|
224
|
+
result = empr_custom.reconstruct(order=2)
|
|
227
225
|
```
|
|
228
226
|
|
|
229
227
|
### 5. **Multi-Backend Comparison**
|
|
@@ -242,8 +240,8 @@ for backend in backends:
|
|
|
242
240
|
set_backend(backend)
|
|
243
241
|
|
|
244
242
|
start_time = time.time()
|
|
245
|
-
model = EMPR(tensor)
|
|
246
|
-
result = model.
|
|
243
|
+
model = EMPR(tensor, order=2)
|
|
244
|
+
result = model.reconstruct(order=2)
|
|
247
245
|
elapsed = time.time() - start_time
|
|
248
246
|
|
|
249
247
|
mse = np.mean((tensor - result) ** 2)
|
|
@@ -267,8 +265,8 @@ x1, x2, x3 = np.meshgrid(np.linspace(-1, 1, 8), np.linspace(-1, 1, 8), np.linspa
|
|
|
267
265
|
tensor = 5*x1**2 + 2*x2 + 0.1*x3 + x1*x2 # x1 most important, x3 least
|
|
268
266
|
|
|
269
267
|
# Decompose with EMPR
|
|
270
|
-
model = EMPR(tensor, supports='das')
|
|
271
|
-
components = model.components
|
|
268
|
+
model = EMPR(tensor, supports='das', order=2)
|
|
269
|
+
components = model.components
|
|
272
270
|
|
|
273
271
|
# Calculate component variances (sensitivity indicators)
|
|
274
272
|
sensitivities = {}
|
|
@@ -296,11 +294,11 @@ x, y, z = np.meshgrid(np.linspace(0, 1, 10), np.linspace(0, 1, 10), np.linspace(
|
|
|
296
294
|
training_data = expensive_function(x, y, z)
|
|
297
295
|
|
|
298
296
|
# Train EMPR surrogate
|
|
299
|
-
surrogate = EMPR(training_data, supports='das')
|
|
297
|
+
surrogate = EMPR(training_data, supports='das', order=3)
|
|
300
298
|
|
|
301
299
|
# Test approximation quality at different orders
|
|
302
300
|
for order in [1, 2, 3]:
|
|
303
|
-
approx = surrogate.
|
|
301
|
+
approx = surrogate.reconstruct(order=order)
|
|
304
302
|
|
|
305
303
|
# Compare on training grid
|
|
306
304
|
error = np.mean((training_data - approx) ** 2)
|
|
@@ -318,19 +316,19 @@ tensor_large = np.random.rand(20, 20, 20)
|
|
|
318
316
|
# Try PyTorch backend for potential GPU acceleration
|
|
319
317
|
try:
|
|
320
318
|
set_backend('torch')
|
|
321
|
-
model_torch = EMPR(tensor_large)
|
|
322
|
-
result_torch = model_torch.
|
|
319
|
+
model_torch = EMPR(tensor_large, order=2)
|
|
320
|
+
result_torch = model_torch.reconstruct(order=2)
|
|
323
321
|
print("PyTorch backend successful")
|
|
324
322
|
except:
|
|
325
323
|
print("PyTorch not available, using NumPy")
|
|
326
324
|
set_backend('numpy')
|
|
327
|
-
model_cpu = EMPR(tensor_large)
|
|
328
|
-
result_cpu = model_cpu.
|
|
325
|
+
model_cpu = EMPR(tensor_large, order=2)
|
|
326
|
+
result_cpu = model_cpu.reconstruct(order=2)
|
|
329
327
|
|
|
330
328
|
# For very large tensors, consider lower order approximations
|
|
331
|
-
model = EMPR(tensor_large)
|
|
332
|
-
result_fast = model.
|
|
333
|
-
result_accurate = model.
|
|
329
|
+
model = EMPR(tensor_large, order=3)
|
|
330
|
+
result_fast = model.reconstruct(order=1) # Faster, main effects only
|
|
331
|
+
result_accurate = model.reconstruct(order=3) # Slower, full interactions
|
|
334
332
|
```
|
|
335
333
|
|
|
336
334
|
---
|
|
@@ -406,18 +404,18 @@ except ValueError as e:
|
|
|
406
404
|
tensor_large = np.random.rand(50, 50, 50)
|
|
407
405
|
|
|
408
406
|
# Instead of order=3, use order=2 or order=1
|
|
409
|
-
model = EMPR(tensor_large)
|
|
410
|
-
result = model.
|
|
407
|
+
model = EMPR(tensor_large, order=1)
|
|
408
|
+
result = model.reconstruct(order=1) # Uses less memory
|
|
411
409
|
```
|
|
412
410
|
|
|
413
411
|
**4. Poor Approximation Quality**
|
|
414
412
|
```python
|
|
415
413
|
# Try different support vectors or increase order
|
|
416
|
-
model_das = EMPR(tensor, supports='das')
|
|
417
|
-
model_ones = EMPR(tensor, supports='ones')
|
|
414
|
+
model_das = EMPR(tensor, supports='das', order=2)
|
|
415
|
+
model_ones = EMPR(tensor, supports='ones', order=2)
|
|
418
416
|
|
|
419
|
-
result_das = model_das.
|
|
420
|
-
result_ones = model_ones.
|
|
417
|
+
result_das = model_das.reconstruct(order=2)
|
|
418
|
+
result_ones = model_ones.reconstruct(order=2)
|
|
421
419
|
|
|
422
420
|
mse_das = np.mean((tensor - result_das) ** 2)
|
|
423
421
|
mse_ones = np.mean((tensor - result_ones) ** 2)
|
|
@@ -81,17 +81,17 @@ tensor = np.random.rand(5, 5, 5)
|
|
|
81
81
|
set_backend('numpy')
|
|
82
82
|
|
|
83
83
|
# EMPR Decomposition
|
|
84
|
-
empr_model = EMPR(tensor)
|
|
85
|
-
empr_result = empr_model.
|
|
86
|
-
empr_components = empr_model.components
|
|
84
|
+
empr_model = EMPR(tensor, order=2)
|
|
85
|
+
empr_result = empr_model.reconstruct()
|
|
86
|
+
empr_components = empr_model.components # dict of components
|
|
87
87
|
|
|
88
88
|
# HDMR Decomposition
|
|
89
|
-
hdmr_model = HDMR(tensor)
|
|
90
|
-
hdmr_result = hdmr_model.
|
|
91
|
-
hdmr_components = hdmr_model.components
|
|
89
|
+
hdmr_model = HDMR(tensor, order=2)
|
|
90
|
+
hdmr_result = hdmr_model.reconstruct()
|
|
91
|
+
hdmr_components = hdmr_model.components
|
|
92
92
|
|
|
93
93
|
print(f"EMPR MSE: {np.mean((tensor - empr_result) ** 2):.6e}")
|
|
94
|
-
print(f"Available components: {list(empr_components.keys())}")
|
|
94
|
+
print(f\"Available EMPR components: {list(empr_components.keys())}\")
|
|
95
95
|
```
|
|
96
96
|
|
|
97
97
|
---
|
|
@@ -131,14 +131,14 @@ empr_das = EMPR(tensor, supports='das') # Data-Adaptive Supports (recommende
|
|
|
131
131
|
empr_ones = EMPR(tensor, supports='ones') # Uniform supports
|
|
132
132
|
|
|
133
133
|
# Decompose at different orders
|
|
134
|
-
result_order1 = empr_das.
|
|
135
|
-
result_order2 = empr_das.
|
|
136
|
-
result_order3 = empr_das.
|
|
134
|
+
result_order1 = empr_das.reconstruct(order=1) # Main effects only
|
|
135
|
+
result_order2 = empr_das.reconstruct(order=2) # Main effects + 2-way interactions
|
|
136
|
+
result_order3 = empr_das.reconstruct(order=3) # Full decomposition
|
|
137
137
|
|
|
138
|
-
# Extract components
|
|
139
|
-
components = empr_das.components
|
|
138
|
+
# Extract components (all stored in the underlying model)
|
|
139
|
+
components = empr_das.components
|
|
140
140
|
print("Available components:", list(components.keys()))
|
|
141
|
-
#
|
|
141
|
+
# Example: ['g_1', 'g_2', 'g_3', 'g_1,2', 'g_1,3', 'g_2,3', 'g_1,2,3']
|
|
142
142
|
|
|
143
143
|
# Component interpretation:
|
|
144
144
|
# g1, g2, g3: Main effects (univariate)
|
|
@@ -154,17 +154,17 @@ HDMR uses weighted support vectors for enhanced numerical stability:
|
|
|
154
154
|
from hdmrlib import HDMR
|
|
155
155
|
|
|
156
156
|
# Initialize HDMR with different weight types
|
|
157
|
-
hdmr_avg = HDMR(tensor, weight='avg') # Average weights (default)
|
|
158
|
-
hdmr_gauss = HDMR(tensor, weight='gaussian') # Gaussian weights
|
|
159
|
-
hdmr_cheb = HDMR(tensor, weight='chebyshev') # Chebyshev weights
|
|
157
|
+
hdmr_avg = HDMR(tensor, order=2, weight='avg') # Average weights (default)
|
|
158
|
+
hdmr_gauss = HDMR(tensor, order=2, weight='gaussian') # Gaussian weights
|
|
159
|
+
hdmr_cheb = HDMR(tensor, order=2, weight='chebyshev') # Chebyshev weights
|
|
160
160
|
|
|
161
161
|
# Custom weights
|
|
162
162
|
custom_weights = [np.ones((6, 1)), np.ones((6, 1)), np.ones((6, 1))]
|
|
163
163
|
hdmr_custom = HDMR(tensor, weight='custom', custom_weights=custom_weights)
|
|
164
164
|
|
|
165
165
|
# Decompose and analyze
|
|
166
|
-
result = hdmr_avg.
|
|
167
|
-
components = hdmr_avg.components
|
|
166
|
+
result = hdmr_avg.reconstruct(order=2)
|
|
167
|
+
components = hdmr_avg.components
|
|
168
168
|
|
|
169
169
|
# Calculate reconstruction quality
|
|
170
170
|
mse = np.mean((tensor - result) ** 2)
|
|
@@ -184,8 +184,8 @@ custom_supports = [
|
|
|
184
184
|
]
|
|
185
185
|
|
|
186
186
|
# Use custom supports
|
|
187
|
-
empr_custom = EMPR(tensor, supports='custom', custom_supports=custom_supports)
|
|
188
|
-
result = empr_custom.
|
|
187
|
+
empr_custom = EMPR(tensor, supports='custom', order=2, custom_supports=custom_supports)
|
|
188
|
+
result = empr_custom.reconstruct(order=2)
|
|
189
189
|
```
|
|
190
190
|
|
|
191
191
|
### 5. **Multi-Backend Comparison**
|
|
@@ -204,8 +204,8 @@ for backend in backends:
|
|
|
204
204
|
set_backend(backend)
|
|
205
205
|
|
|
206
206
|
start_time = time.time()
|
|
207
|
-
model = EMPR(tensor)
|
|
208
|
-
result = model.
|
|
207
|
+
model = EMPR(tensor, order=2)
|
|
208
|
+
result = model.reconstruct(order=2)
|
|
209
209
|
elapsed = time.time() - start_time
|
|
210
210
|
|
|
211
211
|
mse = np.mean((tensor - result) ** 2)
|
|
@@ -229,8 +229,8 @@ x1, x2, x3 = np.meshgrid(np.linspace(-1, 1, 8), np.linspace(-1, 1, 8), np.linspa
|
|
|
229
229
|
tensor = 5*x1**2 + 2*x2 + 0.1*x3 + x1*x2 # x1 most important, x3 least
|
|
230
230
|
|
|
231
231
|
# Decompose with EMPR
|
|
232
|
-
model = EMPR(tensor, supports='das')
|
|
233
|
-
components = model.components
|
|
232
|
+
model = EMPR(tensor, supports='das', order=2)
|
|
233
|
+
components = model.components
|
|
234
234
|
|
|
235
235
|
# Calculate component variances (sensitivity indicators)
|
|
236
236
|
sensitivities = {}
|
|
@@ -258,11 +258,11 @@ x, y, z = np.meshgrid(np.linspace(0, 1, 10), np.linspace(0, 1, 10), np.linspace(
|
|
|
258
258
|
training_data = expensive_function(x, y, z)
|
|
259
259
|
|
|
260
260
|
# Train EMPR surrogate
|
|
261
|
-
surrogate = EMPR(training_data, supports='das')
|
|
261
|
+
surrogate = EMPR(training_data, supports='das', order=3)
|
|
262
262
|
|
|
263
263
|
# Test approximation quality at different orders
|
|
264
264
|
for order in [1, 2, 3]:
|
|
265
|
-
approx = surrogate.
|
|
265
|
+
approx = surrogate.reconstruct(order=order)
|
|
266
266
|
|
|
267
267
|
# Compare on training grid
|
|
268
268
|
error = np.mean((training_data - approx) ** 2)
|
|
@@ -280,19 +280,19 @@ tensor_large = np.random.rand(20, 20, 20)
|
|
|
280
280
|
# Try PyTorch backend for potential GPU acceleration
|
|
281
281
|
try:
|
|
282
282
|
set_backend('torch')
|
|
283
|
-
model_torch = EMPR(tensor_large)
|
|
284
|
-
result_torch = model_torch.
|
|
283
|
+
model_torch = EMPR(tensor_large, order=2)
|
|
284
|
+
result_torch = model_torch.reconstruct(order=2)
|
|
285
285
|
print("PyTorch backend successful")
|
|
286
286
|
except:
|
|
287
287
|
print("PyTorch not available, using NumPy")
|
|
288
288
|
set_backend('numpy')
|
|
289
|
-
model_cpu = EMPR(tensor_large)
|
|
290
|
-
result_cpu = model_cpu.
|
|
289
|
+
model_cpu = EMPR(tensor_large, order=2)
|
|
290
|
+
result_cpu = model_cpu.reconstruct(order=2)
|
|
291
291
|
|
|
292
292
|
# For very large tensors, consider lower order approximations
|
|
293
|
-
model = EMPR(tensor_large)
|
|
294
|
-
result_fast = model.
|
|
295
|
-
result_accurate = model.
|
|
293
|
+
model = EMPR(tensor_large, order=3)
|
|
294
|
+
result_fast = model.reconstruct(order=1) # Faster, main effects only
|
|
295
|
+
result_accurate = model.reconstruct(order=3) # Slower, full interactions
|
|
296
296
|
```
|
|
297
297
|
|
|
298
298
|
---
|
|
@@ -368,18 +368,18 @@ except ValueError as e:
|
|
|
368
368
|
tensor_large = np.random.rand(50, 50, 50)
|
|
369
369
|
|
|
370
370
|
# Instead of order=3, use order=2 or order=1
|
|
371
|
-
model = EMPR(tensor_large)
|
|
372
|
-
result = model.
|
|
371
|
+
model = EMPR(tensor_large, order=1)
|
|
372
|
+
result = model.reconstruct(order=1) # Uses less memory
|
|
373
373
|
```
|
|
374
374
|
|
|
375
375
|
**4. Poor Approximation Quality**
|
|
376
376
|
```python
|
|
377
377
|
# Try different support vectors or increase order
|
|
378
|
-
model_das = EMPR(tensor, supports='das')
|
|
379
|
-
model_ones = EMPR(tensor, supports='ones')
|
|
378
|
+
model_das = EMPR(tensor, supports='das', order=2)
|
|
379
|
+
model_ones = EMPR(tensor, supports='ones', order=2)
|
|
380
380
|
|
|
381
|
-
result_das = model_das.
|
|
382
|
-
result_ones = model_ones.
|
|
381
|
+
result_das = model_das.reconstruct(order=2)
|
|
382
|
+
result_ones = model_ones.reconstruct(order=2)
|
|
383
383
|
|
|
384
384
|
mse_das = np.mean((tensor - result_das) ** 2)
|
|
385
385
|
mse_ones = np.mean((tensor - result_ones) ** 2)
|
|
@@ -10,6 +10,6 @@ __license__ = "MIT"
|
|
|
10
10
|
|
|
11
11
|
from .hdmr import HDMR
|
|
12
12
|
from .empr import EMPR
|
|
13
|
-
from .backends import set_backend, get_backend
|
|
13
|
+
from .backends import set_backend, get_backend, available_backends
|
|
14
14
|
|
|
15
15
|
__all__ = ['HDMR', 'EMPR', 'set_backend', 'get_backend', '__version__']
|
|
@@ -1,41 +1,53 @@
|
|
|
1
|
-
try:
|
|
2
|
-
from .numpy_backend import NumPyBackend
|
|
3
|
-
except Exception:
|
|
4
|
-
NumPyBackend = None
|
|
5
|
-
|
|
6
|
-
try:
|
|
7
|
-
from .torch_backend import TorchBackend
|
|
8
|
-
except Exception:
|
|
9
|
-
TorchBackend = None
|
|
10
|
-
|
|
11
|
-
try:
|
|
12
|
-
from .tensorflow_backend import TensorFlowBackend
|
|
13
|
-
except Exception:
|
|
14
|
-
TensorFlowBackend = None
|
|
15
|
-
|
|
16
|
-
_BACKEND_MAP = {}
|
|
17
|
-
if NumPyBackend is not None:
|
|
18
|
-
_BACKEND_MAP['numpy'] = NumPyBackend()
|
|
19
|
-
if TorchBackend is not None:
|
|
20
|
-
_BACKEND_MAP['torch'] = TorchBackend()
|
|
21
|
-
if TensorFlowBackend is not None:
|
|
22
|
-
_BACKEND_MAP['tensorflow'] = TensorFlowBackend()
|
|
23
|
-
|
|
24
|
-
_CURRENT_BACKEND = 'numpy' if 'numpy' in _BACKEND_MAP else (next(iter(_BACKEND_MAP.keys()), None))
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def set_backend(name):
|
|
28
|
-
global _CURRENT_BACKEND
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
1
|
+
try:
|
|
2
|
+
from .numpy_backend import NumPyBackend
|
|
3
|
+
except Exception:
|
|
4
|
+
NumPyBackend = None
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
from .torch_backend import TorchBackend
|
|
8
|
+
except Exception:
|
|
9
|
+
TorchBackend = None
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
from .tensorflow_backend import TensorFlowBackend
|
|
13
|
+
except Exception:
|
|
14
|
+
TensorFlowBackend = None
|
|
15
|
+
|
|
16
|
+
_BACKEND_MAP = {}
|
|
17
|
+
if NumPyBackend is not None:
|
|
18
|
+
_BACKEND_MAP['numpy'] = NumPyBackend()
|
|
19
|
+
if TorchBackend is not None:
|
|
20
|
+
_BACKEND_MAP['torch'] = TorchBackend()
|
|
21
|
+
if TensorFlowBackend is not None:
|
|
22
|
+
_BACKEND_MAP['tensorflow'] = TensorFlowBackend()
|
|
23
|
+
|
|
24
|
+
_CURRENT_BACKEND = 'numpy' if 'numpy' in _BACKEND_MAP else (next(iter(_BACKEND_MAP.keys()), None))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def set_backend(name):
|
|
28
|
+
global _CURRENT_BACKEND
|
|
29
|
+
name = (name or "").lower()
|
|
30
|
+
if name == "tf":
|
|
31
|
+
name = "tensorflow"
|
|
32
|
+
|
|
33
|
+
if name not in _BACKEND_MAP:
|
|
34
|
+
if name == "torch":
|
|
35
|
+
raise ImportError("Torch backend not available. Install with: pip install 'hdmrlib[torch]'")
|
|
36
|
+
if name == "tensorflow":
|
|
37
|
+
raise ImportError("TensorFlow backend not available. Install with: pip install 'hdmrlib[tensorflow]'")
|
|
38
|
+
raise ValueError(f"Unknown backend: {name}")
|
|
39
|
+
|
|
40
|
+
_CURRENT_BACKEND = name
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def get_backend():
|
|
44
|
+
return _CURRENT_BACKEND
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get_backend_instance():
|
|
48
|
+
if _CURRENT_BACKEND is None:
|
|
49
|
+
raise RuntimeError("No available backend. Please install a supported backend and try again.")
|
|
50
|
+
return _BACKEND_MAP[_CURRENT_BACKEND]
|
|
51
|
+
|
|
52
|
+
def available_backends():
|
|
53
|
+
return list(_BACKEND_MAP.keys())
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
|
|
3
|
+
class BaseBackend(ABC):
|
|
4
|
+
|
|
5
|
+
@abstractmethod
|
|
6
|
+
def get_hdmr_model(self, tensor, **kwargs):
|
|
7
|
+
"""Return an HDMR model instance for reconstruction."""
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
@abstractmethod
|
|
11
|
+
def get_empr_model(self, tensor, **kwargs):
|
|
12
|
+
"""Return an EMPR model instance for reconstruction."""
|
|
13
|
+
pass
|
|
@@ -7,13 +7,19 @@ class NumPyBackend(BaseBackend):
|
|
|
7
7
|
class _HDMR:
|
|
8
8
|
def __init__(self, G, weight="avg", custom_weights=None, supports='ones', custom_supports=None):
|
|
9
9
|
self.G = np.array(G, dtype=np.float64)
|
|
10
|
-
|
|
10
|
+
# Check for singleton dimensions and squeeze if present
|
|
11
|
+
if 1 in self.G.shape:
|
|
12
|
+
self.G = np.squeeze(self.G)
|
|
13
|
+
print(f"Warning: Input tensor contained singleton dimensions.")
|
|
14
|
+
print(f"Original shape: {G.shape}")
|
|
15
|
+
print(f"Squeezed shape: {self.G.shape}")
|
|
16
|
+
self.dimensions = self.G.shape
|
|
11
17
|
self.custom_supports = custom_supports
|
|
12
18
|
self.support_vectors = self.initialize_support_vectors(supports)
|
|
13
19
|
self.custom_weights = custom_weights
|
|
14
20
|
self.weights = self.initialize_weights(weight)
|
|
15
21
|
self.g0 = self.calculate_g0()
|
|
16
|
-
self.g_components = {}
|
|
22
|
+
self.g_components = {'g_0': self.g0}
|
|
17
23
|
self.calculate_hdmr_component(np.arange(len(self.dimensions)))
|
|
18
24
|
|
|
19
25
|
def initialize_weights(self, weight):
|
|
@@ -65,9 +71,7 @@ class NumPyBackend(BaseBackend):
|
|
|
65
71
|
elif supports == 'ones':
|
|
66
72
|
for dim_size in self.dimensions:
|
|
67
73
|
s = np.ones((dim_size, 1), dtype=np.float64)
|
|
68
|
-
|
|
69
|
-
modified_s = (s * (dim_size ** 0.5)) / l2_norm
|
|
70
|
-
support_vectors.append(modified_s)
|
|
74
|
+
support_vectors.append(s)
|
|
71
75
|
elif supports == 'custom':
|
|
72
76
|
if self.custom_supports is None:
|
|
73
77
|
raise ValueError("Custom supports must be provided for 'custom' support type.")
|
|
@@ -155,11 +159,18 @@ class NumPyBackend(BaseBackend):
|
|
|
155
159
|
class _EMPR:
|
|
156
160
|
def __init__(self, G, supports='das', custom_supports=None):
|
|
157
161
|
self.G = np.array(G, dtype=np.float64)
|
|
158
|
-
|
|
162
|
+
# Check for singleton dimensions and squeeze if present
|
|
163
|
+
if 1 in self.G.shape:
|
|
164
|
+
self.G = np.squeeze(self.G)
|
|
165
|
+
print(f"Warning: Input tensor contained singleton dimensions.")
|
|
166
|
+
print(f"Original shape: {G.shape}")
|
|
167
|
+
print(f"Squeezed shape: {self.G.shape}")
|
|
168
|
+
self.dimensions = self.G.shape
|
|
159
169
|
self.custom_supports = custom_supports
|
|
160
170
|
self.support_vectors = self.initialize_support_vectors(supports)
|
|
171
|
+
self.weights = [1 / dim for dim in self.dimensions]
|
|
161
172
|
self.g0 = self.calculate_g0()
|
|
162
|
-
self.g_components = {}
|
|
173
|
+
self.g_components = {'g_0': self.g0}
|
|
163
174
|
self.calculate_empr_component(np.arange(len(self.dimensions)))
|
|
164
175
|
|
|
165
176
|
def initialize_support_vectors(self, supports):
|
|
@@ -192,8 +203,8 @@ class NumPyBackend(BaseBackend):
|
|
|
192
203
|
|
|
193
204
|
def calculate_g0(self):
|
|
194
205
|
g0 = self.G
|
|
195
|
-
for
|
|
196
|
-
g0 = np.tensordot(g0, s, axes=([0], [0]))
|
|
206
|
+
for s, w in zip(self.support_vectors, self.weights):
|
|
207
|
+
g0 = np.tensordot(g0, s, axes=([0], [0])) * w
|
|
197
208
|
return float(np.squeeze(g0))
|
|
198
209
|
|
|
199
210
|
def convert_g_to_string(self, dims):
|
|
@@ -212,16 +223,16 @@ class NumPyBackend(BaseBackend):
|
|
|
212
223
|
involved_dims = sorted(involved_dims)
|
|
213
224
|
# First part
|
|
214
225
|
ind = 0
|
|
215
|
-
for j, s in enumerate(self.support_vectors):
|
|
226
|
+
for j, (s, w) in enumerate(zip(self.support_vectors, self.weights)):
|
|
216
227
|
if j not in involved_dims:
|
|
217
|
-
G_component = np.tensordot(G_component, s, axes=([ind], [0]))
|
|
228
|
+
G_component = np.tensordot(G_component, s, axes=([ind], [0])) * w
|
|
218
229
|
else:
|
|
219
230
|
ind += 1
|
|
220
231
|
# Second part
|
|
221
|
-
subtracted = np.squeeze(self.support_vectors[involved_dims[0]] * self.g0)
|
|
232
|
+
subtracted = np.squeeze(self.support_vectors[involved_dims[0]] * self.weights[involved_dims[0]] * self.g0)
|
|
222
233
|
for i in range(1, len(involved_dims)):
|
|
223
234
|
subtracted = np.einsum('...i,jk->...ij', subtracted,
|
|
224
|
-
self.support_vectors[involved_dims[i]])
|
|
235
|
+
self.support_vectors[involved_dims[i]] * self.weights[involved_dims[i]])
|
|
225
236
|
# Third part
|
|
226
237
|
if len(involved_dims) > 1:
|
|
227
238
|
for i in range(1, len(involved_dims)):
|
|
@@ -230,7 +241,7 @@ class NumPyBackend(BaseBackend):
|
|
|
230
241
|
term = np.squeeze(self.g_components[self.convert_g_to_string(g_combination)])
|
|
231
242
|
for k in range(len(s)):
|
|
232
243
|
term = np.einsum('...i,jk->...ij', term,
|
|
233
|
-
self.support_vectors[s[k]])
|
|
244
|
+
self.support_vectors[s[k]] * self.weights[s[k]])
|
|
234
245
|
subtracted += np.transpose(term, np.argsort(list(g_combination) + s))
|
|
235
246
|
G_component = np.squeeze(G_component)
|
|
236
247
|
subtracted = np.squeeze(subtracted)
|
|
@@ -240,10 +251,10 @@ class NumPyBackend(BaseBackend):
|
|
|
240
251
|
def calculate_approximation(self, order):
|
|
241
252
|
involved_dims = np.arange(len(self.dimensions))
|
|
242
253
|
# First part
|
|
243
|
-
overall_sum = np.squeeze(self.support_vectors[involved_dims[0]] * self.g0)
|
|
254
|
+
overall_sum = np.squeeze(self.support_vectors[involved_dims[0]] * self.weights[involved_dims[0]] * self.g0)
|
|
244
255
|
for i in range(1, len(involved_dims)):
|
|
245
256
|
overall_sum = np.einsum('...i,jk->...ij', overall_sum,
|
|
246
|
-
self.support_vectors[involved_dims[i]])
|
|
257
|
+
self.support_vectors[involved_dims[i]] * self.weights[involved_dims[i]])
|
|
247
258
|
# Second-N'th part
|
|
248
259
|
for i in range(1, order+1):
|
|
249
260
|
for g_combination in combinations(involved_dims, i):
|
|
@@ -251,7 +262,7 @@ class NumPyBackend(BaseBackend):
|
|
|
251
262
|
term = np.squeeze(self.g_components[self.convert_g_to_string(g_combination)])
|
|
252
263
|
for k in range(len(s)):
|
|
253
264
|
term = np.einsum('...i,jk->...ij', term,
|
|
254
|
-
self.support_vectors[s[k]])
|
|
265
|
+
self.support_vectors[s[k]] * self.weights[s[k]])
|
|
255
266
|
overall_sum += np.transpose(term, np.argsort(list(g_combination) + s))
|
|
256
267
|
return np.squeeze(overall_sum)
|
|
257
268
|
|
|
@@ -262,36 +273,10 @@ class NumPyBackend(BaseBackend):
|
|
|
262
273
|
mse = squared_error / num_elements
|
|
263
274
|
return float(mse)
|
|
264
275
|
|
|
265
|
-
def
|
|
266
|
-
model
|
|
267
|
-
return
|
|
268
|
-
|
|
269
|
-
def empr_decompose(self, tensor, order=2, **kwargs):
|
|
270
|
-
model = self._EMPR(tensor, **kwargs)
|
|
271
|
-
return model.calculate_approximation(order)
|
|
272
|
-
|
|
273
|
-
def hdmr_components(self, tensor, max_order=None, **kwargs):
|
|
274
|
-
model = self._HDMR(tensor, **kwargs)
|
|
275
|
-
num_dims = len(model.dimensions)
|
|
276
|
-
if max_order is None:
|
|
277
|
-
max_order = num_dims
|
|
278
|
-
components = {}
|
|
279
|
-
dims = list(range(num_dims))
|
|
280
|
-
for r in range(1, min(max_order, num_dims) + 1):
|
|
281
|
-
for comb in combinations(dims, r):
|
|
282
|
-
key = model.convert_g_to_string(comb)
|
|
283
|
-
components[key] = model.g_components[key]
|
|
284
|
-
return components
|
|
276
|
+
def get_hdmr_model(self, tensor, **kwargs):
|
|
277
|
+
"""Return an HDMR model instance for reconstruction."""
|
|
278
|
+
return self._HDMR(tensor, **kwargs)
|
|
285
279
|
|
|
286
|
-
def
|
|
287
|
-
model
|
|
288
|
-
|
|
289
|
-
if max_order is None:
|
|
290
|
-
max_order = num_dims
|
|
291
|
-
components = {}
|
|
292
|
-
dims = list(range(num_dims))
|
|
293
|
-
for r in range(1, min(max_order, num_dims) + 1):
|
|
294
|
-
for comb in combinations(dims, r):
|
|
295
|
-
key = model.convert_g_to_string(comb)
|
|
296
|
-
components[key] = model.g_components[key]
|
|
297
|
-
return components
|
|
280
|
+
def get_empr_model(self, tensor, **kwargs):
|
|
281
|
+
"""Return an EMPR model instance for reconstruction."""
|
|
282
|
+
return self._EMPR(tensor, **kwargs)
|