gobalkrishnan commited on
Commit
9de340d
·
1 Parent(s): ad1a3b2
Files changed (3) hide show
  1. src/ols/ols.png +0 -0
  2. src/ols/ols.qmd +0 -364
  3. src/ols/style.css +0 -8
src/ols/ols.png DELETED
Binary file (392 kB)
 
src/ols/ols.qmd DELETED
@@ -1,364 +0,0 @@
1
- ---
2
- title: "Ordinary Least Squares (OLS)"
3
- author: "gobalkrishnan.books@gmail.com"
4
- format:
5
- html:
6
- css: styles.css
7
- revealjs:
8
- css: styles.css
9
- fontsize: 22pt
10
- ---
11
-
12
- ### Ostriches Leap Silly
13
-
14
- <div style="text-align: center; height: auto; border-radius: 15px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5); ">
15
- ![](ols.png)
16
- </div>
17
-
18
- # Overview
19
-
20
- - **Introduction**: Ordinary Least Squares (OLS) is a method used in statistics to find the best-fitting line for a set of points on a graph. This helps us see how two things are related, like how the amount of sunlight affects plant growth.
21
-
22
- # Definition
23
-
24
- - OLS is a statistical technique that identifies the straight line that best represents the relationship between two variables by minimizing the total distance (error) between the points and the line.
25
-
26
- # Formula
27
-
28
- The main formula for OLS can be expressed as:
29
-
30
- $$
31
- \hat{Y} = \beta_0 + \beta_1X
32
- $$
33
-
34
- Where:
35
-
36
- - $\hat{Y}$ = Predicted value (what we think will happen)
37
-
38
- - $\beta_0$ = Intercept (where the line crosses the Y-axis)
39
-
40
- - $\beta_1$ = Slope (how much $\hat{Y}$ changes for each change in $X$)
41
-
42
- - $X$ = Input variable (the value we have, like the amount of sunlight)
43
-
44
- # Explanation of Parameters
45
-
46
- - **$\hat{Y}$**: The predicted value, like how tall a plant might grow with a certain amount of sunlight.
47
- - **$\beta_0$**: The starting point of the line, like the height of a plant if it gets no sunlight.
48
- - **$\beta_1$**: The slope, indicating how much the plant height increases with each additional hour of sunlight.
49
- - **$X$**: The variable we change, like the number of hours of sunlight.
50
-
51
- # Advantages
52
-
53
- - **Simple to Understand**: It uses basic math that is easy to follow.
54
- - **Good for Predictions**: Helps us estimate future outcomes based on existing data.
55
- - **Works with Many Points**: Can analyze data from multiple observations easily.
56
-
57
- # Properties
58
-
59
- - **Linear Relationship**: Assumes that the relationship between the variables is a straight line.
60
- - **Minimizes Error**: Aims to minimize the distance between actual points and the fitted line.
61
- - **Uses All Data**: Considers all data points to find the best fit.
62
-
63
-
64
- # Pros and Cons
65
-
66
- | Pros | Cons |
67
- |-------------------------------------|-------------------------------------------|
68
- | Easy to use and understand | Only works well if the data is linear |
69
- | Provides clear results | Sensitive to outliers (unusual data points) |
70
- | Fast to calculate | May not fit complex data patterns well |
71
-
72
-
73
-
74
- # Step-by-Step Calculation
75
-
76
- 1. **Step 1**: Collect data about the relationship between two variables (e.g., hours of sunlight and plant height).
77
- 2. **Step 2**: Organize the data in a table format.
78
- 3. **Step 3**: Use the OLS formula to calculate the slope ($\beta_1$) and intercept ($\beta_0$).
79
- 4. **Step 4**: Use the equation to make predictions for new values.
80
-
81
- ---
82
-
83
- ## Example Problem
84
-
85
- - **Problem Statement**: If we have data on how many hours of sunlight plants receive and how tall they grow, can we predict how tall a plant will grow with 8 hours of sunlight?
86
-
87
-
88
- ### Given Data
89
-
90
- | Sunlight (hours) | Height (cm) |
91
- |------------------|-------------|
92
- | 2 | 20 |
93
- | 4 | 30 |
94
- | 6 | 40 |
95
- | 8 | 50 |
96
- | 10 | 60 |
97
-
98
-
99
-
100
- # Calculation Steps
101
-
102
- 1. **Step 1**: Use the data in the table.
103
- 2. **Step 2**: Calculate necessary values like sums, mean, and the slope ($\beta_1$) and intercept ($\beta_0$) using the OLS formulas.
104
- 3. **Step 3**: Use the OLS line to find the predicted height for 8 hours of sunlight.
105
-
106
- ---
107
-
108
- #### Solution
109
-
110
- 1. **Calculate sums**:
111
- - $n = 5$ (number of data points)
112
- - $\sum{X} = 2 + 4 + 6 + 8 + 10 = 30$
113
- - $\sum{Y} = 20 + 30 + 40 + 50 + 60 = 200$
114
- - $\sum{XY} = (2 \cdot 20) + (4 \cdot 30) + (6 \cdot 40) + (8 \cdot 50) + (10 \cdot 60) = 40 + 120 + 240 + 400 + 600 = 1400$
115
- - $\sum{X^2} = 2^2 + 4^2 + 6^2 + 8^2 + 10^2 = 4 + 16 + 36 + 64 + 100 = 220$
116
-
117
-
118
- 2. **Calculate slope ($\beta_1$)**:
119
- $$
120
- \beta_1 = \frac{n(\sum{XY}) - (\sum{X})(\sum{Y})}{n(\sum{X^2}) - (\sum{X})^2} = \frac{5(1400) - (30)(200)}{5(220) - (30)^2} = \frac{7000 - 6000}{1100 - 900} = \frac{1000}{200} = 5
121
- $$
122
-
123
- ---
124
-
125
- 3. **Calculate intercept ($\beta_0$)**:
126
- $$
127
- \beta_0 = \frac{\sum{Y} - \beta_1(\sum{X})}{n} = \frac{200 - 5(30)}{5} = \frac{200 - 150}{5} = \frac{50}{5} = 10
128
- $$
129
-
130
-
131
- 4. **Equation of the line**:
132
- - The equation is: $\hat{Y} = 10 + 5X$
133
-
134
- 5. **Predict height for 8 hours of sunlight**:
135
- $$
136
- \hat{Y} = 10 + 5(8) = 10 + 40 = 50 \text{ cm}
137
- $$
138
-
139
- ---
140
-
141
- ### Python Code Example using Formula
142
-
143
- 1. **Step 1**: Organize the data.
144
- 2. **Step 2**: Calculate using the formulas provided above.
145
-
146
- ```python
147
- # Given data
148
- sunlight_hours = [2, 4, 6, 8, 10]
149
- heights = [20, 30, 40, 50, 60]
150
-
151
- # Calculate necessary sums
152
- n = len(sunlight_hours)
153
- sum_X = sum(sunlight_hours)
154
- sum_Y = sum(heights)
155
- sum_XY = sum(x * y for x, y in zip(sunlight_hours, heights))
156
- sum_X2 = sum(x**2 for x in sunlight_hours)
157
-
158
- # Calculate slope (β1) and intercept (β0)
159
- beta_1 = (n * sum_XY - sum_X * sum_Y) / (n * sum_X2 - sum_X**2)
160
- beta_0 = (sum_Y - beta_1 * sum_X) / n
161
-
162
- # Predict height for 8 hours of sunlight
163
- predicted_height = beta_0 + beta_1 * 8
164
- print(f"Predicted height for 8 hours of sunlight: {predicted_height} cm")
165
- ```
166
-
167
- Output:
168
-
169
- ```{python}
170
- # Given data
171
- sunlight_hours = [2, 4, 6, 8, 10]
172
- heights = [20, 30, 40, 50, 60]
173
-
174
- # Calculate necessary sums
175
- n = len(sunlight_hours)
176
- sum_X = sum(sunlight_hours)
177
- sum_Y = sum(heights)
178
- sum_XY = sum(x * y for x, y in zip(sunlight_hours, heights))
179
- sum_X2 = sum(x**2 for x in sunlight_hours)
180
-
181
- # Calculate slope (β1) and intercept (β0)
182
- beta_1 = (n * sum_XY - sum_X * sum_Y) / (n * sum_X2 - sum_X**2)
183
- beta_0 = (sum_Y - beta_1 * sum_X) / n
184
-
185
- # Predict height for 8 hours of sunlight
186
- predicted_height = beta_0 + beta_1 * 8
187
- print(f"Predicted height for 8 hours of sunlight: {predicted_height} cm")
188
- ```
189
-
190
-
191
- # Python Code Example using Scikit
192
-
193
- 1. **Step 1**: Import necessary libraries.
194
- 2. **Step 2**: Create a dataset from the given data.
195
- 3. **Step 3**: Generate noise to create a more realistic dataset.
196
- 4. **Step 4**: Create a Linear Regression model.
197
- 5. **Step 5**: Train the model using the dataset.
198
- 6. **Step 6**: Predict the height for 8 hours of sunlight.
199
- 7. **Step 7**: Evaluate the model's performance.
200
- 8. **Step 8**: Print accuracy and loss metrics.
201
- 9. **Step 9**: Plot graphs for visual understanding.
202
- 10. **Step 10**: Full code implementation.
203
-
204
- ---
205
-
206
- <div style="display: flex; justify-content: center;font-size:1.7em;background-color:orange;">
207
-
208
- ```python
209
-
210
- import numpy as np
211
- import pandas as pd
212
- import matplotlib.pyplot as plt
213
- from sklearn.linear_model import LinearRegression
214
- from sklearn.metrics import mean_squared_error, r2_score
215
-
216
- # Step 2: Create the dataset
217
- data = {
218
- 'Sunlight_hours': [2, 4, 6, 8, 10],
219
- 'Height_cm': [20, 30, 40, 50, 60]
220
- }
221
- df = pd.DataFrame(data)
222
-
223
- # Step 3: Generate noise for a more realistic dataset
224
- np.random.seed(0) # For reproducibility
225
- noise = np.random.normal(0, 1, size=df['Height_cm'].shape)
226
- df['Height_cm'] += noise
227
-
228
- # Step 4: Create and train the model
229
- X = df[['Sunlight_hours']]
230
- y = df['Height_cm']
231
- model = LinearRegression()
232
- model.fit(X, y)
233
-
234
- # Step 5: Predicting for 8 hours of sunlight
235
- predicted_height = model.predict([[8]])
236
-
237
- # Step 6: Evaluate the model
238
- y_pred = model.predict(X)
239
- mse = mean_squared_error(y, y_pred)
240
- r2 = r2_score(y, y_pred)
241
-
242
- # Step 7: Print results
243
- print(f"Predicted height for 8 hours of sunlight: {predicted_height[0]:.2f} cm")
244
- print(f"Mean Squared Error: {mse:.2f}")
245
- print(f"R-squared: {r2:.2f}")
246
-
247
-
248
-
249
- # Step 8: Plotting
250
- plt.scatter(X, y, color='blue', label='Actual data')
251
- plt.plot(X, y_pred, color='red', label='Regression line')
252
- plt.xlabel('Sunlight Hours')
253
- plt.ylabel('Height (cm)')
254
- plt.title('Height vs. Sunlight Hours')
255
- plt.legend()
256
- plt.show()
257
- ```
258
-
259
-
260
- </div>
261
-
262
- ---
263
-
264
- ```{python}
265
- import numpy as np
266
- import pandas as pd
267
- import matplotlib.pyplot as plt
268
- from sklearn.linear_model import LinearRegression
269
- from sklearn.metrics import mean_squared_error, r2_score
270
-
271
- # Step 2: Create the dataset
272
- data = {
273
- 'Sunlight_hours': [2, 4, 6, 8, 10],
274
- 'Height_cm': [20, 30, 40, 50, 60]
275
- }
276
- df = pd.DataFrame(data)
277
-
278
- # Step 3: Generate noise for a more realistic dataset
279
- np.random.seed(0) # For reproducibility
280
- noise = np.random.normal(0, 1, size=df['Height_cm'].shape)
281
- df['Height_cm'] += noise
282
-
283
- # Step 4: Create and train the model
284
- X = df[['Sunlight_hours']]
285
- y = df['Height_cm']
286
- model = LinearRegression()
287
- model.fit(X, y)
288
-
289
- # Step 5: Predicting for 8 hours of sunlight
290
- predicted_height = model.predict([[8]])
291
-
292
- # Step 6: Evaluate the model
293
- y_pred = model.predict(X)
294
- mse = mean_squared_error(y, y_pred)
295
- r2 = r2_score(y, y_pred)
296
-
297
- # Step 7: Print results
298
- print(f"Predicted height for 8 hours of sunlight: {predicted_height[0]:.2f} cm")
299
- print(f"Mean Squared Error: {mse:.2f}")
300
- print(f"R-squared: {r2:.2f}")
301
-
302
-
303
-
304
- # Step 8: Plotting
305
- plt.scatter(X, y, color='blue', label='Actual data')
306
- plt.plot(X, y_pred, color='red', label='Regression line')
307
- plt.xlabel('Sunlight Hours')
308
- plt.ylabel('Height (cm)')
309
- plt.title('Height vs. Sunlight Hours')
310
- plt.legend()
311
- plt.show()
312
- ```
313
-
314
-
315
- # Applications
316
-
317
- - **Agriculture**: Understanding how different sunlight conditions affect plant growth.
318
- - **Economics**: Analyzing the relationship between supply and demand.
319
- - **Healthcare**: Investigating the impact of different factors on patient outcomes.
320
-
321
-
322
-
323
- # Summary
324
-
325
- - Ordinary Least Squares is a useful tool for finding relationships between two variables. It helps make predictions and is easy to understand and implement using formulas or programming.
326
-
327
-
328
-
329
- # Recap
330
-
331
- - OLS allows us to see how one thing affects another by drawing a straight line through data points, making it easier to predict future outcomes.
332
-
333
- ---
334
-
335
-
336
- ### Comparison of Ordinary Least Squares (OLS) and OLS Complexity
337
-
338
- 1. **Focus**
339
- - **Ordinary Least Squares (OLS)**: Finding the best-fitting line or hyperplane for the data.
340
- - **OLS Complexity**: Analyzing the computational cost and efficiency of the OLS algorithm.
341
-
342
-
343
- 2. **Primary Goal**
344
- - **Ordinary Least Squares (OLS)**: Minimize the sum of squared residuals.
345
- - **OLS Complexity**: Minimize computational time and memory usage in solving the OLS equation.
346
-
347
- ---
348
-
349
- 3. **Context**
350
- - **Ordinary Least Squares (OLS)**: Regression analysis to estimate relationships.
351
- - **OLS Complexity**: Complexity analysis to determine performance on large or high-dimensional datasets.
352
-
353
-
354
-
355
- 4. **Computational Techniques**
356
- - **Ordinary Least Squares (OLS)**: Closed-form OLS solution $\beta = (X^T X)^{-1} X^T y$.
357
- - **OLS Complexity**: Analyzing matrix operations and optimizing performance with iterative methods like Gradient Descent.
358
-
359
- ---
360
-
361
- 5. **Considerations**
362
- - **Ordinary Least Squares (OLS)**: Accuracy and fit of the regression model.
363
- - **OLS Complexity**: Scalability, performance, and resource usage in computation.
364
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/ols/style.css DELETED
@@ -1,8 +0,0 @@
1
- .scrollable-table {
2
- width: 100%;
3
- max-height: 400px; /* Adjust the height to fit the screen */
4
- overflow-x: auto; /* Enable horizontal scrolling */
5
- overflow-y: auto; /* Enable vertical scrolling */
6
- font-size: 0.8em; /
7
- }
8
-