Dea22's picture
Upload 2 files
bdd8d5b
raw
history blame
3.14 kB
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('''
<div>
<h1 style='text-align: center'> Joint feature selection with multi-task Lasso </h1>
</div>
''')
gr.Markdown(model_card)
gr.Markdown("Original example Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>")
gr.Markdown(
"Iterative conversion by: <a href=\"https://github.com/DeaMariaLeon\">Dea María Léon</a>"
)
n_samples = gr.Slider(50,500,value=100,step=50,label='Select number of samples')
n_features = gr.Slider(5,50,value=30,step=5,label='Select number of features')
n_tasks = gr.Slider(5,50,value=40,step=5,label='Select number of tasks')
n_relevant_features = gr.Slider(1,10,value=5,step=1,label='Select number of relevant_features')
with gr.Column():
with gr.Tab('Select Alpha Range'):
alpha = gr.Slider(0,10,value=1.0,step=0.5,label='alpha')
btn = gr.Button(value = 'Submit')
btn.click(make_plot,inputs=[n_samples,n_features, n_tasks, n_relevant_features, alpha],outputs=[gr.Plot()])
demo.launch()