LenixC commited on
Commit
e90417e
·
1 Parent(s): c565a82

Built the gradio implementation of the example.

Browse files
Files changed (2) hide show
  1. app.py +78 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gradio Implementation: Lenix Carter
2
+ # License: BSD 3-Clause or CC-0
3
+
4
+ import gradio as gr
5
+
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ from sklearn.metrics import r2_score
9
+
10
+ from sklearn.model_selection import train_test_split
11
+ from sklearn.linear_model import LinearRegression
12
+
13
+ plt.switch_backend("agg")
14
+
15
+ def compare_reg(n_samples, n_features):
16
+ np.random.seed(42)
17
+
18
+ X = np.random.randn(n_samples, n_features)
19
+ true_coef = 3 * np.random.randn(n_features)
20
+
21
+ # Threshold coefficients to render them non-negative
22
+ true_coef[true_coef < 0] = 0
23
+ y = np.dot(X, true_coef)
24
+
25
+ # Add some noise
26
+ y += 5 * np.random.normal(size=(n_samples,))
27
+
28
+ # Split the data in train set and test set
29
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)
30
+
31
+ reg_nnls = LinearRegression(positive=True)
32
+ y_pred_nnls = reg_nnls.fit(X_train, y_train).predict(X_test)
33
+ r2_score_nnls = r2_score(y_test, y_pred_nnls)
34
+
35
+ reg_ols = LinearRegression()
36
+ y_pred_ols = reg_ols.fit(X_train, y_train).predict(X_test)
37
+ r2_score_ols = r2_score(y_test, y_pred_ols)
38
+
39
+ fig, ax = plt.subplots()
40
+ ax.plot(reg_ols.coef_, reg_nnls.coef_, linewidth=0, marker=".")
41
+
42
+ low_x, high_x = ax.get_xlim()
43
+ low_y, high_y = ax.get_ylim()
44
+ low = max(low_x, low_y)
45
+ high = min(high_x, high_y)
46
+ ax.plot([low, high], [low, high], ls="--", c=".3", alpha=0.5)
47
+ ax.set_xlabel("OLS regression coefficients", fontweight="bold")
48
+ ax.set_ylabel("NNLS regression coefficients", fontweight="bold")
49
+
50
+ scores = "The R2 for NNLS is {}\nThe R2 for OLS is {}".format(r2_score_nnls, r2_score_ols)
51
+ return fig, scores
52
+
53
+ title = "Non-negative Least Squares"
54
+ with gr.Blocks() as demo:
55
+ gr.Markdown(f" # {title}")
56
+ gr.Markdown("""
57
+ This example fits a linear model with positivity constraints on the regression coefficients and compares the estimated coefficients to a classic linear regression.
58
+
59
+ This is based on the example [here](https://scikit-learn.org/stable/auto_examples/linear_model/plot_nnls.html#sphx-glr-auto-examples-linear-model-plot-nnls-py).
60
+ """)
61
+ with gr.Row():
62
+ with gr.Column():
63
+ n_samp = gr.Slider(100, 1000, 200, step=1, label="Number of Samples")
64
+ n_feat = gr.Slider(3, 100, 50, step=1, label="Number of Features")
65
+ btn = gr.Button(label="Run")
66
+ with gr.Column():
67
+ scores = gr.Textbox(label="R2 Scores")
68
+ coeff_comp_graph = gr.Plot(label="Comparison of Coefficients")
69
+ btn.click(
70
+ fn=compare_reg,
71
+ inputs=[n_samp, n_feat],
72
+ outputs=[coeff_comp_graph, scores]
73
+ )
74
+ with gr.Row():
75
+ gr.Markdown("This shows a high degree of correlation between the the regression coefficients of OLS and NNLS. However, we observe that some coefficients in the NNLS regression shrink to 0.")
76
+
77
+ if __name__ == '__main__':
78
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ matplotlib==3.6.3
2
+ scikit-learn==1.2.2