Created
February 22, 2026 21:42
-
-
Save robintux/48a62f42a01ceee7c319c0f6b80acd75 to your computer and use it in GitHub Desktop.
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 | |
| import matplotlib.pyplot as plt | |
| from sklearn.pipeline import Pipeline | |
| from sklearn.preprocessing import PolynomialFeatures | |
| from sklearn.linear_model import LinearRegression | |
| from sklearn.metrics import mean_squared_error | |
| from sklearn.model_selection import train_test_split | |
| # Configuración de estilo para publicaciones académicas | |
| plt.style.use('seaborn-v0_8-whitegrid') | |
| plt.rcParams['figure.figsize'] = (12, 10) | |
| plt.rcParams['font.size'] = 12 | |
| def generate_data(n_samples=100, noise_std=0.1, random_state=42): | |
| """ | |
| Genera datos sintéticos basados en una función verdadera conocida. | |
| """ | |
| np.random.seed(random_state) | |
| X = np.linspace(0, 1, n_samples) | |
| # Función verdadera: f*(x) = sin(2 * pi * x) | |
| y_true = np.sin(2 * np.pi * X) | |
| # Observaciones: y = f*(x) + epsilon | |
| y_noise = y_true + np.random.normal(0, noise_std, n_samples) | |
| return X, y_true, y_noise | |
| def create_polynomial_model(degree): | |
| """ | |
| Crea un pipeline de regresión polinómica. | |
| """ | |
| model = Pipeline([ | |
| ('poly', PolynomialFeatures(degree=degree, include_bias=False)), | |
| ('linear', LinearRegression()) | |
| ]) | |
| return model | |
| def evaluate_model(model, X_train, y_train, X_test, y_test, y_true_func): | |
| """ | |
| Entrena y evalúa el modelo retornando métricas y predicciones. | |
| """ | |
| model.fit(X_train.reshape(-1, 1), y_train) | |
| # Predicciones | |
| y_train_pred = model.predict(X_train.reshape(-1, 1)) | |
| y_test_pred = model.predict(X_test.reshape(-1, 1)) | |
| # Errores | |
| mse_train = mean_squared_error(y_train, y_train_pred) | |
| mse_test = mean_squared_error(y_test, y_test_pred) | |
| # Error respecto a la función verdadera (sin ruido) en el conjunto de test | |
| # Esto nos dice qué tan bien aprendimos la señal real | |
| mse_true = mean_squared_error(y_true_func(X_test), y_test_pred) | |
| return mse_train, mse_test, mse_true, y_test_pred |
Author
robintux
commented
Feb 22, 2026
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment