import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import MultiTaskLasso, Lasso import gradio as gr rng = np.random.RandomState(42) # Generate some 2D coefficients with sine waves with random frequency and phase def make_plot(n_samples, n_features, n_tasks, n_relevant_features, alpha): coef = np.zeros((n_tasks, n_features)) times = np.linspace(0, 2 * np.pi, n_tasks) for k in range(n_relevant_features): coef[:, k] = np.sin((1.0 + rng.randn(1)) * times + 3 * rng.randn(1)) X = rng.randn(n_samples, n_features) Y = np.dot(X, coef.T) + rng.randn(n_samples, n_tasks) coef_lasso_ = np.array([Lasso(alpha=0.5).fit(X, y).coef_ for y in Y.T]) coef_multi_task_lasso_ = MultiTaskLasso(alpha=alpha).fit(X, Y).coef_ fig = plt.figure(figsize=(8, 5)) feature_to_plot = 0 fig = plt.figure() lw = 2 plt.plot(coef[:, feature_to_plot], color="seagreen", linewidth=lw, label="Ground truth") plt.plot( coef_lasso_[:, feature_to_plot], color="cornflowerblue", linewidth=lw, label="Lasso" ) plt.plot( coef_multi_task_lasso_[:, feature_to_plot], color="gold", linewidth=lw, label="MultiTaskLasso", ) plt.legend(loc="upper center") plt.axis("tight") plt.ylim([-1.1, 1.1]) fig.suptitle("Lasso, MultiTaskLasso and Ground truth time series") return fig model_card=f""" ## Description The multi-task lasso allows to fit multiple regression problems jointly enforcing the selected features to be the same across tasks. This example simulates sequential measurements, each task is a time instant, and the relevant features vary in amplitude over time while being the same. The multi-task lasso imposes that features that are selected at one time point are select for all time point. This makes feature selection by the Lasso more stable. ## Model currentmodule: sklearn.linear_model class:`Lasso` and class: `MultiTaskLasso` are used in this example. Plots represent Lasso, MultiTaskLasso and Ground truth time series """ with gr.Blocks() as demo: gr.Markdown('''