NTaylor commited on
Commit
06870e1
·
0 Parent(s):

Duplicate from NTaylor/compare-bayesian-regressors

Browse files
Files changed (4) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +295 -0
  4. requirements.txt +4 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Compare Bayesian Regressors
3
+ emoji: 🐨
4
+ colorFrom: yellow
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 3.27.0
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: NTaylor/compare-bayesian-regressors
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.pipeline import make_pipeline
2
+ from sklearn.preprocessing import PolynomialFeatures, StandardScaler
3
+ import numpy as np
4
+ from sklearn.datasets import make_regression
5
+ import pandas as pd
6
+ from sklearn.linear_model import ARDRegression, LinearRegression, BayesianRidge
7
+ import matplotlib.pyplot as plt
8
+ from matplotlib.colors import SymLogNorm
9
+ import gradio as gr
10
+ import seaborn as sns
11
+
12
+
13
+ X, y, true_weights = make_regression(
14
+ n_samples=100,
15
+ n_features=100,
16
+ n_informative=10,
17
+ noise=8,
18
+ coef=True,
19
+ random_state=42,
20
+ )
21
+
22
+ # Fit the regressors
23
+ # ------------------
24
+ #
25
+ # We now fit both Bayesian models and the OLS to later compare the models'
26
+ # coefficients.
27
+
28
+
29
+ def fit_regression_models(n_iter=30, X=X, y=y, true_weights=true_weights):
30
+ olr = LinearRegression().fit(X, y)
31
+ print(f"inside fit_regression n_iter={n_iter}")
32
+ brr = BayesianRidge(compute_score=True, n_iter=n_iter).fit(X, y)
33
+ ard = ARDRegression(compute_score=True, n_iter=n_iter).fit(X, y)
34
+ df = pd.DataFrame(
35
+ {
36
+ "Weights of true generative process": true_weights,
37
+ "ARDRegression": ard.coef_,
38
+ "BayesianRidge": brr.coef_,
39
+ "LinearRegression": olr.coef_,
40
+ }
41
+ )
42
+ return df, olr, brr, ard
43
+
44
+
45
+
46
+ # %%
47
+ # Plot the true and estimated coefficients
48
+ # ----------------------------------------
49
+ #
50
+ # Now we compare the coefficients of each model with the weights of
51
+ # the true generative model.
52
+
53
+ def visualize_coefficients(df=None):
54
+ fig = plt.figure(figsize=(10, 6))
55
+ ax = sns.heatmap(
56
+ df.T,
57
+ norm=SymLogNorm(linthresh=10e-4, vmin=-80, vmax=80),
58
+ cbar_kws={"label": "coefficients' values"},
59
+ cmap="seismic_r",
60
+ )
61
+ plt.ylabel("linear model")
62
+ plt.xlabel("coefficients")
63
+ plt.tight_layout(rect=(0, 0, 1, 0.95))
64
+ _ = plt.title("Models' coefficients")
65
+
66
+ return fig
67
+
68
+ # %%
69
+ # Due to the added noise, none of the models recover the true weights. Indeed,
70
+ # all models always have more than 10 non-zero coefficients. Compared to the OLS
71
+ # estimator, the coefficients using a Bayesian Ridge regression are slightly
72
+ # shifted toward zero, which stabilises them. The ARD regression provides a
73
+ # sparser solution: some of the non-informative coefficients are set exactly to
74
+ # zero, while shifting others closer to zero. Some non-informative coefficients
75
+ # are still present and retain large values.
76
+
77
+ # %%
78
+ # Plot the marginal log-likelihood
79
+ # --------------------------------
80
+
81
+
82
+ def plot_marginal_log_likelihood(ard=None, brr=None, n_iter=30):
83
+
84
+ fig = plt.figure(figsize=(10, 6))
85
+ ard_scores = -np.array(ard.scores_)
86
+ brr_scores = -np.array(brr.scores_)
87
+ # print(f"ard_scores = {ard_scores}")
88
+ # print(f"brr_scores = {brr_scores}")
89
+ plt.plot(ard_scores, color="navy", label="ARD")
90
+ plt.plot(brr_scores, color="red", label="BayesianRidge")
91
+ plt.ylabel("Log-likelihood")
92
+ plt.xlabel("Iterations")
93
+ plt.xlim(1, n_iter)
94
+ plt.legend()
95
+ _ = plt.title("Models log-likelihood")
96
+
97
+ print("fig inside plot marginal = ", fig)
98
+ return fig
99
+
100
+ def make_regression_comparison_plot(n_iter=30):
101
+
102
+ # print(f"n_iter = {n_iter}")
103
+ # fit models
104
+ df, olr, brr, ard = fit_regression_models(n_iter=n_iter, X=X, y=y, true_weights=true_weights)
105
+ # print(f"df = {df}")
106
+ # get figure
107
+ fig = visualize_coefficients(df=df)
108
+
109
+ return fig
110
+
111
+ def make_log_likelihood_plot(n_iter=30):
112
+
113
+ # print(f"n_iter = {n_iter}")
114
+ # fit models
115
+ df, olr, brr, ard = fit_regression_models(n_iter=n_iter, X=X, y=y, true_weights=true_weights)
116
+ # print(f"df = {df}")
117
+ # get figure
118
+ fig = plot_marginal_log_likelihood(ard=ard, brr=brr, n_iter=n_iter)
119
+
120
+ print(f"fig = {fig}")
121
+
122
+ return fig
123
+
124
+ # visualize coefficients
125
+
126
+ # # %%
127
+ # # Indeed, both models minimize the log-likelihood up to an arbitrary cutoff
128
+ # # defined by the `n_iter` parameter.
129
+ # #
130
+ # # Bayesian regressions with polynomial feature expansion
131
+ # # ======================================================
132
+ # Generate synthetic dataset
133
+ # --------------------------
134
+ # We create a target that is a non-linear function of the input feature.
135
+ # Noise following a standard uniform distribution is added.
136
+
137
+
138
+
139
+ rng = np.random.RandomState(0)
140
+ n_samples = 110
141
+
142
+ # sort the data to make plotting easier later
143
+ g_X = np.sort(-10 * rng.rand(n_samples) + 10)
144
+ noise = rng.normal(0, 1, n_samples) * 1.35
145
+ g_y = np.sqrt(g_X) * np.sin(g_X) + noise
146
+ full_data = pd.DataFrame({"input_feature": g_X, "target": g_y})
147
+ g_X = g_X.reshape((-1, 1))
148
+
149
+ # extrapolation
150
+ X_plot = np.linspace(10, 10.4, 10)
151
+ y_plot = np.sqrt(X_plot) * np.sin(X_plot)
152
+ X_plot = np.concatenate((g_X, X_plot.reshape((-1, 1))))
153
+ y_plot = np.concatenate((g_y - noise, y_plot))
154
+
155
+ # %%
156
+ # Fit the regressors
157
+ # ------------------
158
+ #
159
+ # Here we try a degree 10 polynomial to potentially overfit, though the bayesian
160
+ # linear models regularize the size of the polynomial coefficients. As
161
+ # `fit_intercept=True` by default for
162
+ # :class:`~sklearn.linear_model.ARDRegression` and
163
+ # :class:`~sklearn.linear_model.BayesianRidge`, then
164
+ # :class:`~sklearn.preprocessing.PolynomialFeatures` should not introduce an
165
+ # additional bias feature. By setting `return_std=True`, the bayesian regressors
166
+ # return the standard deviation of the posterior distribution for the model
167
+ # parameters.
168
+
169
+ #TODO - make this function that can be adapted with the gr.slider
170
+
171
+ def generate_polynomial_dataset(degree = 10):
172
+
173
+ ard_poly = make_pipeline(
174
+ PolynomialFeatures(degree=degree, include_bias=False),
175
+ StandardScaler(),
176
+ ARDRegression(),
177
+ ).fit(g_X, g_y)
178
+ brr_poly = make_pipeline(
179
+ PolynomialFeatures(degree=degree, include_bias=False),
180
+ StandardScaler(),
181
+ BayesianRidge(),
182
+ ).fit(g_X, g_y)
183
+
184
+ y_ard, y_ard_std = ard_poly.predict(X_plot, return_std=True)
185
+ y_brr, y_brr_std = brr_poly.predict(X_plot, return_std=True)
186
+
187
+ return y_ard, y_ard_std, y_brr, y_brr_std
188
+
189
+ # %%
190
+ # Plotting polynomial regressions with std errors of the scores
191
+ # -------------------------------------------------------------
192
+
193
+
194
+
195
+ def visualize_bayes_regressions_polynomial_features(degree = 10):
196
+
197
+ #TODO - get data dynamically from the gr.slider
198
+ y_ard, y_ard_std, y_brr, y_brr_std = generate_polynomial_dataset(degree)
199
+
200
+ fig = plt.figure(figsize=(10, 6))
201
+ ax = sns.scatterplot(
202
+ data=full_data, x="input_feature", y="target", color="black", alpha=0.75)
203
+ ax.plot(X_plot, y_plot, color="black", label="Ground Truth")
204
+ ax.plot(X_plot, y_brr, color="red", label="BayesianRidge with polynomial features")
205
+ ax.plot(X_plot, y_ard, color="navy", label="ARD with polynomial features")
206
+ ax.fill_between(
207
+ X_plot.ravel(),
208
+ y_ard - y_ard_std,
209
+ y_ard + y_ard_std,
210
+ color="navy",
211
+ alpha=0.3,
212
+ )
213
+ ax.fill_between(
214
+ X_plot.ravel(),
215
+ y_brr - y_brr_std,
216
+ y_brr + y_brr_std,
217
+ color="red",
218
+ alpha=0.3,
219
+ )
220
+ ax.legend()
221
+ _ = ax.set_title("Polynomial fit of a non-linear feature")
222
+ # print(f"ax = {ax}")
223
+ return fig
224
+
225
+
226
+ # def make_polynomial_comparison_plot():
227
+
228
+
229
+
230
+ # return fig
231
+
232
+
233
+
234
+
235
+
236
+ title = " Illustration of Comparing Linear Bayesian Regressors with synthetic data"
237
+ with gr.Blocks(title=title) as demo:
238
+ gr.Markdown(f"# {title}")
239
+ gr.Markdown(""" This example shows a comparison of two different bayesian regressors:
240
+ Automatic Relevance Determination - ARD see [sklearn-docs](https://scikit-learn.org/stable/modules/linear_model.html#automatic-relevance-determination)
241
+ Bayesian Ridge Regression - see [sklearn-docs](https://scikit-learn.org/stable/modules/linear_model.html#bayesian-ridge-regression)
242
+ The tutorial is split into sections, with the first comparing model coeffecients produced by Ordinary Least Squares (OLS), Bayesian Ridge Regression, and ARD with the known true coefficients. For this
243
+ We generated a dataset where X and y are linearly linked: 10 of the features of X will be used to generate y. The other features are not useful at predicting y.
244
+ n addition, we generate a dataset where n_samples == n_features. Such a setting is challenging for an OLS model and leads potentially to arbitrary large weights.
245
+ Having a prior on the weights and a penalty alleviates the problem. Finally, gaussian noise is added.
246
+
247
+ For the final tab, we investigate bayesian regressors with polynomial features and generate an additional dataset where the target is a non-linear function of the input feature, with
248
+ added noise following a standard uniform distribution.
249
+
250
+ For further details please see the sklearn docs:
251
+ """)
252
+
253
+ gr.Markdown(" **[Demo is based on sklearn docs found here](https://scikit-learn.org/stable/auto_examples/linear_model/plot_ard.html#sphx-glr-auto-examples-linear-model-plot-ard-py)** <br>")
254
+
255
+
256
+ with gr.Tab("# Plot true and estimated coefficients"):
257
+
258
+ with gr.Row():
259
+ n_iter = gr.Slider(value=5, minimum=5, maximum=50, step=1, label="n_iterations")
260
+ btn = gr.Button(value="Plot true and estimated coefficients")
261
+ btn.click(make_regression_comparison_plot, inputs = [n_iter], outputs= gr.Plot(label='Plot true and estimated coefficients') )
262
+ gr.Markdown(
263
+ """
264
+ # Details
265
+
266
+ One can observe that with the added noise, none of the models can perfectly recover the coefficients of the original model. All models have more thab 10 non-zero coefficients,
267
+ where only 10 are useful. The Bayesian Ridge Regression manages to recover most of the coefficients, while the ARD is more conservative.
268
+ """)
269
+ with gr.Tab("# Plot marginal log likelihoods"):
270
+ with gr.Row():
271
+ n_iter = gr.Slider(value=5, minimum=5, maximum=50, step=1, label="n_iterations")
272
+ btn = gr.Button(value="Plot marginal log likelihoods")
273
+ btn.click(make_log_likelihood_plot, inputs = [n_iter], outputs= gr.Plot(label='Plot marginal log likelihoods') )
274
+ gr.Markdown(
275
+ """
276
+ # Confirm with marginal log likelihoods
277
+ Both ARD and Bayesian Ridge minimized the log-likelihood upto an arbitrary cuttoff defined the the n_iter parameter.
278
+ """
279
+ )
280
+ with gr.Tab("# Plot bayesian regression with polynomial features"):
281
+ with gr.Row():
282
+ degree = gr.Slider(value=5, minimum=5, maximum=50, step=1, label="n_degrees")
283
+ btn = gr.Button(value="Plot bayesian regression with polynomial features")
284
+ btn.click(visualize_bayes_regressions_polynomial_features, inputs = [degree], outputs= gr.Plot(label='Plot bayesian regression with polynomial features') )
285
+ gr.Markdown(
286
+ """
287
+ # Details
288
+ Here we try a degree 10 polynomial to potentially overfit, though the bayesian linear models regularize the size of the polynomial coefficients.
289
+ As fit_intercept=True by default for ARDRegression and BayesianRidge, then PolynomialFeatures should not introduce an additional bias feature. By setting return_std=True,
290
+ the bayesian regressors return the standard deviation of the posterior distribution for the model parameters.
291
+
292
+ """)
293
+
294
+
295
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ scikit-learn==1.2.2
2
+ matplotlib==3.5.1
3
+ numpy==1.21.6
4
+ seaborn==0.11.2