Haleshot commited on
Commit
2d4a671
·
unverified ·
1 Parent(s): 157ee83

Add `logistic regression` notebook

Browse files
Files changed (1) hide show
  1. probability/21_logistic_regression.py +669 -0
probability/21_logistic_regression.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.4"
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 is a classification algorithm (I know, terrible name. Perhaps Logistic Classification would have been better) that works by trying to learn a function that approximates $P(y|x)$. 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!
77
+
78
+ Let's try to understand why:
79
+
80
+ To estimate $p$ using linear regression, we would need:
81
+ $$p = \beta_0 + \beta_1 \cdot x_{tumor\_size}$$
82
+
83
+ This doesn't seem to be feasible as the right side, in principle, belongs to $\mathbb{R}$ (any real number) & the left side belongs to $(0,1)$ (a probability).
84
+
85
+ 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!
86
+
87
+ 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}$.
88
+
89
+ Fortunately, such functions do exist and they are often referred to as link functions in this context.
90
+ """
91
+ )
92
+ return
93
+
94
+
95
+ @app.cell(hide_code=True)
96
+ def _(mo):
97
+ mo.md(
98
+ r"""
99
+ ## The Mathematical Foundation
100
+
101
+ Mathematically, for a single training datapoint $(\mathbf{x}, y)$ Logistic Regression assumes:
102
+
103
+ $$P(Y=1|\mathbf{X}=\mathbf{x}) = \sigma(z) \text{ where } z = \theta_0 + \sum_{i=1}^m \theta_i x_i$$
104
+
105
+ This assumption is often written in the equivalent forms:
106
+
107
+ $$P(Y=1|\mathbf{X}=\mathbf{x}) =\sigma(\mathbf{\theta}^T\mathbf{x}) \quad \text{ where we always set $x_0$ to be 1}$$
108
+
109
+ $$P(Y=0|\mathbf{X}=\mathbf{x}) =1-\sigma(\mathbf{\theta}^T\mathbf{x}) \quad \text{ by total law of probability}$$
110
+
111
+ Using these equations for probability of $Y|X$ we can create an algorithm that selects values of $\theta$ that maximize that probability for all data. I am first going to state the log probability function and partial derivatives with respect to $\theta$. Then later we will (a) show an algorithm that can chose optimal values of $\theta$ and (b) show how the equations were derived.
112
+
113
+ An important thing to realize is that: given the best values for the parameters ($\theta$), logistic regression often can do a great job of estimating the probability of different class labels. However, given bad, or even random, values of $\theta$ it does a poor job. The amount of "intelligence" that your logistic regression machine learning algorithm has is dependent on having good values of $\theta$.
114
+ """
115
+ )
116
+ return
117
+
118
+
119
+ @app.cell(hide_code=True)
120
+ def _(mo):
121
+ mo.md(
122
+ r"""
123
+ ### Logistic Regression Is A Linear Classifier
124
+
125
+ The logistic regression equation is actually a straight line (of the form $y = mx + c$).
126
+
127
+ Recall the prediction rule:
128
+ $$\text{predicted class} =
129
+ \begin{cases}
130
+ 1, & \text{if } p \geq \theta_0 + \theta_1 \cdot x_{tumor\_size} \Rightarrow \log\frac{p}{1-p} \\
131
+ 0, & \text{otherwise}
132
+ \end{cases}$$
133
+
134
+ A simple logistic regression (the one we discussed) 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.
135
+
136
+ Logistic regression works well for linearly separable classes.
137
+ """
138
+ )
139
+ return
140
+
141
+
142
+ @app.cell(hide_code=True)
143
+ def _(mo):
144
+ mo.md("""### Visual: Linear Separability and Classification""")
145
+ return
146
+
147
+
148
+ @app.cell(hide_code=True)
149
+ def _(mo, np, plt):
150
+ # show relevant comaparison to the above last sentence/statement
151
+
152
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
153
+
154
+ # Linear separable data
155
+ np.random.seed(42)
156
+ X1 = np.random.randn(100, 2) - 2
157
+ X2 = np.random.randn(100, 2) + 2
158
+
159
+ ax1.scatter(X1[:, 0], X1[:, 1], color='blue', alpha=0.5)
160
+ ax1.scatter(X2[:, 0], X2[:, 1], color='red', alpha=0.5)
161
+
162
+ # Decision boundary (line)
163
+ ax1.plot([-5, 5], [5, -5], 'k--', linewidth=2)
164
+ ax1.set_xlim(-5, 5)
165
+ ax1.set_ylim(-5, 5)
166
+ ax1.set_title('Linearly Separable Classes')
167
+
168
+ # non-linear separable data
169
+ radius = 2
170
+ theta = np.linspace(0, 2*np.pi, 100)
171
+
172
+ # Outer circle points (class 1)
173
+ outer_x = 3 * np.cos(theta)
174
+ outer_y = 3 * np.sin(theta)
175
+ # Inner circle points (class 2)
176
+ inner_x = 1.5 * np.cos(theta) + np.random.randn(100) * 0.2
177
+ inner_y = 1.5 * np.sin(theta) + np.random.randn(100) * 0.2
178
+
179
+ ax2.scatter(outer_x, outer_y, color='blue', alpha=0.5)
180
+ ax2.scatter(inner_x, inner_y, color='red', alpha=0.5)
181
+
182
+ # Attempt to draw a linear boundary (which won't work well) proving the point
183
+ ax2.plot([-5, 5], [2, 2], 'k--', linewidth=2)
184
+
185
+ ax2.set_xlim(-5, 5)
186
+ ax2.set_ylim(-5, 5)
187
+ ax2.set_title('Non-Linearly Separable Classes')
188
+
189
+ fig.tight_layout()
190
+ mo.mpl.interactive(fig)
191
+ return (
192
+ X1,
193
+ X2,
194
+ ax1,
195
+ ax2,
196
+ fig,
197
+ inner_x,
198
+ inner_y,
199
+ outer_x,
200
+ outer_y,
201
+ radius,
202
+ theta,
203
+ )
204
+
205
+
206
+ @app.cell(hide_code=True)
207
+ def _(mo):
208
+ 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.""")
209
+ return
210
+
211
+
212
+ @app.cell(hide_code=True)
213
+ def _(mo):
214
+ mo.md(
215
+ r"""
216
+ ## Notation
217
+
218
+ Before we get started I want to make sure that we are all on the same page with respect to notation. In logistic regression, $\theta$ is a vector of parameters of length $m$ and we are going to learn the values of those parameters based off of $n$ training examples. The number of parameters should be equal to the number of features of each datapoint.
219
+
220
+ Two pieces of notation that we use often in logistic regression that you may not be familiar with are:
221
+
222
+ $$\mathbf{\theta}^T\mathbf{x} = \sum_{i=1}^m \theta_i x_i = \theta_1 x_1 + \theta_2 x_2 + \dots + \theta_m x_m \quad \text{dot product, aka weighted sum}$$
223
+
224
+ $$\sigma(z) = \frac{1}{1+ e^{-z}} \quad \text{sigmoid function}$$
225
+
226
+ The sigmoid function is a special function that maps any real number to a probability between 0 and 1. It has an S-shaped curve and is particularly useful for binary classification problems.
227
+ """
228
+ )
229
+ return
230
+
231
+
232
+ @app.cell(hide_code=True)
233
+ def _(mo, np, plt):
234
+ # Plot the sigmoid function
235
+
236
+ _fig, ax = plt.subplots(figsize=(10, 6))
237
+
238
+ # Generate x values
239
+ x = np.linspace(-10, 10, 1000)
240
+
241
+ # Compute sigmoid
242
+ def sigmoid(z):
243
+ return 1 / (1 + np.exp(-z))
244
+
245
+ y = sigmoid(x)
246
+
247
+ # Plot sigmoid function
248
+ ax.plot(x, y, 'b-', linewidth=2)
249
+
250
+ # Add horizontal lines at y=0 and y=1
251
+ ax.axhline(y=0, color='k', linestyle='-', alpha=0.3)
252
+ ax.axhline(y=1, color='k', linestyle='-', alpha=0.3)
253
+ ax.axhline(y=0.5, color='r', linestyle='--', alpha=0.5)
254
+
255
+ # Add vertical line at x=0
256
+ ax.axvline(x=0, color='k', linestyle='-', alpha=0.3)
257
+
258
+ # Add annotations
259
+ ax.text(1, 0.85, r'$\sigma(z) = \frac{1}{1 + e^{-z}}$', fontsize=14)
260
+ ax.text(-9, 0.1, 'As z → -∞, σ(z) → 0', fontsize=12)
261
+ ax.text(3, 0.9, 'As z → ∞, σ(z) → 1', fontsize=12)
262
+ ax.text(0.5, 0.4, 'σ(0) = 0.5', fontsize=12)
263
+
264
+ # Set labels and title
265
+ ax.set_xlabel('z', fontsize=14)
266
+ ax.set_ylabel('σ(z)', fontsize=14)
267
+ ax.set_title('Sigmoid Function', fontsize=16)
268
+
269
+ # Set axis limits
270
+ ax.set_xlim(-10, 10)
271
+ ax.set_ylim(-0.1, 1.1)
272
+
273
+ # Add grid
274
+ ax.grid(True, alpha=0.3)
275
+
276
+ mo.mpl.interactive(_fig)
277
+
278
+ mo.md(r"""
279
+ **Figure**: The sigmoid function maps any real number to a value between 0 and 1, making it perfect for representing probabilities.
280
+
281
+ /// note
282
+ For more information about the sigmoid function and its applications in deep learning, 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.
283
+ ///
284
+ """)
285
+ return ax, sigmoid, x, y
286
+
287
+
288
+ @app.cell(hide_code=True)
289
+ def _(mo):
290
+ mo.md(
291
+ r"""
292
+ ## Log Likelihood
293
+
294
+ In order to choose values for the parameters of logistic regression we use Maximum Likelihood Estimation (MLE). As such we are going to have two steps: (1) write the log-likelihood function and (2) find the values of $\theta$ that maximize the log-likelihood function.
295
+
296
+ The labels that we are predicting are binary, and the output of our logistic regression function is supposed to be the probability that the label is one. This means that we can (and should) interpret each label as a Bernoulli random variable: $Y \sim \text{Bern}(p)$ where $p = \sigma(\theta^T \textbf{x})$.
297
+
298
+ To start, here is a super slick way of writing the probability of one datapoint (recall this is the equation form of the probability mass function of a Bernoulli):
299
+
300
+ $$P(Y=y | X = \mathbf{x}) = \sigma({\mathbf{\theta}^T\mathbf{x}})^y \cdot \left[1 - \sigma({\mathbf{\theta}^T\mathbf{x}})\right]^{(1-y)}$$
301
+
302
+ Now that we know the probability mass function, we can write the likelihood of all the data:
303
+
304
+ $$L(\theta) = \prod_{i=1}^n P(Y=y^{(i)} | X = \mathbf{x}^{(i)}) \quad \text{The likelihood of independent training labels}$$
305
+
306
+ $$= \prod_{i=1}^n \sigma({\mathbf{\theta}^T\mathbf{x}^{(i)}})^{y^{(i)}} \cdot \left[1 - \sigma({\mathbf{\theta}^T\mathbf{x}^{(i)}})\right]^{(1-y^{(i)})} \quad \text{Substituting the likelihood of a Bernoulli}$$
307
+
308
+ And if you take the log of this function, you get the reported Log Likelihood for Logistic Regression. The log likelihood equation is:
309
+
310
+ $$LL(\theta) = \sum_{i=1}^n y^{(i)} \log \sigma(\mathbf{\theta}^T\mathbf{x}^{(i)}) + (1-y^{(i)}) \log [1 - \sigma(\mathbf{\theta}^T\mathbf{x}^{(i)})]$$
311
+
312
+ Recall that in MLE the only remaining step is to choose parameters ($\theta$) that maximize log likelihood.
313
+ """
314
+ )
315
+ return
316
+
317
+
318
+ @app.cell(hide_code=True)
319
+ def _(mo):
320
+ mo.md(
321
+ r"""
322
+ ## Gradient of Log Likelihood
323
+
324
+ Now that we have a function for log-likelihood, we simply need to choose the values of $\theta$ that maximize it. We can find the best values of $\theta$ by using an optimization algorithm. However, in order to use an optimization algorithm, we first need to know the partial derivative of log likelihood with respect to each parameter. First I am going to give you the partial derivative (so you can see how it is used). Then I am going to show you how to derive it:
325
+
326
+ $$\frac{\partial LL(\theta)}{\partial \theta_j} = \sum_{i=1}^n \left[
327
+ y^{(i)} - \sigma(\mathbf{\theta}^T\mathbf{x}^{(i)})
328
+ \right] x_j^{(i)}$$
329
+
330
+ This is a beautifully simple formula. Notice that the gradient is the sum of the error terms $(y^{(i)} - \sigma(\mathbf{\theta}^T\mathbf{x}^{(i)}))$ multiplied by the feature value $x_j^{(i)}$. The _error term_ represents the _difference_ between the true label and our predicted probability.
331
+ """
332
+ )
333
+ return
334
+
335
+
336
+ @app.cell(hide_code=True)
337
+ def _(mo):
338
+ mo.md(
339
+ r"""
340
+ ## Gradient Descent Optimization
341
+
342
+ Our goal is to choose parameters ($\theta$) that maximize likelihood, and we know the partial derivative of log likelihood with respect to each parameter. We are ready for our optimization algorithm.
343
+
344
+ In the case of logistic regression, we can't solve for $\theta$ mathematically. Instead, we use a computer to chose $\theta$. To do so we employ an algorithm called gradient descent (a classic in optimization theory). The idea behind gradient descent is that if you continuously take small steps downhill (in the direction of your negative gradient), you will eventually make it to a local minima. In our case we want to maximize our likelihood. As you can imagine, minimizing a negative of our likelihood will be equivalent to maximizing our likelihood.
345
+
346
+ The update to our parameters that results in each small step can be calculated as:
347
+
348
+ $$\theta_j^{\text{ new}} = \theta_j^{\text{ old}} + \eta \cdot \frac{\partial LL(\theta^{\text{ old}})}{\partial \theta_j^{\text{ old}}}$$
349
+
350
+ $$= \theta_j^{\text{ old}} + \eta \cdot \sum_{i=1}^n \left[
351
+ y^{(i)} - \sigma(\mathbf{\theta}^T\mathbf{x}^{(i)})
352
+ \right] x_j^{(i)}$$
353
+
354
+ Where $\eta$ is the magnitude of the step size that we take. If you keep updating $\theta$ using the equation above you will converge on the best values of $\theta$. You now have an intelligent model. Here is the gradient ascent algorithm for logistic regression in pseudo-code:
355
+ """
356
+ )
357
+ return
358
+
359
+
360
+ @app.cell(hide_code=True)
361
+ def _(mo):
362
+ # Create a stylized pseudocode display
363
+ mo.md(r"""
364
+ ```
365
+ Initialize: θⱼ = 0 for all 0 ≤ j ≤ m
366
+
367
+ Repeat many times:
368
+ gradient[j] = 0 for all 0 ≤ j ≤ m
369
+
370
+ For each training example (x, y):
371
+ For each parameter j:
372
+ gradient[j] += xⱼ(y - 1/(1+e^(-θᵀx)))
373
+
374
+ θⱼ += η * gradient[j] for all 0 ≤ j ≤ m
375
+ ```
376
+
377
+ **Pro-tip:** Don't forget that in order to learn the value of θ₀ you can simply define x₀ to always be 1.
378
+ """)
379
+ return
380
+
381
+
382
+ @app.cell(hide_code=True)
383
+ def _(controls, mo, widget):
384
+ # create the layout
385
+ mo.vstack([
386
+ 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)_."),
387
+ controls,
388
+ widget
389
+ ])
390
+ return
391
+
392
+
393
+ @app.cell(hide_code=True)
394
+ def _(LogisticRegression, mo, np, plt, run_button, widget):
395
+ warning_msg = mo.md(""" /// warning
396
+ Need more data, please draw points of at least two different colors in the scatter widget
397
+ """)
398
+
399
+ # mo.stop if button isn't clicked yet
400
+ mo.stop(
401
+ not run_button.value,
402
+ mo.md(""" /// tip
403
+ click 'Run Logistic Regression' to see the model
404
+ """)
405
+ )
406
+
407
+ # get data from widget (can also use as_pandas)
408
+ df = widget.data_as_polars
409
+
410
+ # display appropriate warning
411
+ mo.stop(
412
+ df.is_empty() or df['color'].n_unique() < 2,
413
+ warning_msg
414
+ )
415
+
416
+ # extract features and labels
417
+ X = df[['x', 'y']].to_numpy()
418
+ y_colors = df['color'].to_numpy()
419
+
420
+ # fit logistic regression model
421
+ model = LogisticRegression()
422
+ model.fit(X, y_colors)
423
+
424
+ # create grid for the viz
425
+ x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
426
+ y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
427
+ xx, yy = np.meshgrid(
428
+ np.linspace(x_min, x_max, 100),
429
+ np.linspace(y_min, y_max, 100)
430
+ )
431
+
432
+ # get probability predictions
433
+ Z = model.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
434
+ Z = Z.reshape(xx.shape)
435
+
436
+ # create figure
437
+ _fig, ax_fig = plt.subplots(figsize=(12, 8))
438
+
439
+ # plot decision boundary (probability contours)
440
+ contour = ax_fig.contourf(
441
+ xx, yy, Z,
442
+ levels=np.linspace(0, 1, 11),
443
+ alpha=0.7,
444
+ cmap="RdBu_r"
445
+ )
446
+
447
+ # plot decision boundary line (probability = 0.5)
448
+ ax_fig.contour(
449
+ xx, yy, Z,
450
+ levels=[0.5],
451
+ colors='k',
452
+ linewidths=2
453
+ )
454
+
455
+ # plot the data points (use same colors as in the widget)
456
+ ax_fig.scatter(X[:, 0], X[:, 1], c=y_colors, edgecolor='k', s=80)
457
+
458
+ # colorbar
459
+ plt.colorbar(contour, ax=ax_fig)
460
+
461
+ # labels and title
462
+ ax_fig.set_xlabel('x')
463
+ ax_fig.set_ylabel('y')
464
+ ax_fig.set_title('Logistic Regression')
465
+
466
+ # model params
467
+ coef = model.coef_[0]
468
+ intercept = model.intercept_[0]
469
+ equation = f"log(p/(1-p)) = {intercept:.2f} + {coef[0]:.3f}x₁ + {coef[1]:.3f}x₂"
470
+
471
+ # relevant info in regards to regression
472
+ model_info = mo.md(f"""
473
+ ### Logistic regression model
474
+
475
+ **Equation**: {equation}
476
+
477
+ **Decision boundary**: probability = 0.5
478
+
479
+ **Accuracy**: {model.score(X, y_colors):.2f}
480
+ """)
481
+
482
+ # show results vertically stacked
483
+ mo.vstack([
484
+ mo.mpl.interactive(_fig),
485
+ model_info
486
+ ])
487
+ return (
488
+ X,
489
+ Z,
490
+ ax_fig,
491
+ coef,
492
+ contour,
493
+ df,
494
+ equation,
495
+ intercept,
496
+ model,
497
+ model_info,
498
+ warning_msg,
499
+ x_max,
500
+ x_min,
501
+ xx,
502
+ y_colors,
503
+ y_max,
504
+ y_min,
505
+ yy,
506
+ )
507
+
508
+
509
+ @app.cell(hide_code=True)
510
+ def _(mo):
511
+ mo.md(
512
+ r"""
513
+ ## Derivations
514
+
515
+ In this section we provide the mathematical derivations for the gradient of log-likelihood. The derivations are worth knowing because these ideas are heavily used in Artificial Neural Networks.
516
+
517
+ Our goal is to calculate the derivative of the log likelihood with respect to each theta. To start, here is the definition for the derivative of a sigmoid function with respect to its inputs:
518
+
519
+ $$\frac{\partial}{\partial z} \sigma(z) = \sigma(z)[1 - \sigma(z)] \quad \text{to get the derivative with respect to $\theta$, use the chain rule}$$
520
+
521
+ Take a moment and appreciate the beauty of the derivative of the sigmoid function. The reason that sigmoid has such a simple derivative stems from the natural exponent in the sigmoid denominator.
522
+ """
523
+ )
524
+ return
525
+
526
+
527
+ @app.cell(hide_code=True)
528
+ def _(mo):
529
+ mo.md(
530
+ r"""
531
+ ### Detailed Derivation
532
+
533
+ Since the likelihood function is a sum over all of the data, and in calculus the derivative of a sum is the sum of derivatives, we can focus on computing the derivative of one example. The gradient of theta is simply the sum of this term for each training datapoint.
534
+
535
+ First I am going to show you how to compute the derivative the hard way. Then we are going to look at an easier method. The derivative of gradient for one datapoint $(\mathbf{x}, y)$:
536
+
537
+ $$\begin{align}
538
+ \frac{\partial LL(\theta)}{\partial \theta_j} &= \frac{\partial }{\partial \theta_j} y \log \sigma(\mathbf{\theta}^T\mathbf{x}) + \frac{\partial }{\partial \theta_j} (1-y) \log [1 - \sigma(\mathbf{\theta}^T\mathbf{x})] \quad \text{derivative of sum of terms}\\
539
+ &=\left[\frac{y}{\sigma(\theta^T\mathbf{x})} - \frac{1-y}{1-\sigma(\theta^T\mathbf{x})} \right] \frac{\partial}{\partial \theta_j} \sigma(\theta^T \mathbf{x}) \quad \text{derivative of log $f(x)$}\\
540
+ &=\left[\frac{y}{\sigma(\theta^T\mathbf{x})} - \frac{1-y}{1-\sigma(\theta^T\mathbf{x})} \right] \sigma(\theta^T \mathbf{x}) [1 - \sigma(\theta^T \mathbf{x})]\mathbf{x}_j \quad \text{chain rule + derivative of sigma}\\
541
+ &=\left[
542
+ \frac{y - \sigma(\theta^T\mathbf{x})}{\sigma(\theta^T \mathbf{x}) [1 - \sigma(\theta^T \mathbf{x})]}
543
+ \right] \sigma(\theta^T \mathbf{x}) [1 - \sigma(\theta^T \mathbf{x})]\mathbf{x}_j \quad \text{algebraic manipulation}\\
544
+ &= \left[y - \sigma(\theta^T\mathbf{x}) \right] \mathbf{x}_j \quad \text{cancelling terms}
545
+ \end{align}$$
546
+ """
547
+ )
548
+ return
549
+
550
+
551
+ @app.cell(hide_code=True)
552
+ def _(mo):
553
+ mo.md(
554
+ r"""
555
+ ### Derivatives Without Tears
556
+
557
+ That was the hard way. Logistic regression is the building block of [Artificial Neural Networks](https://en.wikipedia.org/wiki/Neural_network_(machine_learning)). If we want to scale up, we are going to have to get used to an easier way of calculating derivatives. For that we are going to have to welcome back our old friend the chain rule. By the chain rule:
558
+
559
+ $$\begin{align}
560
+ \frac{\partial LL(\theta)}{\partial \theta_j} &=
561
+ \frac{\partial LL(\theta)}{\partial p}
562
+ \cdot \frac{\partial p}{\partial \theta_j}
563
+ \quad \text{Where } p = \sigma(\theta^T\textbf{x})\\
564
+ &=
565
+ \frac{\partial LL(\theta)}{\partial p}
566
+ \cdot \frac{\partial p}{\partial z}
567
+ \cdot \frac{\partial z}{\partial \theta_j}
568
+ \quad \text{Where } z = \theta^T\textbf{x}
569
+ \end{align}$$
570
+
571
+ Chain rule is the decomposition mechanism of calculus. It allows us to calculate a complicated partial derivative $\frac{\partial LL(\theta)}{\partial \theta_j}$ by breaking it down into smaller pieces.
572
+
573
+ $$\begin{align}
574
+ LL(\theta) &= y \log p + (1-y) \log (1 - p) \quad \text{Where } p = \sigma(\theta^T\textbf{x}) \\
575
+ \frac{\partial LL(\theta)}{\partial p} &= \frac{y}{p} - \frac{1-y}{1-p} \quad \text{By taking the derivative}
576
+ \end{align}$$
577
+
578
+ $$\begin{align}
579
+ p &= \sigma(z) \quad \text{Where }z = \theta^T\textbf{x}\\
580
+ \frac{\partial p}{\partial z} &= \sigma(z)[1- \sigma(z)] \quad \text{By taking the derivative of the sigmoid}
581
+ \end{align}$$
582
+
583
+ $$\begin{align}
584
+ z &= \theta^T\textbf{x} \quad \text{As previously defined}\\
585
+ \frac{\partial z}{\partial \theta_j} &= \textbf{x}_j \quad \text{ Only $\textbf{x}_j$ interacts with $\theta_j$}
586
+ \end{align}$$
587
+
588
+ Each of those derivatives was much easier to calculate. Now we simply multiply them together.
589
+
590
+ $$\begin{align}
591
+ \frac{\partial LL(\theta)}{\partial \theta_j} &=
592
+ \frac{\partial LL(\theta)}{\partial p}
593
+ \cdot \frac{\partial p}{\partial z}
594
+ \cdot \frac{\partial z}{\partial \theta_j} \\
595
+ &=
596
+ \Big[\frac{y}{p} - \frac{1-y}{1-p}\Big]
597
+ \cdot \sigma(z)[1- \sigma(z)]
598
+ \cdot \textbf{x}_j \quad \text{By substituting in for each term} \\
599
+ &=
600
+ \Big[\frac{y}{p} - \frac{1-y}{1-p}\Big]
601
+ \cdot p[1- p]
602
+ \cdot \textbf{x}_j \quad \text{Since }p = \sigma(z)\\
603
+ &=
604
+ [y(1-p) - p(1-y)]
605
+ \cdot \textbf{x}_j \quad \text{Multiplying in} \\
606
+ &= [y - p]\textbf{x}_j \quad \text{Expanding} \\
607
+ &= [y - \sigma(\theta^T\textbf{x})]\textbf{x}_j \quad \text{Since } p = \sigma(\theta^T\textbf{x})
608
+ \end{align}$$
609
+ """
610
+ )
611
+ return
612
+
613
+
614
+ @app.cell(hide_code=True)
615
+ def _(mo):
616
+ mo.md(
617
+ r"""
618
+ Additional resources referred to:
619
+
620
+ - [Logistic Regression Tutorial by _Koushik Khan_](https://koushikkhan.github.io/resources/pdf/tutorials/logistic_regression_tutorial.pdf)
621
+ """
622
+ )
623
+ return
624
+
625
+
626
+ @app.cell(hide_code=True)
627
+ def _(mo):
628
+ mo.md(r"""Appendix (helper code)""")
629
+ return
630
+
631
+
632
+ @app.cell
633
+ def _():
634
+ import marimo as mo
635
+ return (mo,)
636
+
637
+
638
+ @app.cell
639
+ def init_imports():
640
+ # imports for our notebook
641
+ import numpy as np
642
+ import matplotlib.pyplot as plt
643
+ from drawdata import ScatterWidget
644
+ from sklearn.linear_model import LogisticRegression
645
+
646
+
647
+ # for consistent results
648
+ np.random.seed(42)
649
+
650
+ # nicer plots
651
+ plt.style.use('seaborn-v0_8-darkgrid')
652
+ return LogisticRegression, ScatterWidget, np, plt
653
+
654
+
655
+ @app.cell(hide_code=True)
656
+ def _(ScatterWidget, mo):
657
+ # drawing widget
658
+ widget = mo.ui.anywidget(ScatterWidget())
659
+
660
+ # run_button to run model
661
+ run_button = mo.ui.run_button(label="Run Logistic Regression", kind="success")
662
+
663
+ # stack controls
664
+ controls = mo.hstack([run_button])
665
+ return controls, run_button, widget
666
+
667
+
668
+ if __name__ == "__main__":
669
+ app.run()