fomltools 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fomltools/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """FOML Tools - code from the Foundations of Machine Learning labs."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ def run_lab(lab_number):
6
+ """Run one included FOML lab by number."""
7
+ if not isinstance(lab_number, int):
8
+ raise TypeError("lab_number must be an integer")
9
+ module = __import__(f"fomltools.labs.lab{lab_number:02d}", fromlist=["run"])
10
+ return module.run()
@@ -0,0 +1,5 @@
1
+ """Runnable FOML lab modules.
2
+
3
+ Labs included: 1-12 and 14.
4
+ Lab 13 was not included in the uploaded files.
5
+ """
@@ -0,0 +1,210 @@
1
+ """Lab 1 code imported from the uploaded FOML notebook."""
2
+
3
+ def run():
4
+ """Run the original lab code in notebook-cell order."""
5
+ import numpy as np
6
+
7
+ A=np.array([[1,3],[3,2]],dtype=np.dtype(float))
8
+ B=np.array([7,1],dtype=np.dtype(float))
9
+ print(A)
10
+ print()
11
+ print(B)
12
+
13
+ print(A.shape)
14
+ print(B.shape)
15
+
16
+ x=np.linalg.solve(A,B)
17
+ print(x)
18
+
19
+ d=np.linalg.det(A)
20
+ print(d)
21
+
22
+ try:
23
+ x=np.linalg.solve(A,B)
24
+ print("Solution:",x)
25
+ except np.linalg.LinAlgError as err:
26
+ print(err)
27
+
28
+ A_system=np.hstack((A,B.reshape(2,1)))
29
+ print(A_system)
30
+
31
+ import matplotlib.pyplot as plt
32
+ import numpy as np
33
+
34
+ def plot_lines(M):
35
+ x_1 = np.linspace(-10, 10, 100)
36
+ x_2_line_1 = (M[0,2] - M[0,0] * x_1) / M[0,1]
37
+ x_2_line_2 = (M[1,2] - M[1,0] * x_1) / M[1,1]
38
+ _, ax = plt.subplots(figsize=(10, 10))
39
+ ax.plot(x_1, x_2_line_1, '-', linewidth=2, color='#FF69B4',
40
+ label=f'$x_2={-M[0,0]/M[0,1]:.2f}x_1 + {M[0,2]/M[0,1]:.2f}$')
41
+ ax.plot(x_1, x_2_line_2, '-', linewidth=2, color='#FF5F1F',
42
+ label=f'$x_2={-M[1,0]/M[1,1]:.2f}x_1 + {M[1,2]/M[1,1]:.2f}$')
43
+
44
+ A = M[:, 0:-1]
45
+ b = M[:, -1::].flatten()
46
+ d = np.linalg.det(A)
47
+
48
+ if d != 0:
49
+ solution = np.linalg.solve(A, b)
50
+ ax.plot(solution[0], solution[1], '-o', mfc='none',
51
+ markersize=10, markeredgecolor='#FFF01F', markeredgewidth=2)
52
+ ax.text(solution[0]-0.25, solution[1]+0.75, f'$({solution[0]:.0f}, {solution[1]:.0f})$', fontsize=14)
53
+
54
+ ax.tick_params(axis='x', labelsize=14)
55
+ ax.tick_params(axis='y', labelsize=14)
56
+ ax.set_xticks(np.arange(-10, 10))
57
+ ax.set_yticks(np.arange(-10, 10))
58
+
59
+ plt.xlabel('$x_1$', size=14)
60
+ plt.ylabel('$x_2$', size=14)
61
+ plt.legend(loc='upper right', fontsize=14)
62
+ plt.axis([-10, 10, -10, 10])
63
+
64
+ plt.grid()
65
+ plt.gca().set_aspect("equal")
66
+ plt.show()
67
+
68
+ plot_lines(A_system)
69
+
70
+ #-1,3,7
71
+ #3,-9,1
72
+
73
+ A=np.array([[-1,3],[3,-9]],dtype=np.dtype(float))
74
+ B=np.array([7,1],dtype=np.dtype(float))
75
+ print(A)
76
+ print()
77
+ print(B)
78
+
79
+ print(A.shape)
80
+ print(B.shape)
81
+
82
+ try:
83
+ x=np.linalg.solve(A,B)
84
+ print("Solution:",x)
85
+ except np.linalg.LinAlgError as err:
86
+ print(err)
87
+
88
+ A2_system=np.hstack((A,B.reshape(2,1)))
89
+ print(A2_system)
90
+
91
+ plot_lines(A2_system)
92
+
93
+ #-1,3,7
94
+ #3,-9,-21
95
+
96
+ A=np.array([[-1,3],[3,-9]],dtype=np.dtype(float))
97
+ B=np.array([7,-21],dtype=np.dtype(float))
98
+ print(A)
99
+ print()
100
+ print(B)
101
+
102
+ print(A.shape)
103
+ print(B.shape)
104
+
105
+ try:
106
+ x=np.linalg.solve(A,B)
107
+ print("Solution:",x)
108
+ except np.linalg.LinAlgError as err:
109
+ print(err)
110
+
111
+ A3_system=np.hstack((A,B.reshape(2,1)))
112
+ print(A3_system)
113
+
114
+ plot_lines(A3_system)
115
+
116
+ import time
117
+ a=np.random.rand(100000000)
118
+ b=np.random.rand(100000000)
119
+ tic=time.time()
120
+ c=np.dot(a,b)
121
+ toc=time.time()
122
+ time_taken=1000*(toc-tic)
123
+ print(time_taken)
124
+
125
+ c=0
126
+ tic=time.time()
127
+ for i in range(1000000):
128
+ c+=a[i]*b[i]
129
+ toc=time.time()
130
+ print(c)
131
+ time_taken=1000*(toc-tic)
132
+ print(time_taken)
133
+
134
+ ##Broadcasting
135
+ #vertical use of vectors
136
+ A=np.array([[2,3,5],[7,2,1],[4,5,1]])
137
+ print(A)
138
+ print()
139
+ cal=A.sum(axis=0)
140
+ cal1=A.sum(axis=1)
141
+ print(cal)
142
+ print(cal1)
143
+ percent=100*(A/cal.reshape(1,3))
144
+ print()
145
+ print(percent)
146
+
147
+ a=np.array([1,2,3])
148
+ b=a+100
149
+
150
+ print(a)
151
+ print(b)
152
+
153
+ c=a*100
154
+ print(c)
155
+
156
+ d=np.array([[2,3,5],[6,7,8],[9,10,11]])
157
+ print(d)
158
+ print()
159
+ e=np.array([10,20,30])
160
+ print(e)
161
+ print()
162
+ f=d+e
163
+ print(f)
164
+
165
+ a=np.random.rand(5)
166
+ print(a)
167
+ print(a.shape)
168
+ at=a.T
169
+ print()
170
+ print("Transpose")
171
+ print(at)
172
+ print(at.shape)
173
+ dotpro=np.dot(a,at)
174
+ print()
175
+ print("DotProdcut")
176
+ print(dotpro)
177
+
178
+
179
+ a=np.random.rand(5,1)
180
+ print(a)
181
+ print(a.shape)
182
+ at=a.T
183
+ print()
184
+ print("Transpose")
185
+ print(at)
186
+ print(at.shape)
187
+ dotpro=np.dot(a,at)
188
+ print()
189
+ print("DotProdcut")
190
+ print(dotpro)
191
+
192
+
193
+ a=np.random.randint(1, 100, size=(4, 5))
194
+ b=np.random.randint(1, 100, size=(4, 1))
195
+ at=a.T
196
+ dotpro=np.dot(at,b)
197
+ print()
198
+ print("DotProdcut")
199
+ print(dotpro)
200
+
201
+
202
+ a=np.random.randint(1, 100, size=(4, 5))
203
+ b=np.random.randint(1, 100, size=(1, 4))
204
+ at=a.T
205
+ bt=b.T
206
+ dotpro=np.dot(at,bt)
207
+ print()
208
+ print("DotProdcut")
209
+ print(dotpro)
210
+
@@ -0,0 +1,233 @@
1
+ """Lab 2 code imported from the uploaded FOML notebook."""
2
+
3
+ def run():
4
+ """Run the original lab code in notebook-cell order."""
5
+ #Gradient Desent in Linear Regression
6
+ import numpy as np
7
+
8
+ x=np.array([0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6])
9
+ y=np.array([0.7,0.65,0.9,0.95,1.1,1.15,1.2,1.4,1.55,1.5])
10
+
11
+ m=float(len(x)) #Training examples
12
+
13
+ import numpy as np
14
+
15
+ # Initialize parameters
16
+ w0 = 0.35
17
+ w1 = 0.65
18
+
19
+ lr = 0.01
20
+ epochs = 100
21
+ cost_hist = []
22
+
23
+ m = len(x)
24
+
25
+ for i in range(epochs):
26
+
27
+ # Predictions
28
+ h = w0 + w1 * x
29
+
30
+ # Cost
31
+ cost = (1/(2*m)) * np.sum((y - h)**2)
32
+
33
+ # Gradients
34
+ dw0 = -(1/m) * np.sum(y - h)
35
+ dw1 = -(1/m) * np.sum((y - h) * x)
36
+
37
+ # Update parameters
38
+ w0 = w0 - lr * dw0
39
+ w1 = w1 - lr * dw1
40
+
41
+ cost_hist.append(cost)
42
+
43
+ if i % 10 == 0:
44
+ print(f"Cost: {cost}\tIteration: {i}")
45
+
46
+ print("\nFinal Parameters:")
47
+ print("w0 =", w0)
48
+ print("w1 =", w1)
49
+
50
+ #Plot the error
51
+ import matplotlib.pyplot as plt
52
+ cost_hist1=np.asarray(cost_hist)
53
+ plt.plot(cost_hist1)
54
+
55
+ x = np.array([0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6])
56
+ y =np.array([0.7,0.65,0.9,0.95,1.1,1.15,1.2,1.4,1.55,1.5])
57
+
58
+ #Create a Linear Regression Gradient Desent Function
59
+
60
+ def LGD(x,y,lr,w0,w1,epochs):
61
+ w0=w0
62
+ w1=w1
63
+ cost_hist=[]
64
+
65
+ m=float(len(x))
66
+
67
+ for i in range(epochs):
68
+
69
+ # Predictions
70
+ h = w0 + w1 * x
71
+
72
+ # Cost
73
+ cost = (1/(2*m)) * np.sum((y - h)**2)
74
+
75
+ # Gradients
76
+ dw0 = -(1/m) * np.sum(y - h)
77
+ dw1 = -(1/m) * np.sum((y - h) * x)
78
+
79
+ # Update parameters
80
+ w0 = w0 - lr * dw0
81
+ w1 = w1 - lr * dw1
82
+
83
+ cost_hist.append(cost)
84
+
85
+ if i % 10 == 0:
86
+ print(f"Cost: {cost}\tIteration: {i}")
87
+
88
+ w0=w0-lr*dw0
89
+ w1=w1-lr*dw1
90
+ cost_hist.append(cost)
91
+ return w0,w1
92
+
93
+ LGD(x,y,0.01,0.35,0.65,100)
94
+
95
+ from sklearn.linear_model import LinearRegression
96
+
97
+ from sklearn.linear_model import LinearRegression
98
+ import numpy as np
99
+
100
+ # Example data
101
+ x = np.array([0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6]).reshape(-1, 1) # Features must be 2D
102
+ y =np.array([0.7,0.65,0.9,0.95,1.1,1.15,1.2,1.4,1.55,1.5]) # Target
103
+
104
+ # Create model
105
+ model = LinearRegression()
106
+
107
+ # Train the model
108
+ model.fit(x, y)
109
+
110
+ # Parameters
111
+ print("Intercept (w0):", model.intercept_)
112
+ print("Slope (w1):", model.coef_[0])
113
+
114
+ # Predictions
115
+ y_pred = model.predict(x)
116
+ print("Predicted values:", y_pred)
117
+
118
+ #Plot the fit line
119
+ plt.scatter(x,y,label="Data")
120
+ plt.plot(x,w1*x+w0,color='red',label="Model Prediction")
121
+ plt.xlabel("X")
122
+ plt.ylabel("Y")
123
+ plt.title("Linear Regression using Gradient Descent")
124
+ plt.legend()
125
+ plt.grid()
126
+ plt.show()
127
+
128
+ #Lab 2 Assignment
129
+ x1=np.array([0.4,0.8,1,1.2,1.8,1.8,2,2,2.4,2])
130
+ x2=np.array([0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6])
131
+ y=np.array([0.7,0.65,0.9,0.95,1.1,1.15,1.2,1.4,1.5,1.5])
132
+
133
+
134
+
135
+ #Create a Linear Regression Gradient Desent Function
136
+
137
+ def LGD(x1,x2,y,lr,w0,w1,w2,epochs):
138
+ w0=w0
139
+ w1=w1
140
+ w2=w2
141
+ cost_hist=[]
142
+
143
+ m=float(len(x1))
144
+
145
+ for i in range(epochs):
146
+ h = w0 + w1*x1 + w2*x2
147
+ cost = (1/(2*m)) * np.sum((y - h)**2)
148
+ dw0 = -(1/m) * np.sum(y - h)
149
+ dw1 = -(1/m) * np.sum((y - h) * x1)
150
+ dw2 = -(1/m) * np.sum((y - h) * x2)
151
+
152
+ w0 = w0 - lr * dw0
153
+ w1 = w1 - lr * dw1
154
+ w2 = w2 - lr * dw2
155
+
156
+ cost_hist.append(cost)
157
+
158
+ if i % 100 == 0:
159
+ print(f"Cost: {cost}\tIteration: {i}")
160
+
161
+ w0=w0-lr*dw0
162
+ w1=w1-lr*dw1
163
+ w2=w2-lr*dw2
164
+ cost_hist.append(cost)
165
+ return w0,w1,w2
166
+
167
+ LGD(x1,x2,y,0.01,0.35,0.65,0.45,5000)
168
+
169
+ from sklearn.linear_model import SGDRegressor
170
+ import numpy as np
171
+
172
+ from sklearn.linear_model import SGDRegressor
173
+ import numpy as np
174
+ import pandas as pd
175
+
176
+ # Data
177
+ x1 = np.array([0.4,0.8,1,1.2,1.8,1.8,2,2,2.4,2]).reshape(-1,1)
178
+ x2 = np.array([0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6]).reshape(-1,1)
179
+ y = np.array([0.7,0.65,0.9,0.95,1.1,1.15,1.2,1.4,1.55,1.5])
180
+ df = pd.DataFrame({
181
+ "x1": x1.flatten(),
182
+ "x2": x2.flatten(),
183
+ "y": y
184
+ })
185
+
186
+ X = df[["x1", "x2"]]
187
+ y = df["y"]
188
+
189
+ # Model
190
+ model = SGDRegressor(
191
+ max_iter=5000,
192
+ eta0=0.01,
193
+ learning_rate='constant',
194
+ penalty=None,
195
+ random_state=42
196
+ )
197
+
198
+ # Trainmodel
199
+ model.fit(X, y)
200
+ # Parameters
201
+ print("Intercept:", model.intercept_[0])
202
+ print("Weights:", model.coef_)
203
+
204
+
205
+
206
+ from sklearn.linear_model import LinearRegression
207
+ import numpy as np
208
+
209
+ x1 = np.array([0.4,0.8,1,1.2,1.8,1.8,2,2,2.4,2]).reshape(-1,1)
210
+ x2 = np.array([0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6]).reshape(-1,1)
211
+ y = np.array([0.7,0.65,0.9,0.95,1.1,1.15,1.2,1.4,1.55,1.5])
212
+ df = pd.DataFrame({
213
+ "x1": x1.flatten(),
214
+ "x2": x2.flatten(),
215
+ "y": y
216
+ })
217
+
218
+
219
+ X = df[["x1", "x2"]]
220
+ y = df["y"]
221
+
222
+
223
+ # Create model
224
+ model = LinearRegression()
225
+
226
+ # Train the model
227
+ model.fit(X, y)
228
+
229
+ # Parameters
230
+ print("Intercept (w0):", model.intercept_)
231
+ print("Slope (w1):", model.coef_)
232
+
233
+
@@ -0,0 +1,62 @@
1
+ """Lab 3 code imported from the uploaded FOML notebook."""
2
+
3
+ def run():
4
+ """Run the original lab code in notebook-cell order."""
5
+ import numpy as np
6
+
7
+ np.random.seed(5)
8
+ X=np.array([[5,3],[6,4],[7,6],[9,8]])
9
+ y=np.array([2,4,7,8]).reshape(-1,1)
10
+ print(X.shape)
11
+ print(y.shape)
12
+
13
+ def LGR(X,y,lr,epoch):
14
+ nx=X.shape[1]
15
+ m=X.shape[0]
16
+ w=np.random.rand(nx,1)
17
+ b=0
18
+ cost1=[]
19
+ for i in range(epoch):
20
+ h=np.dot(X,w)+b
21
+ error=h-y
22
+ cost=(np.dot(error.T,error)/(2*m)).item()
23
+ dw=np.dot(X.T,error)/m
24
+ db=np.sum(error)/m
25
+ w=w-lr*dw
26
+ b=b-lr*db
27
+ cost1.append(cost)
28
+ return w,b,cost1
29
+
30
+
31
+
32
+ w,b,cost=LGR(X,y,0.01,100000)
33
+
34
+ import matplotlib.pyplot as plt
35
+ cost1=np.asarray(cost)
36
+ print("W:",w)
37
+ print("B:",b)
38
+ plt.plot(cost1)
39
+
40
+ import sklearn.linear_model as lm
41
+ lr=lm.LinearRegression()
42
+ lr.fit(X,y)
43
+ print(lr.intercept_)
44
+ print(lr.coef_)
45
+
46
+ np.random.seed(123)
47
+ X=np.random.rand(100,8)
48
+ y=np.random.rand(100,1)
49
+
50
+ w,b,cost=LGR(X,y,0.01,100000)
51
+
52
+ import matplotlib.pyplot as plt
53
+ cost1=np.asarray(cost)
54
+ print("W:",w)
55
+ print("B:",b)
56
+ plt.plot(cost1)
57
+
58
+ import sklearn.linear_model as lm
59
+ lr=lm.LinearRegression()
60
+ lr.fit(X,y)
61
+ print(lr.intercept_)
62
+ print(lr.coef_)
@@ -0,0 +1,81 @@
1
+ """Lab 4 code imported from the uploaded FOML notebook."""
2
+
3
+ def run():
4
+ """Run the original lab code in notebook-cell order."""
5
+ import numpy as np
6
+
7
+ def sigmoid(z):
8
+ s=1/(1+np.exp(-z))
9
+ return s
10
+
11
+ X1=np.array([[1.,2.,-1.],[3.,4.,-3.2]])
12
+ Y1=np.array([[1,0,1]])
13
+ X=X1.T
14
+ y=Y1.T
15
+ w=np.array([[1.2],[2.3]])
16
+ print(w.shape)
17
+ b=2
18
+ n_x=2
19
+ m=3
20
+ h=np.dot(X,w)+b
21
+ a=sigmoid(h)
22
+ error=a-y
23
+ cost=-(np.sum(y*np.log(a)+(1-y)*(np.log(1-a))))/m
24
+ dw=np.dot(X.T,error)/m
25
+ db=np.sum(a-y)/m
26
+ lr=0.009
27
+ w=w-lr*dw
28
+ b=b-lr*db
29
+ print(w)
30
+ print(b)
31
+ print(h)
32
+
33
+ import sklearn.linear_model as lm
34
+ lr=lm.LogisticRegression()
35
+ y=y.reshape(-1)
36
+ lr.fit(X,y)
37
+ print(lr.intercept_)
38
+ print(lr.coef_)
39
+
40
+ def LGR(X,y,lr,epochs):
41
+ nx=X.shape[1]
42
+ m=X.shape[0]
43
+ w=np.random.rand(nx,1)
44
+ b=0
45
+ cost1=[]
46
+ for i in range(epochs):
47
+ z=np.dot(X,w)+b
48
+ a=sigmoid(z)
49
+ cost=-(1/m)*np.sum(y*np.log(a+1e-15)+(1-y)*np.log(1-a+1e-15))
50
+ cost1.append(cost)
51
+ error=a-y
52
+ dw=(1/m)*np.dot(X.T,error)
53
+ db=(1/m)*np.sum(error)
54
+ w=w-lr*dw
55
+ b=b-lr*db
56
+ return w,b,cost1
57
+
58
+ y=np.array([
59
+ [1],
60
+ [0],
61
+ [1]
62
+ ])
63
+
64
+ X=np.array([
65
+ [1.,3.],
66
+ [2.,4.],
67
+ [-1.,-3.2]
68
+ ])
69
+
70
+ w,b,cost=LGR(X,y,0.01,1000)
71
+
72
+ print("W:",w)
73
+ print("B:",b)
74
+ print("Cost",cost[-1])
75
+
76
+ import sklearn.linear_model as lm
77
+ lr=lm.LogisticRegression()
78
+ y=y.reshape(-1)
79
+ lr.fit(X,y)
80
+ print(lr.intercept_)
81
+ print(lr.coef_)