Skip to content

Commit 508589e

Browse files
Local Weighted Learning (#5615)
* Local Weighted Learning Added * Delete LWL directory * Local Weighted Learning Added * local weighted learning added * Delete LWL directory * Delete local_weighted_learning.py * rephrased code added * local weight learning updated * local weight learning updated * Updated dir * updated codespell * import modification * Doctests added * doctests updated * lcl updated * doctests updated * doctest values updated
1 parent 7488c50 commit 508589e

File tree

3 files changed

+201
-0
lines changed

3 files changed

+201
-0
lines changed

machine_learning/local_weighted_learning/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Locally Weighted Linear Regression
2+
It is a non-parametric ML algorithm that does not learn on a fixed set of parameters such as **linear regression**. \
3+
So, here comes a question of what is *linear regression*? \
4+
**Linear regression** is a supervised learning algorithm used for computing linear relationships between input (X) and output (Y). \
5+
6+
### Terminology Involved
7+
8+
number_of_features(i) = Number of features involved. \
9+
number_of_training_examples(m) = Number of training examples. \
10+
output_sequence(y) = Output Sequence. \
11+
$\theta$ $^T$ x = predicted point. \
12+
J($\theta$) = COst function of point.
13+
14+
The steps involved in ordinary linear regression are:
15+
16+
Training phase: Compute \theta to minimize the cost. \
17+
J($\theta$) = $\sum_{i=1}^m$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$
18+
19+
Predict output: for given query point x, \
20+
return: ($\theta$)$^T$ x
21+
22+
<img src="https://miro.medium.com/max/700/1*FZsLp8yTULf77qrp0Qd91g.png" alt="Linear Regression">
23+
24+
This training phase is possible when data points are linear, but there again comes a question can we predict non-linear relationship between x and y ? as shown below
25+
26+
<img src="https://miro.medium.com/max/700/1*DHYvJg55uN-Kj8jHaxDKvQ.png" alt="Non-linear Data">
27+
<br />
28+
<br />
29+
So, here comes the role of non-parametric algorithm which doesn't compute predictions based on fixed set of params. Rather parameters $\theta$ are computed individually for each query point/data point x.
30+
<br />
31+
<br />
32+
While Computing $\theta$ , a higher "preferance" is given to points in the vicinity of x than points farther from x.
33+
34+
Cost Function J($\theta$) = $\sum_{i=1}^m$ $w^i$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$
35+
36+
$w^i$ is non-negative weight associated to training point $x^i$. \
37+
$w^i$ is large fr $x^i$'s lying closer to query point $x_i$. \
38+
$w^i$ is small for $x^i$'s lying farther to query point $x_i$.
39+
40+
A Typical weight can be computed using \
41+
42+
$w^i$ = $\exp$(-$\frac{(x^i-x)(x^i-x)^T}{2\tau^2}$)
43+
44+
Where $\tau$ is the bandwidth parameter that controls $w^i$ distance from x.
45+
46+
Let's look at a example :
47+
48+
Suppose, we had a query point x=5.0 and training points $x^1$=4.9 and $x^2$=5.0 than we can calculate weights as :
49+
50+
$w^i$ = $\exp$(-$\frac{(x^i-x)(x^i-x)^T}{2\tau^2}$) with $\tau$=0.5
51+
52+
$w^1$ = $\exp$(-$\frac{(4.9-5)^2}{2(0.5)^2}$) = 0.9802
53+
54+
$w^2$ = $\exp$(-$\frac{(3-5)^2}{2(0.5)^2}$) = 0.000335
55+
56+
So, J($\theta$) = 0.9802*($\theta$ $^T$ $x^1$ - $y^1$) + 0.000335*($\theta$ $^T$ $x^2$ - $y^2$)
57+
58+
So, here by we can conclude that the weight fall exponentially as the distance between x & $x^i$ increases and So, does the contribution of error in prediction for $x^i$ to the cost.
59+
60+
Steps involved in LWL are : \
61+
Compute \theta to minimize the cost.
62+
J($\theta$) = $\sum_{i=1}^m$ $w^i$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$ \
63+
Predict Output: for given query point x, \
64+
return : $\theta$ $^T$ x
65+
66+
<img src="https://miro.medium.com/max/700/1*H3QS05Q1GJtY-tiBL00iug.png" alt="LWL">
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# Required imports to run this file
2+
import matplotlib.pyplot as plt
3+
import numpy as np
4+
5+
6+
# weighted matrix
7+
def weighted_matrix(point: np.mat, training_data_x: np.mat, bandwidth: float) -> np.mat:
8+
"""
9+
Calculate the weight for every point in the
10+
data set. It takes training_point , query_point, and tau
11+
Here Tau is not a fixed value it can be varied depends on output.
12+
tau --> bandwidth
13+
xmat -->Training data
14+
point --> the x where we want to make predictions
15+
>>> weighted_matrix(np.array([1., 1.]),np.mat([[16.99, 10.34], [21.01,23.68],
16+
... [24.59,25.69]]), 0.6)
17+
matrix([[1.43807972e-207, 0.00000000e+000, 0.00000000e+000],
18+
[0.00000000e+000, 0.00000000e+000, 0.00000000e+000],
19+
[0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])
20+
"""
21+
# m is the number of training samples
22+
m, n = np.shape(training_data_x)
23+
# Initializing weights as identity matrix
24+
weights = np.mat(np.eye(m))
25+
# calculating weights for all training examples [x(i)'s]
26+
for j in range(m):
27+
diff = point - training_data_x[j]
28+
weights[j, j] = np.exp(diff * diff.T / (-2.0 * bandwidth ** 2))
29+
return weights
30+
31+
32+
def local_weight(
33+
point: np.mat, training_data_x: np.mat, training_data_y: np.mat, bandwidth: float
34+
) -> np.mat:
35+
"""
36+
Calculate the local weights using the weight_matrix function on training data.
37+
Return the weighted matrix.
38+
>>> local_weight(np.array([1., 1.]),np.mat([[16.99, 10.34], [21.01,23.68],
39+
... [24.59,25.69]]),np.mat([[1.01, 1.66, 3.5]]), 0.6)
40+
matrix([[0.00873174],
41+
[0.08272556]])
42+
"""
43+
weight = weighted_matrix(point, training_data_x, bandwidth)
44+
W = (training_data_x.T * (weight * training_data_x)).I * (
45+
training_data_x.T * weight * training_data_y.T
46+
)
47+
48+
return W
49+
50+
51+
def local_weight_regression(
52+
training_data_x: np.mat, training_data_y: np.mat, bandwidth: float
53+
) -> np.mat:
54+
"""
55+
Calculate predictions for each data point on axis.
56+
>>> local_weight_regression(np.mat([[16.99, 10.34], [21.01,23.68],
57+
... [24.59,25.69]]),np.mat([[1.01, 1.66, 3.5]]), 0.6)
58+
array([1.07173261, 1.65970737, 3.50160179])
59+
"""
60+
m, n = np.shape(training_data_x)
61+
ypred = np.zeros(m)
62+
63+
for i, item in enumerate(training_data_x):
64+
ypred[i] = item * local_weight(
65+
item, training_data_x, training_data_y, bandwidth
66+
)
67+
68+
return ypred
69+
70+
71+
def load_data(dataset_name: str, cola_name: str, colb_name: str) -> np.mat:
72+
"""
73+
Function used for loading data from the seaborn splitting into x and y points
74+
>>> pass # this function has no doctest
75+
"""
76+
import seaborn as sns
77+
78+
data = sns.load_dataset(dataset_name)
79+
col_a = np.array(data[cola_name]) # total_bill
80+
col_b = np.array(data[colb_name]) # tip
81+
82+
mcol_a = np.mat(col_a)
83+
mcol_b = np.mat(col_b)
84+
85+
m = np.shape(mcol_b)[1]
86+
one = np.ones((1, m), dtype=int)
87+
88+
# horizontal stacking
89+
training_data_x = np.hstack((one.T, mcol_a.T))
90+
91+
return training_data_x, mcol_b, col_a, col_b
92+
93+
94+
def get_preds(training_data_x: np.mat, mcol_b: np.mat, tau: float) -> np.ndarray:
95+
"""
96+
Get predictions with minimum error for each training data
97+
>>> get_preds(np.mat([[16.99, 10.34], [21.01,23.68],
98+
... [24.59,25.69]]),np.mat([[1.01, 1.66, 3.5]]), 0.6)
99+
array([1.07173261, 1.65970737, 3.50160179])
100+
"""
101+
ypred = local_weight_regression(training_data_x, mcol_b, tau)
102+
return ypred
103+
104+
105+
def plot_preds(
106+
training_data_x: np.mat,
107+
predictions: np.ndarray,
108+
col_x: np.ndarray,
109+
col_y: np.ndarray,
110+
cola_name: str,
111+
colb_name: str,
112+
) -> plt.plot:
113+
"""
114+
This function used to plot predictions and display the graph
115+
>>> pass #this function has no doctest
116+
"""
117+
xsort = training_data_x.copy()
118+
xsort.sort(axis=0)
119+
plt.scatter(col_x, col_y, color="blue")
120+
plt.plot(
121+
xsort[:, 1],
122+
predictions[training_data_x[:, 1].argsort(0)],
123+
color="yellow",
124+
linewidth=5,
125+
)
126+
plt.title("Local Weighted Regression")
127+
plt.xlabel(cola_name)
128+
plt.ylabel(colb_name)
129+
plt.show()
130+
131+
132+
if __name__ == "__main__":
133+
training_data_x, mcol_b, col_a, col_b = load_data("tips", "total_bill", "tip")
134+
predictions = get_preds(training_data_x, mcol_b, 0.5)
135+
plot_preds(training_data_x, predictions, col_a, col_b, "total_bill", "tip")

0 commit comments

Comments
 (0)