Akshay Agrawal commited on
Commit
1d55e13
·
unverified ·
2 Parent(s): 157ee83 7497033

Merge pull request #90 from marimo-team/haleshot/21_logistic_regression

Browse files
Files changed (1) hide show
  1. probability/21_logistic_regression.py +530 -0
probability/21_logistic_regression.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "marimo",
5
+ # "matplotlib==3.10.1",
6
+ # "numpy==2.2.4",
7
+ # "drawdata==0.3.7",
8
+ # "scikit-learn==1.6.1",
9
+ # "polars==1.26.0",
10
+ # ]
11
+ # ///
12
+
13
+ import marimo
14
+
15
+ __generated_with = "0.12.5"
16
+ app = marimo.App(width="medium", app_title="Logistic Regression")
17
+
18
+
19
+ @app.cell(hide_code=True)
20
+ def _(mo):
21
+ mo.md(
22
+ r"""
23
+ # Logistic Regression
24
+
25
+ _This notebook is a computational companion to ["Probability for Computer Scientists"](https://chrispiech.github.io/probabilityForComputerScientists/en/part5/log_regression/), by Stanford professor Chris Piech._
26
+
27
+ Logistic regression learns a function approximating $P(y|x)$, and can be used to make a classifier. It makes the central assumption that $P(y|x)$ can be approximated as a sigmoid function applied to a linear combination of input features. It is particularly important to learn because logistic regression is the basic building block of artificial neural networks.
28
+ """
29
+ )
30
+ return
31
+
32
+
33
+ @app.cell(hide_code=True)
34
+ def _(mo):
35
+ mo.md(
36
+ r"""
37
+ ## The Binary Classification Problem
38
+
39
+ Imagine situations where we would like to know:
40
+
41
+ - The eligibility of getting a bank loan given the value of credit score ($x_{credit\_score}$) and monthly income ($x_{income}$)
42
+ - Identifying a tumor as benign or malignant given its size ($x_{tumor\_size}$)
43
+ - Classifying an email as promotional given the number of occurrences for some keywords like {'win', 'gift', 'discount'} ($x_{n\_win}$, $x_{n\_gift}$, $x_{n\_discount}$)
44
+ - Finding a monetary transaction as fraudulent given the time of occurrence ($x_{time\_stamp}$) and amount ($x_{amount}$)
45
+
46
+ These problems occur frequently in real life & can be dealt with machine learning. All such problems come under the umbrella of what is known as Classification. In each scenario, only one of the two possible outcomes can occur, hence these are specifically known as Binary Classification problems.
47
+
48
+ ### How Does A Machine Perform Classification?
49
+
50
+ During the inference, the goal is to have the ML model predict the class label for a given set of feature values.
51
+
52
+ Specifically, a binary classification model estimates two probabilities $p_0$ & $p_1$ for 'class-0' and 'class-1' respectively where $p_0 + p_1 = 1$.
53
+
54
+ The predicted label depends on $\max(p_0, p_1)$ i.e., it's the one which is most probable based on the given features.
55
+
56
+ In logistic regression, $p_1$ (i.e., success probability) is compared with a predefined threshold $p$ to predict the class label like below:
57
+
58
+ $$\text{predicted class} =
59
+ \begin{cases}
60
+ 1, & \text{if } p_1 \geq p \\
61
+ 0, & \text{otherwise}
62
+ \end{cases}$$
63
+
64
+ To keep the notation simple and consistent, we will denote the success probability as $p$, and failure probability as $(1-p)$ instead of $p_1$ and $p_0$ respectively.
65
+ """
66
+ )
67
+ return
68
+
69
+
70
+ @app.cell(hide_code=True)
71
+ def _(mo):
72
+ mo.md(
73
+ r"""
74
+ ## Why NOT Linear Regression?
75
+
76
+ Can't we really use linear regression to address classification? The answer is NO! The key issue is that probabilities must be between 0 and 1 and linear regression can output any real number.
77
+
78
+ If we tried using linear regression directly:
79
+ $$p = \beta_0 + \beta_1 \cdot x_{feature}$$
80
+
81
+ This creates a problem: the right side can produce any value in $\mathbb{R}$ (all real numbers), but a probability $p$ must be confined to the range $(0,1)$.
82
+
83
+ Can we convert $(\beta_0 + \beta_1 \cdot x_{tumor\_size})$ to something belonging to $(0,1)$? That may work as an estimate of a probability! The answer is YES!
84
+
85
+ We need a converter (a function), say, $g()$ that will connect $p \in (0,1)$ to $(\beta_0 + \beta_1 \cdot x_{tumor\_size}) \in \mathbb{R}$.
86
+
87
+ The solution is to use a "link function" that maps from any real number to a valid probability range. This is where the sigmoid function comes in.
88
+ """
89
+ )
90
+ return
91
+
92
+
93
+ @app.cell(hide_code=True)
94
+ def _(mo, np, plt):
95
+ # plot sigmoid to evidentiate above statements
96
+ _fig, ax = plt.subplots(figsize=(10, 6))
97
+
98
+ # x values
99
+ x = np.linspace(-10, 10, 1000)
100
+
101
+ # sigmoid formula
102
+ def sigmoid(z):
103
+ return 1 / (1 + np.exp(-z))
104
+
105
+ y = sigmoid(x)
106
+
107
+ # plot
108
+ ax.plot(x, y, 'b-', linewidth=2)
109
+
110
+ ax.axhline(y=0, color='k', linestyle='-', alpha=0.3)
111
+ ax.axhline(y=1, color='k', linestyle='-', alpha=0.3)
112
+ ax.axhline(y=0.5, color='r', linestyle='--', alpha=0.5)
113
+
114
+ # vertical line at x=0
115
+ ax.axvline(x=0, color='k', linestyle='-', alpha=0.3)
116
+
117
+ # annotations
118
+ ax.text(1, 0.85, r'$\sigma(z) = \frac{1}{1 + e^{-z}}$', fontsize=14)
119
+ ax.text(-9, 0.1, 'As z → -∞, σ(z) → 0', fontsize=12)
120
+ ax.text(3, 0.9, 'As z → ∞, σ(z) → 1', fontsize=12)
121
+ ax.text(0.5, 0.4, 'σ(0) = 0.5', fontsize=12)
122
+
123
+ # labels and title
124
+ ax.set_xlabel('z', fontsize=14)
125
+ ax.set_ylabel('σ(z)', fontsize=14)
126
+ ax.set_title('Sigmoid Function', fontsize=16)
127
+
128
+ # axis limits set
129
+ ax.set_xlim(-10, 10)
130
+ ax.set_ylim(-0.1, 1.1)
131
+
132
+ # grid
133
+ ax.grid(True, alpha=0.3)
134
+
135
+ mo.mpl.interactive(_fig)
136
+ return ax, sigmoid, x, y
137
+
138
+
139
+ @app.cell(hide_code=True)
140
+ def _(mo):
141
+ mo.md(
142
+ r"""
143
+ **Figure**: The sigmoid function maps any real number to a value between 0 and 1, making it perfect for representing probabilities.
144
+
145
+ /// note
146
+ For more information about the sigmoid function, head over to [this detailed notebook](http://marimo.app/https://github.com/marimo-team/deepml-notebooks/blob/main/problems/problem-22/notebook.py) for more insights.
147
+ ///
148
+ """
149
+ )
150
+ return
151
+
152
+
153
+ @app.cell(hide_code=True)
154
+ def _(mo):
155
+ mo.md(
156
+ r"""
157
+ ## The Core Concept (math)
158
+
159
+ Logistic regression models the probability of class 1 using the sigmoid function:
160
+
161
+ $$P(Y=1|X=x) = \sigma(z) \text{ where } z = \theta_0 + \sum_{i=1}^m \theta_i x_i$$
162
+
163
+ The sigmoid function $\sigma(z)$ transforms any real number into a probability between 0 and 1:
164
+
165
+ $$\sigma(z) = \frac{1}{1+ e^{-z}}$$
166
+
167
+ This can be written more compactly using vector notation:
168
+
169
+ $$P(Y=1|\mathbf{X}=\mathbf{x}) =\sigma(\mathbf{\theta}^T\mathbf{x}) \quad \text{ where we always set $x_0$ to be 1}$$
170
+
171
+ $$P(Y=0|\mathbf{X}=\mathbf{x}) =1-\sigma(\mathbf{\theta}^T\mathbf{x}) \quad \text{ by total law of probability}$$
172
+
173
+ Where $\theta$ represents the model parameters that need to be learned from data, and $x$ is the feature vector (with $x_0=1$ to account for the intercept term).
174
+
175
+ > **Note:** For the detailed mathematical derivation of how these parameters are learned through Maximum Likelihood Estimation (MLE) and Gradient Descent (GD), please refer to [Chris Piech's original material](https://chrispiech.github.io/probabilityForComputerScientists/en/part5/log_regression/). The mathematical details are elegant but beyond the scope of this notebook topic (which is confined to Logistic Regression).
176
+ """
177
+ )
178
+ return
179
+
180
+
181
+ @app.cell(hide_code=True)
182
+ def _(mo):
183
+ mo.md(
184
+ r"""
185
+ ### Linear Decision Boundary
186
+
187
+ A key characteristic of logistic regression is that it creates a linear decision boundary. When the model predicts, it's effectively dividing the feature space with a straight line (in 2D) or hyperplane (in higher dimensions). It is actually a straight line (of the form $y = mx + c$).
188
+
189
+ Recall the prediction rule:
190
+ $$\text{predicted class} =
191
+ \begin{cases}
192
+ 1, & \text{if } p \geq \theta_0 + \theta_1 \cdot x_{tumor\_size} \Rightarrow \log\frac{p}{1-p} \\
193
+ 0, & \text{otherwise}
194
+ \end{cases}$$
195
+
196
+ For a two-feature model, the decision boundary where $P(Y=1|X=x) = 0.5$ occurs at:
197
+ $$\theta_0 + \theta_1 x_1 + \theta_2 x_2 = 0$$
198
+
199
+ A simple logistic regression predicts the class label by identifying the regions on either side of a straight line (or hyperplane in general), hence it's a _linear_ classifier.
200
+
201
+ This linear nature makes logistic regression effective for linearly separable classes but limited when dealing with more complex patterns.
202
+ """
203
+ )
204
+ return
205
+
206
+
207
+ @app.cell(hide_code=True)
208
+ def _(mo):
209
+ mo.md("""### Visual: Linear Separability and Classification""")
210
+ return
211
+
212
+
213
+ @app.cell(hide_code=True)
214
+ def _(mo, np, plt):
215
+ # show relevant comparison to the above concepts/statements
216
+
217
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
218
+
219
+ # Linear separable data
220
+ np.random.seed(42)
221
+ X1 = np.random.randn(100, 2) - 2
222
+ X2 = np.random.randn(100, 2) + 2
223
+
224
+ ax1.scatter(X1[:, 0], X1[:, 1], color='blue', alpha=0.5)
225
+ ax1.scatter(X2[:, 0], X2[:, 1], color='red', alpha=0.5)
226
+
227
+ # Decision boundary (line)
228
+ ax1.plot([-5, 5], [5, -5], 'k--', linewidth=2)
229
+ ax1.set_xlim(-5, 5)
230
+ ax1.set_ylim(-5, 5)
231
+ ax1.set_title('Linearly Separable Classes')
232
+
233
+ # non-linear separable data
234
+ radius = 2
235
+ theta = np.linspace(0, 2*np.pi, 100)
236
+
237
+ # Outer circle points (class 1)
238
+ outer_x = 3 * np.cos(theta)
239
+ outer_y = 3 * np.sin(theta)
240
+ # Inner circle points (class 2)
241
+ inner_x = 1.5 * np.cos(theta) + np.random.randn(100) * 0.2
242
+ inner_y = 1.5 * np.sin(theta) + np.random.randn(100) * 0.2
243
+
244
+ ax2.scatter(outer_x, outer_y, color='blue', alpha=0.5)
245
+ ax2.scatter(inner_x, inner_y, color='red', alpha=0.5)
246
+
247
+ # Attempt to draw a linear boundary (which won't work well) proving the point
248
+ ax2.plot([-5, 5], [2, 2], 'k--', linewidth=2)
249
+
250
+ ax2.set_xlim(-5, 5)
251
+ ax2.set_ylim(-5, 5)
252
+ ax2.set_title('Non-Linearly Separable Classes')
253
+
254
+ fig.tight_layout()
255
+ mo.mpl.interactive(fig)
256
+ return (
257
+ X1,
258
+ X2,
259
+ ax1,
260
+ ax2,
261
+ fig,
262
+ inner_x,
263
+ inner_y,
264
+ outer_x,
265
+ outer_y,
266
+ radius,
267
+ theta,
268
+ )
269
+
270
+
271
+ @app.cell(hide_code=True)
272
+ def _(mo):
273
+ mo.md(r"""**Figure**: On the left, the classes are linearly separable as the boundary is a straight line. However, they are not linearly separable on the right, where no straight line can properly separate the two classes.""")
274
+ return
275
+
276
+
277
+ @app.cell(hide_code=True)
278
+ def _(mo):
279
+ mo.md(
280
+ r"""
281
+ Logistic regression is typically trained using MLE - finding the parameters $\theta$ that make our observed data most probable.
282
+
283
+ The optimization process generally uses GD (or its variants) to iteratively improve the parameters. The gradient has a surprisingly elegant form:
284
+
285
+ $$\frac{\partial LL(\theta)}{\partial \theta_j} = \sum_{i=1}^n \left[
286
+ y^{(i)} - \sigma(\theta^T x^{(i)})
287
+ \right] x_j^{(i)}$$
288
+
289
+ This shows that the update to each parameter depends on the prediction error (actual - predicted) multiplied by the feature value.
290
+
291
+ For those interested in the complete mathematical derivation, including log likelihood calculation and the detailed steps of GD (and relevant pseudocode followed for training), please see the [original lecture notes](https://chrispiech.github.io/probabilityForComputerScientists/en/part5/log_regression/).
292
+ """
293
+ )
294
+ return
295
+
296
+
297
+ @app.cell(hide_code=True)
298
+ def _(controls, mo, widget):
299
+ # create the layout
300
+ mo.vstack([
301
+ mo.md("## Interactive drawing demo\nDraw points of two different classes and see how logistic regression separates them. _The interactive demo was adapted and improvised from [Vincent Warmerdam's](https://github.com/koaning) code [here](https://github.com/probabl-ai/youtube-appendix/blob/main/04-drawing-data/notebook.ipynb)_."),
302
+ controls,
303
+ widget
304
+ ])
305
+ return
306
+
307
+
308
+ @app.cell(hide_code=True)
309
+ def _(LogisticRegression, mo, np, plt, run_button, widget):
310
+ warning_msg = mo.md(""" /// warning
311
+ Need more data, please draw points of at least two different colors in the scatter widget
312
+ """)
313
+
314
+ # mo.stop if button isn't clicked yet
315
+ mo.stop(
316
+ not run_button.value,
317
+ mo.md(""" /// tip
318
+ click 'Run Logistic Regression' to see the model
319
+ """)
320
+ )
321
+
322
+ # get data from widget (can also use as_pandas)
323
+ df = widget.data_as_polars
324
+
325
+ # display appropriate warning
326
+ mo.stop(
327
+ df.is_empty() or df['color'].n_unique() < 2,
328
+ warning_msg
329
+ )
330
+
331
+ # extract features and labels
332
+ X = df[['x', 'y']].to_numpy()
333
+ y_colors = df['color'].to_numpy()
334
+
335
+ # fit logistic regression model
336
+ model = LogisticRegression()
337
+ model.fit(X, y_colors)
338
+
339
+ # create grid for the viz
340
+ x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
341
+ y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
342
+ xx, yy = np.meshgrid(
343
+ np.linspace(x_min, x_max, 100),
344
+ np.linspace(y_min, y_max, 100)
345
+ )
346
+
347
+ # get probability predictions
348
+ Z = model.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
349
+ Z = Z.reshape(xx.shape)
350
+
351
+ # create figure
352
+ _fig, ax_fig = plt.subplots(figsize=(12, 8))
353
+
354
+ # plot decision boundary (probability contours)
355
+ contour = ax_fig.contourf(
356
+ xx, yy, Z,
357
+ levels=np.linspace(0, 1, 11),
358
+ alpha=0.7,
359
+ cmap="RdBu_r"
360
+ )
361
+
362
+ # plot decision boundary line (probability = 0.5)
363
+ ax_fig.contour(
364
+ xx, yy, Z,
365
+ levels=[0.5],
366
+ colors='k',
367
+ linewidths=2
368
+ )
369
+
370
+ # plot the data points (use same colors as in the widget)
371
+ ax_fig.scatter(X[:, 0], X[:, 1], c=y_colors, edgecolor='k', s=80)
372
+
373
+ # colorbar
374
+ plt.colorbar(contour, ax=ax_fig)
375
+
376
+ # labels and title
377
+ ax_fig.set_xlabel('x')
378
+ ax_fig.set_ylabel('y')
379
+ ax_fig.set_title('Logistic Regression')
380
+
381
+ # model params
382
+ coef = model.coef_[0]
383
+ intercept = model.intercept_[0]
384
+ equation = f"log(p/(1-p)) = {intercept:.2f} + {coef[0]:.3f}x₁ + {coef[1]:.3f}x₂"
385
+
386
+ # relevant info in regards to regression
387
+ model_info = mo.md(f"""
388
+ ### Logistic regression model
389
+
390
+ **Equation**: {equation}
391
+
392
+ **Decision boundary**: probability = 0.5
393
+
394
+ **Accuracy**: {model.score(X, y_colors):.2f}
395
+ """)
396
+
397
+ # show results vertically stacked
398
+ mo.vstack([
399
+ mo.mpl.interactive(_fig),
400
+ model_info
401
+ ])
402
+ return (
403
+ X,
404
+ Z,
405
+ ax_fig,
406
+ coef,
407
+ contour,
408
+ df,
409
+ equation,
410
+ intercept,
411
+ model,
412
+ model_info,
413
+ warning_msg,
414
+ x_max,
415
+ x_min,
416
+ xx,
417
+ y_colors,
418
+ y_max,
419
+ y_min,
420
+ yy,
421
+ )
422
+
423
+
424
+ @app.cell(hide_code=True)
425
+ def _(mo):
426
+ mo.md(
427
+ r"""
428
+ ## 🤔 Key Takeaways
429
+
430
+ Click on the statements below that you think are correct to verify your understanding:
431
+
432
+ /// details | Logistic regression tries to find parameters (θ) that minimize the error between predicted and actual values using ordinary least squares.
433
+ ❌ **Incorrect.** Logistic regression uses maximum likelihood estimation (MLE), not ordinary least squares. It finds parameters that maximize the probability of observing the training data, which is different from minimizing squared errors as in linear regression.
434
+ ///
435
+
436
+ /// details | The sigmoid function maps any real number to a value between 0 and 1, which allows logistic regression to output probabilities.
437
+ ✅ **Correct!** The sigmoid function σ(z) = 1/(1+e^(-z)) takes any real number as input and outputs a value between 0 and 1. This is perfect for representing probabilities and is a key component of logistic regression.
438
+ ///
439
+
440
+ /// details | The decision boundary in logistic regression is always a straight line, regardless of the data's complexity.
441
+ ✅ **Correct!** Standard logistic regression produces a linear decision boundary (a straight line in 2D or a hyperplane in higher dimensions). This is why it works well for linearly separable data but struggles with more complex patterns, like concentric circles (as you might've noticed from the interactive demo).
442
+ ///
443
+
444
+ /// details | The logistic regression model params are typically initialized to random values and refined through gradient descent.
445
+ ✅ **Correct!** Parameters are often initialized to zeros or small random values, then updated iteratively using gradient descent (or ascent for maximizing likelihood) until convergence.
446
+ ///
447
+
448
+ /// details | Logistic regression can naturally handle multi-class classification problems without any modifications.
449
+ ❌ **Incorrect.** Standard logistic regression is inherently a binary classifier. To handle multi-class classification, techniques like one-vs-rest or softmax regression are typically used.
450
+ ///
451
+ """
452
+ )
453
+ return
454
+
455
+
456
+ @app.cell(hide_code=True)
457
+ def _(mo):
458
+ mo.md(
459
+ r"""
460
+ ## Summary
461
+
462
+ So we've just explored logistic regression. Despite its name (seriously though, why not call it "logistic classification"?), it's actually quite elegant in how it transforms a simple linear model into a powerful decision _boundary_ maker.
463
+
464
+ The training process boils down to finding the values of θ that maximize the likelihood of seeing our training data. What's super cool is that even though the math looks _scary_ at first, the gradient has this surprisingly simple form: just the error (y - predicted) multiplied by the feature values.
465
+
466
+ Two key insights to remember:
467
+
468
+ - Logistic regression creates a _linear_ decision boundary, so it works great for linearly separable classes but struggles with more _complex_ patterns
469
+ - It directly gives you probabilities, not just classifications, which is incredibly useful when you need confidence measures
470
+ """
471
+ )
472
+ return
473
+
474
+
475
+ @app.cell(hide_code=True)
476
+ def _(mo):
477
+ mo.md(
478
+ r"""
479
+ Additional resources referred to:
480
+
481
+ - [Logistic Regression Tutorial by _Koushik Khan_](https://koushikkhan.github.io/resources/pdf/tutorials/logistic_regression_tutorial.pdf)
482
+ """
483
+ )
484
+ return
485
+
486
+
487
+ @app.cell(hide_code=True)
488
+ def _(mo):
489
+ mo.md(r"""Appendix (helper code)""")
490
+ return
491
+
492
+
493
+ @app.cell
494
+ def _():
495
+ import marimo as mo
496
+ return (mo,)
497
+
498
+
499
+ @app.cell
500
+ def init_imports():
501
+ # imports for our notebook
502
+ import numpy as np
503
+ import matplotlib.pyplot as plt
504
+ from drawdata import ScatterWidget
505
+ from sklearn.linear_model import LogisticRegression
506
+
507
+
508
+ # for consistent results
509
+ np.random.seed(42)
510
+
511
+ # nicer plots
512
+ plt.style.use('seaborn-v0_8-darkgrid')
513
+ return LogisticRegression, ScatterWidget, np, plt
514
+
515
+
516
+ @app.cell(hide_code=True)
517
+ def _(ScatterWidget, mo):
518
+ # drawing widget
519
+ widget = mo.ui.anywidget(ScatterWidget())
520
+
521
+ # run_button to run model
522
+ run_button = mo.ui.run_button(label="Run Logistic Regression", kind="success")
523
+
524
+ # stack controls
525
+ controls = mo.hstack([run_button])
526
+ return controls, run_button, widget
527
+
528
+
529
+ if __name__ == "__main__":
530
+ app.run()