Last active
November 14, 2025 02:45
-
-
Save pukpr/6c4904b7e11ede2abc9c648a4154e4d1 to your computer and use it in GitHub Desktop.
SINDy example of a non-autonomous fit to a hidden latent layer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| from sklearn.linear_model import Lasso | |
| # ---------------------------- | |
| # USER INPUT: hidden layer & target | |
| # ---------------------------- | |
| # Example synthetic data (replace with your arrays) | |
| N = 1000 | |
| t = np.linspace(0, 10, N) | |
| hidden_layer = np.sin(2*np.pi*1*t) + 0.5*np.sin(2*np.pi*3*t) # latent forcing | |
| target = 2*np.sin(2*np.pi*1*t + 0.2) + 0.7*np.cos(2*np.pi*3*t - 0.3) # observed output | |
| # ---------------------------- | |
| # Parameters | |
| # ---------------------------- | |
| max_harmonic = 3 # max multiple of the latent phase to include | |
| alpha = 1e-3 # Lasso sparsity regularization | |
| fit_intercept = True # include intercept in regression | |
| # ---------------------------- | |
| # Build library of sin/cos functions | |
| # ---------------------------- | |
| library_list = [] | |
| for n in range(1, max_harmonic+1): | |
| library_list.append(np.sin(n * hidden_layer)) | |
| library_list.append(np.cos(n * hidden_layer)) | |
| Theta = np.column_stack(library_list) # shape (N, 2*max_harmonic) | |
| # ---------------------------- | |
| # Fit sparse regression (non-autonomous SINDy) | |
| # ---------------------------- | |
| lasso = Lasso(alpha=alpha, fit_intercept=fit_intercept) | |
| lasso.fit(Theta, target) | |
| Xi = lasso.coef_ | |
| intercept = lasso.intercept_ | |
| # ---------------------------- | |
| # Prediction | |
| # ---------------------------- | |
| y_pred = Theta @ Xi + intercept | |
| # ---------------------------- | |
| # Diagnostics / display | |
| # ---------------------------- | |
| print("Selected coefficients (Xi):") | |
| for i, coef in enumerate(Xi): | |
| func_type = 'sin' if i%2==0 else 'cos' | |
| harmonic = (i//2)+1 | |
| print(f"{func_type}({harmonic}*latent) -> {coef:.4f}") | |
| print(f"Intercept: {intercept:.4f}") | |
| # Optional: plot | |
| import matplotlib.pyplot as plt | |
| plt.figure(figsize=(10,4)) | |
| plt.plot(t, target, label='Target') | |
| plt.plot(t, y_pred, '--', label='SINDy Pred') | |
| plt.xlabel('Time') | |
| plt.ylabel('Observable') | |
| plt.legend() | |
| plt.show() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SINDy, KAN, Koopman views:
https://chatgpt.com/share/690f5eea-267c-8006-8c8d-f7d584714fbd
overview
