foml-toolkit 0.2.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.
@@ -0,0 +1,56 @@
1
+ """foml_toolkit: all FOML lab code (Labs 1-14) in one library."""
2
+
3
+ from .clustering import (
4
+ load_iris_df,
5
+ load_wine_df,
6
+ scale_features,
7
+ run_kmeans,
8
+ plot_clusters_2d,
9
+ plot_dendrogram,
10
+ run_agglomerative,
11
+ compare_linkages,
12
+ cluster_vs_actual,
13
+ )
14
+ from .regression import (
15
+ load_concrete,
16
+ clean_data,
17
+ engineer_features,
18
+ ORIGINAL_FEATURES,
19
+ ENGINEERED_REDUCED_FEATURES,
20
+ VIF_REDUCED_FEATURES,
21
+ select_feature_sets,
22
+ calculate_vif,
23
+ get_model_configs,
24
+ evaluate_models,
25
+ select_best_model,
26
+ plot_actual_vs_predicted,
27
+ plot_residuals,
28
+ predict_new_mix,
29
+ )
30
+
31
+ from .codebook import (
32
+ run, execute, topics, search, show_all, build_doc, topic_objects, Topic,
33
+ )
34
+
35
+ __version__ = "0.2.0"
36
+
37
+ # every topic is also available as a name: ft.pca, ft.kmeans, ft.lda ...
38
+ _TOPICS = topic_objects()
39
+ globals().update(_TOPICS)
40
+
41
+ # help(foml_toolkit) now lists every topic and prints all the code
42
+ __doc__ = build_doc()
43
+
44
+ __all__ = [
45
+ # clustering (Lab 11 + Lab 12)
46
+ "load_iris_df", "load_wine_df", "scale_features", "run_kmeans",
47
+ "plot_clusters_2d", "plot_dendrogram", "run_agglomerative",
48
+ "compare_linkages", "cluster_vs_actual",
49
+ # regression (Lab 14)
50
+ "load_concrete", "clean_data", "engineer_features",
51
+ "ORIGINAL_FEATURES", "ENGINEERED_REDUCED_FEATURES", "VIF_REDUCED_FEATURES",
52
+ "select_feature_sets", "calculate_vif", "get_model_configs",
53
+ "evaluate_models", "select_best_model", "plot_actual_vs_predicted",
54
+ "plot_residuals", "predict_new_mix",
55
+ ]
56
+ __all__ += ["run", "execute", "topics", "search", "show_all", *_TOPICS.keys()]
@@ -0,0 +1,136 @@
1
+ """Clustering helpers.
2
+
3
+ Lab 11: K-Means on the Wine dataset and on small 2-D arrays.
4
+ Lab 12: Hierarchical (agglomerative) clustering on the Iris dataset.
5
+ """
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import matplotlib.pyplot as plt
10
+ from sklearn.datasets import load_iris, load_wine
11
+ from sklearn.preprocessing import StandardScaler
12
+ from sklearn.cluster import KMeans, AgglomerativeClustering
13
+ from sklearn.metrics import silhouette_score
14
+ from scipy.cluster.hierarchy import linkage, dendrogram
15
+
16
+
17
+ # --------------------------------------------------------------------------
18
+ # Data loading
19
+ # --------------------------------------------------------------------------
20
+ def load_iris_df():
21
+ """Return (X as DataFrame, y as array) for the Iris dataset."""
22
+ iris = load_iris()
23
+ return pd.DataFrame(iris.data, columns=iris.feature_names), iris.target
24
+
25
+
26
+ def load_wine_df():
27
+ """Return (X as DataFrame, y as array) for the Wine dataset."""
28
+ wine = load_wine()
29
+ return pd.DataFrame(wine.data, columns=wine.feature_names), wine.target
30
+
31
+
32
+ # --------------------------------------------------------------------------
33
+ # Shared
34
+ # --------------------------------------------------------------------------
35
+ def scale_features(X):
36
+ """Standardise features (zero mean, unit variance).
37
+
38
+ Returns (X_scaled, fitted_scaler).
39
+ """
40
+ scaler = StandardScaler()
41
+ return scaler.fit_transform(X), scaler
42
+
43
+
44
+ def plot_clusters_2d(X, labels, x_index=0, y_index=1, xlabel="X1", ylabel="X2",
45
+ title="Clusters", cmap="viridis", centers=None, ax=None,
46
+ show=True):
47
+ """Scatter plot of two columns of X coloured by cluster label.
48
+
49
+ X can be a numpy array or a DataFrame. Pass ``centers`` (e.g.
50
+ ``kmeans.cluster_centers_``) to overlay centroids.
51
+ """
52
+ arr = X.to_numpy() if hasattr(X, "to_numpy") else np.asarray(X)
53
+ if ax is None:
54
+ _, ax = plt.subplots(figsize=(8, 5))
55
+ ax.scatter(arr[:, x_index], arr[:, y_index], c=labels, cmap=cmap)
56
+ if centers is not None:
57
+ c = np.asarray(centers)
58
+ ax.scatter(c[:, x_index], c[:, y_index], marker="X", s=200,
59
+ c="red", edgecolors="black", label="Centroids")
60
+ ax.legend()
61
+ ax.set_xlabel(xlabel)
62
+ ax.set_ylabel(ylabel)
63
+ ax.set_title(title)
64
+ if show:
65
+ plt.show()
66
+ return ax
67
+
68
+
69
+ # --------------------------------------------------------------------------
70
+ # Lab 11: K-Means
71
+ # --------------------------------------------------------------------------
72
+ def run_kmeans(X, n_clusters=3, scale=False, random_state=42, n_init=10):
73
+ """Fit K-Means.
74
+
75
+ Parameters
76
+ ----------
77
+ X : array-like or DataFrame
78
+ n_clusters : int
79
+ scale : bool
80
+ Standardise X before fitting (as done for the Wine data in Lab 11).
81
+
82
+ Returns
83
+ -------
84
+ model : fitted KMeans (use ``.labels_`` and ``.cluster_centers_``)
85
+ X_used : the data actually clustered (scaled if scale=True)
86
+ """
87
+ X_used = scale_features(X)[0] if scale else np.asarray(X)
88
+ model = KMeans(n_clusters=n_clusters, random_state=random_state,
89
+ n_init=n_init)
90
+ model.fit(X_used)
91
+ return model, X_used
92
+
93
+
94
+ # --------------------------------------------------------------------------
95
+ # Lab 12: Hierarchical clustering
96
+ # --------------------------------------------------------------------------
97
+ def plot_dendrogram(X, method="ward", figsize=(12, 6),
98
+ title="Agglomerative Clustering Dendrogram", show=True):
99
+ """Draw a dendrogram. Returns the linkage matrix Z."""
100
+ Z = linkage(X, method=method)
101
+ plt.figure(figsize=figsize)
102
+ dendrogram(Z)
103
+ plt.title(title)
104
+ plt.xlabel("Observations")
105
+ plt.ylabel("Merge Distance")
106
+ if show:
107
+ plt.show()
108
+ return Z
109
+
110
+
111
+ def run_agglomerative(X, n_clusters=3, linkage_method="ward"):
112
+ """Fit AgglomerativeClustering and return (model, labels)."""
113
+ model = AgglomerativeClustering(n_clusters=n_clusters,
114
+ linkage=linkage_method)
115
+ labels = model.fit_predict(X)
116
+ return model, labels
117
+
118
+
119
+ def compare_linkages(X, n_clusters=3,
120
+ methods=("single", "complete", "average", "ward")):
121
+ """Silhouette score for each linkage method.
122
+
123
+ The silhouette score ranges from -1 to 1; higher means better-separated
124
+ clusters. Returns a DataFrame with columns Linkage / Silhouette Score.
125
+ """
126
+ rows = []
127
+ for m in methods:
128
+ _, labels = run_agglomerative(X, n_clusters, m)
129
+ rows.append([m, silhouette_score(X, labels)])
130
+ return pd.DataFrame(rows, columns=["Linkage", "Silhouette Score"])
131
+
132
+
133
+ def cluster_vs_actual(y_true, labels):
134
+ """Crosstab of actual classes vs. predicted clusters."""
135
+ return pd.crosstab(np.asarray(y_true), np.asarray(labels),
136
+ rownames=["Actual Class"], colnames=["Cluster"])
@@ -0,0 +1,188 @@
1
+ """The code book: every lab's code, retrievable by name.
2
+
3
+ import foml_toolkit as ft
4
+ ft.run("pca") # prints ALL pca code (manual, sklearn, faces, own images)
5
+ ft.run("pca_manual") # prints one specific topic
6
+ ft.run(ft.pca) # works without quotes too
7
+ ft.run("kmeans", execute=True) # print AND execute it
8
+ ft.topics() # table of everything available
9
+ ft.search("silhouette") # find a topic by keyword
10
+ ft.show_all() # print every code in the library
11
+ help(ft) # same as show_all, inside Python's help viewer
12
+ """
13
+
14
+ import difflib
15
+ import re
16
+ from pathlib import Path
17
+
18
+ _DIR = Path(__file__).parent / "labs_code"
19
+
20
+ # group names -> topics they contain (so run("pca") shows every PCA variant)
21
+ GROUPS = {
22
+ "pca": ["pca_manual", "pca_sklearn", "pca_faces", "pca_images"],
23
+ "gd": ["gd_simple", "gd_two_var", "gd_matrix"],
24
+ "logistic": ["logistic_gd"],
25
+ "nn": ["nn_forward", "nn_scratch", "keras_nn"],
26
+ "cluster": ["kmeans", "hierarchical"],
27
+ "linear_regression": ["gd_simple", "gd_two_var", "gd_matrix", "concrete_regression"],
28
+ "numpy_basics": ["linalg", "broadcasting"],
29
+ }
30
+
31
+
32
+ class Topic:
33
+ """A named piece of code. Printing it shows the code; calling it runs it."""
34
+
35
+ def __init__(self, name, keys):
36
+ self.name = name
37
+ self.keys = list(keys)
38
+
39
+ @property
40
+ def code(self):
41
+ return "\n\n".join(_REGISTRY[k]["code"] for k in self.keys)
42
+
43
+ def __repr__(self):
44
+ return self.code
45
+
46
+ __str__ = __repr__
47
+
48
+ def __call__(self):
49
+ return execute(self)
50
+
51
+
52
+ def _parse(path):
53
+ text = path.read_text(encoding="utf-8")
54
+ meta = {"TOPIC": path.stem, "LAB": "", "TITLE": "", "TAGS": ""}
55
+ for line in text.splitlines()[:8]:
56
+ m = re.match(r"#\s*(TOPIC|LAB|TITLE|TAGS|NEEDS):\s*(.*)", line)
57
+ if m:
58
+ meta[m.group(1)] = m.group(2).strip()
59
+ return meta, text
60
+
61
+
62
+ def _load():
63
+ reg = {}
64
+ for p in sorted(_DIR.glob("*.py")):
65
+ meta, text = _parse(p)
66
+ reg[meta["TOPIC"]] = {"lab": meta["LAB"], "title": meta["TITLE"],
67
+ "tags": meta["TAGS"], "needs": meta.get("NEEDS", ""),
68
+ "file": p.name, "code": text}
69
+ return reg
70
+
71
+
72
+ _REGISTRY = _load()
73
+
74
+
75
+ def topic_objects():
76
+ """name -> Topic for every topic and group (exposed as ft.<name>)."""
77
+ objs = {k: Topic(k, [k]) for k in _REGISTRY}
78
+ for g, keys in GROUPS.items():
79
+ objs[g] = Topic(g, [k for k in keys if k in _REGISTRY])
80
+ return objs
81
+
82
+
83
+ def _resolve(name):
84
+ """Turn a string / Topic into a list of registry keys."""
85
+ if isinstance(name, Topic):
86
+ return name.keys
87
+ key = str(name).strip().lower().replace("-", "_").replace(" ", "_")
88
+ if key in _REGISTRY:
89
+ return [key]
90
+ if key in GROUPS:
91
+ return [k for k in GROUPS[key] if k in _REGISTRY]
92
+ # lab number: "lab9", "9"
93
+ m = re.fullmatch(r"(?:lab_?)?0*(\d+)", key)
94
+ if m:
95
+ keys = [k for k, v in _REGISTRY.items() if v["lab"] == m.group(1)]
96
+ if keys:
97
+ return keys
98
+ # prefix / substring / tag match
99
+ flat = key.replace("_", "")
100
+ hits = [k for k in _REGISTRY
101
+ if k.startswith(key) or key in k or flat in k.replace("_", "")
102
+ or flat in re.sub(r"[\s_\-]", "", _REGISTRY[k]["tags"].lower())]
103
+ if hits:
104
+ return hits
105
+ close = difflib.get_close_matches(key, list(_REGISTRY) + list(GROUPS), n=3)
106
+ raise KeyError(f"No topic '{name}'." + (f" Did you mean: {', '.join(close)}?" if close else "")
107
+ + " Use ft.topics() to see everything.")
108
+
109
+
110
+ def run(name=None, execute_code=False, execute=None):
111
+ """Print the code for a topic (or group, or lab number) and return it as text.
112
+
113
+ Examples: run("pca"), run("kmeans"), run("lab9"), run(ft.lda).
114
+ ``run("kmeans", execute=True)`` also executes the code.
115
+ With no argument it lists all topics.
116
+ """
117
+ if name is None:
118
+ return topics()
119
+ if execute is not None:
120
+ execute_code = execute
121
+ keys = _resolve(name)
122
+ code = "\n\n".join(_REGISTRY[k]["code"] for k in keys)
123
+ print(code)
124
+ if execute_code:
125
+ _exec(code)
126
+ return None
127
+
128
+
129
+ def execute(name):
130
+ """Run the code of a topic (or group) and return the namespace it created."""
131
+ keys = _resolve(name)
132
+ ns = {"__name__": "__main__"}
133
+ for k in keys:
134
+ _exec(_REGISTRY[k]["code"], ns)
135
+ return ns
136
+
137
+
138
+ def _exec(code, ns=None):
139
+ ns = ns if ns is not None else {"__name__": "__main__"}
140
+ exec(compile(code, "<foml_toolkit>", "exec"), ns)
141
+ return ns
142
+
143
+
144
+ def topics():
145
+ """Print a table of every topic."""
146
+ lines = [f"{'name':<22}{'lab':<5}description", "-" * 78]
147
+ for k, v in _REGISTRY.items():
148
+ lines.append(f"{k:<22}{v['lab']:<5}{v['title']}")
149
+ lines.append("")
150
+ lines.append("groups (run several at once): " +
151
+ ", ".join(f"{g} -> {len(ks)}" for g, ks in GROUPS.items()))
152
+ print("\n".join(lines))
153
+
154
+
155
+ def search(word):
156
+ """Find topics whose name, title or tags contain ``word``."""
157
+ w = word.lower()
158
+ hits = [k for k, v in _REGISTRY.items()
159
+ if w in k or w in v["title"].lower() or w in v["tags"].lower()]
160
+ for k in hits:
161
+ print(f"{k:<22}Lab {_REGISTRY[k]['lab']:<3}{_REGISTRY[k]['title']}")
162
+ return hits
163
+
164
+
165
+ def show_all():
166
+ """Print the code of every topic in the library."""
167
+ print(_full_text())
168
+
169
+
170
+ def _index_text():
171
+ rows = [f" {k:<20} Lab {v['lab']:<3} {v['title']}" for k, v in _REGISTRY.items()]
172
+ grp = [f" {g:<20} -> {', '.join(ks)}" for g, ks in GROUPS.items()]
173
+ return ("TOPICS\n" + "\n".join(rows) + "\n\nGROUPS (run(\"pca\") prints all of them)\n"
174
+ + "\n".join(grp))
175
+
176
+
177
+ def _full_text():
178
+ parts = []
179
+ for k, v in _REGISTRY.items():
180
+ bar = "=" * 78
181
+ parts.append(f"{bar}\n{k} (Lab {v['lab']}) - {v['title']}\n{bar}\n{v['code']}")
182
+ return "\n\n".join(parts)
183
+
184
+
185
+ def build_doc():
186
+ """Text used as the package docstring so help(foml_toolkit) shows everything."""
187
+ head = (__doc__ or "").strip()
188
+ return (head + "\n\n" + _index_text() + "\n\n\nALL CODE\n\n" + _full_text())
@@ -0,0 +1,77 @@
1
+ # TOPIC: linalg
2
+ # LAB: 1
3
+ # TITLE: Solving linear systems, determinant, singular matrices, plotting lines
4
+ # TAGS: numpy, solve, determinant, singular, linear equations
5
+
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+
9
+ A = np.array([[1, 3], [3, 2]], dtype=float)
10
+ B = np.array([7, 1], dtype=float)
11
+ print(A, "\n", B)
12
+ print(A.shape, B.shape)
13
+
14
+ x = np.linalg.solve(A, B) # solve A x = B
15
+ print("Solution:", x)
16
+ print("Determinant:", np.linalg.det(A))
17
+
18
+ try:
19
+ x = np.linalg.solve(A, B)
20
+ print("Solution:", x)
21
+ except np.linalg.LinAlgError as err:
22
+ print(err)
23
+
24
+ A_system = np.hstack((A, B.reshape(2, 1))) # augmented matrix [A | B]
25
+ print(A_system)
26
+
27
+
28
+ def plot_lines(M):
29
+ """Plot the two lines of a 2x2 system given the augmented matrix M."""
30
+ x_1 = np.linspace(-10, 10, 100)
31
+ x_2_line_1 = (M[0, 2] - M[0, 0] * x_1) / M[0, 1]
32
+ x_2_line_2 = (M[1, 2] - M[1, 0] * x_1) / M[1, 1]
33
+ _, ax = plt.subplots(figsize=(10, 10))
34
+ ax.plot(x_1, x_2_line_1, '-', linewidth=2, color='#FF69B4',
35
+ label=f'$x_2={-M[0,0]/M[0,1]:.2f}x_1 + {M[0,2]/M[0,1]:.2f}$')
36
+ ax.plot(x_1, x_2_line_2, '-', linewidth=2, color='#FF5F1F',
37
+ label=f'$x_2={-M[1,0]/M[1,1]:.2f}x_1 + {M[1,2]/M[1,1]:.2f}$')
38
+
39
+ A_ = M[:, 0:-1]
40
+ b_ = M[:, -1::].flatten()
41
+ d = np.linalg.det(A_)
42
+ if d != 0: # unique solution -> mark it
43
+ solution = np.linalg.solve(A_, b_)
44
+ ax.plot(solution[0], solution[1], '-o', mfc='none', markersize=10,
45
+ markeredgecolor='#FFF01F', markeredgewidth=2)
46
+ ax.text(solution[0] - 0.25, solution[1] + 0.75,
47
+ f'$({solution[0]:.0f}, {solution[1]:.0f})$', fontsize=14)
48
+
49
+ ax.set_xticks(np.arange(-10, 10))
50
+ ax.set_yticks(np.arange(-10, 10))
51
+ plt.xlabel('$x_1$', size=14)
52
+ plt.ylabel('$x_2$', size=14)
53
+ plt.legend(loc='upper right', fontsize=14)
54
+ plt.axis([-10, 10, -10, 10])
55
+ plt.grid()
56
+ plt.gca().set_aspect("equal")
57
+ plt.show()
58
+
59
+
60
+ plot_lines(A_system)
61
+
62
+ # --- singular system, infinitely many solutions (parallel + same line) ---
63
+ A = np.array([[-1, 3], [3, -9]], dtype=float)
64
+ B = np.array([7, 1], dtype=float)
65
+ try:
66
+ print("Solution:", np.linalg.solve(A, B))
67
+ except np.linalg.LinAlgError as err:
68
+ print(err) # Singular matrix
69
+ plot_lines(np.hstack((A, B.reshape(2, 1))))
70
+
71
+ # --- singular system, second RHS ---
72
+ B = np.array([7, -21], dtype=float)
73
+ try:
74
+ print("Solution:", np.linalg.solve(A, B))
75
+ except np.linalg.LinAlgError as err:
76
+ print(err)
77
+ plot_lines(np.hstack((A, B.reshape(2, 1))))
@@ -0,0 +1,56 @@
1
+ # TOPIC: broadcasting
2
+ # LAB: 1
3
+ # TITLE: NumPy vectorisation speed, broadcasting, dot-product shapes
4
+ # TAGS: numpy, broadcasting, vectorization, dot product, shapes, transpose
5
+
6
+ import time
7
+ import numpy as np
8
+
9
+ # --- vectorised vs loop dot product (sizes reduced from 1e8 so it runs fast) ---
10
+ a = np.random.rand(1_000_000)
11
+ b = np.random.rand(1_000_000)
12
+ tic = time.time()
13
+ c = np.dot(a, b)
14
+ toc = time.time()
15
+ print("vectorised ms:", 1000 * (toc - tic))
16
+
17
+ c = 0
18
+ tic = time.time()
19
+ for i in range(1_000_000):
20
+ c += a[i] * b[i]
21
+ toc = time.time()
22
+ print(c)
23
+ print("loop ms:", 1000 * (toc - tic))
24
+
25
+ # --- broadcasting: column percentages ---
26
+ A = np.array([[2, 3, 5], [7, 2, 1], [4, 5, 1]])
27
+ cal = A.sum(axis=0) # column sums
28
+ cal1 = A.sum(axis=1) # row sums
29
+ print(A, cal, cal1)
30
+ percent = 100 * (A / cal.reshape(1, 3))
31
+ print(percent)
32
+
33
+ a = np.array([1, 2, 3])
34
+ print(a + 100) # scalar broadcast
35
+ print(a * 100)
36
+
37
+ d = np.array([[2, 3, 5], [6, 7, 8], [9, 10, 11]])
38
+ e = np.array([10, 20, 30])
39
+ print(d + e) # row vector added to every row
40
+
41
+ # --- shapes: 1-D vs 2-D transposes ---
42
+ a = np.random.rand(5)
43
+ print(a.shape, a.T.shape, np.dot(a, a.T)) # 1-D: transpose does nothing -> scalar
44
+
45
+ a = np.random.rand(5, 1)
46
+ print(a.shape, a.T.shape)
47
+ print(np.dot(a, a.T)) # (5,5) outer product
48
+
49
+ # --- Experiment 1: matrix shapes ---
50
+ a = np.random.randint(1, 100, size=(4, 5))
51
+ b = np.random.randint(1, 100, size=(4, 1))
52
+ print(np.dot(a.T, b)) # (5,4)@(4,1) -> (5,1)
53
+
54
+ a = np.random.randint(1, 100, size=(4, 5))
55
+ b = np.random.randint(1, 100, size=(1, 4))
56
+ print(np.dot(a.T, b.T)) # (5,4)@(4,1) -> (5,1)
@@ -0,0 +1,46 @@
1
+ # TOPIC: gd_simple
2
+ # LAB: 2
3
+ # TITLE: Linear regression with gradient descent (one feature) vs sklearn
4
+ # TAGS: gradient descent, linear regression, cost, learning rate
5
+
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ from sklearn.linear_model import LinearRegression
9
+
10
+ x = np.array([0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6])
11
+ y = np.array([0.7, 0.65, 0.9, 0.95, 1.1, 1.15, 1.2, 1.4, 1.55, 1.5])
12
+
13
+
14
+ def LGD(x, y, lr, w0, w1, epochs, verbose=True):
15
+ """Gradient descent for h = w0 + w1*x. Returns w0, w1, cost history."""
16
+ m = float(len(x))
17
+ cost_hist = []
18
+ for i in range(epochs):
19
+ h = w0 + w1 * x # predictions
20
+ cost = (1 / (2 * m)) * np.sum((y - h) ** 2)
21
+ dw0 = -(1 / m) * np.sum(y - h) # gradients
22
+ dw1 = -(1 / m) * np.sum((y - h) * x)
23
+ w0 = w0 - lr * dw0 # NOTE: update ONCE per epoch
24
+ w1 = w1 - lr * dw1 # (notebook's function updated twice)
25
+ cost_hist.append(cost)
26
+ if verbose and i % 10 == 0:
27
+ print(f"Cost: {cost}\tIteration: {i}")
28
+ return w0, w1, cost_hist
29
+
30
+
31
+ w0, w1, cost_hist = LGD(x, y, lr=0.01, w0=0.35, w1=0.65, epochs=100)
32
+ print("Final w0 =", w0, " w1 =", w1)
33
+
34
+ plt.plot(cost_hist)
35
+ plt.title("Cost vs iteration")
36
+ plt.show()
37
+
38
+ # --- sklearn comparison ---
39
+ model = LinearRegression().fit(x.reshape(-1, 1), y)
40
+ print("sklearn intercept:", model.intercept_, " slope:", model.coef_[0])
41
+
42
+ plt.scatter(x, y, label="Data")
43
+ plt.plot(x, w1 * x + w0, color='red', label="Model Prediction")
44
+ plt.xlabel("X"); plt.ylabel("Y")
45
+ plt.title("Linear Regression using Gradient Descent")
46
+ plt.legend(); plt.grid(); plt.show()
@@ -0,0 +1,45 @@
1
+ # TOPIC: gd_two_var
2
+ # LAB: 2
3
+ # TITLE: Gradient descent with two features + SGDRegressor + LinearRegression
4
+ # TAGS: gradient descent, multiple regression, sgd, assignment
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from sklearn.linear_model import SGDRegressor, LinearRegression
9
+
10
+ x1 = np.array([0.4, 0.8, 1, 1.2, 1.8, 1.8, 2, 2, 2.4, 2])
11
+ x2 = np.array([0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6])
12
+ y = np.array([0.7, 0.65, 0.9, 0.95, 1.1, 1.15, 1.2, 1.4, 1.5, 1.5])
13
+
14
+
15
+ def LGD2(x1, x2, y, lr, w0, w1, w2, epochs, print_every=1000):
16
+ m = float(len(x1))
17
+ cost_hist = []
18
+ for i in range(epochs):
19
+ h = w0 + w1 * x1 + w2 * x2
20
+ cost = (1 / (2 * m)) * np.sum((y - h) ** 2)
21
+ dw0 = -(1 / m) * np.sum(y - h)
22
+ dw1 = -(1 / m) * np.sum((y - h) * x1)
23
+ dw2 = -(1 / m) * np.sum((y - h) * x2)
24
+ w0 -= lr * dw0 # NOTE: single update per epoch
25
+ w1 -= lr * dw1
26
+ w2 -= lr * dw2
27
+ cost_hist.append(cost)
28
+ if i % print_every == 0:
29
+ print(f"Cost: {cost}\tIteration: {i}")
30
+ return w0, w1, w2, cost_hist
31
+
32
+
33
+ w0, w1, w2, cost_hist = LGD2(x1, x2, y, 0.01, 0.35, 0.65, 0.45, 5000)
34
+ print("GD:", w0, w1, w2)
35
+
36
+ df = pd.DataFrame({"x1": x1, "x2": x2, "y": y})
37
+ X = df[["x1", "x2"]]
38
+ target = df["y"]
39
+
40
+ sgd = SGDRegressor(max_iter=5000, eta0=0.01, learning_rate='constant',
41
+ penalty=None, random_state=42).fit(X, target)
42
+ print("SGD intercept:", sgd.intercept_[0], " weights:", sgd.coef_)
43
+
44
+ lin = LinearRegression().fit(X, target)
45
+ print("OLS intercept:", lin.intercept_, " weights:", lin.coef_)
@@ -0,0 +1,50 @@
1
+ # TOPIC: gd_matrix
2
+ # LAB: 3
3
+ # TITLE: Linear regression gradient descent using matrices (any number of features)
4
+ # TAGS: gradient descent, matrix, vectorized, linear regression
5
+
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ import sklearn.linear_model as lm
9
+
10
+ np.random.seed(5)
11
+ X = np.array([[5, 3], [6, 4], [7, 6], [9, 8]])
12
+ y = np.array([2, 4, 7, 8]).reshape(-1, 1)
13
+ print(X.shape, y.shape)
14
+
15
+
16
+ def LGR(X, y, lr, epoch):
17
+ nx = X.shape[1]
18
+ m = X.shape[0]
19
+ w = np.random.rand(nx, 1)
20
+ b = 0
21
+ cost1 = []
22
+ for i in range(epoch):
23
+ h = np.dot(X, w) + b
24
+ error = h - y
25
+ cost = (np.dot(error.T, error) / (2 * m)).item()
26
+ dw = np.dot(X.T, error) / m
27
+ db = np.sum(error) / m
28
+ w = w - lr * dw
29
+ b = b - lr * db
30
+ cost1.append(cost)
31
+ return w, b, cost1
32
+
33
+
34
+ w, b, cost = LGR(X, y, 0.01, 100000)
35
+ print("W:", w)
36
+ print("B:", b)
37
+ plt.plot(np.asarray(cost)); plt.title("Cost"); plt.show()
38
+
39
+ reg = lm.LinearRegression().fit(X, y)
40
+ print("sklearn:", reg.intercept_, reg.coef_)
41
+
42
+ # --- random data with 8 features ---
43
+ np.random.seed(123)
44
+ X = np.random.rand(100, 8)
45
+ y = np.random.rand(100, 1)
46
+ w, b, cost = LGR(X, y, 0.01, 20000)
47
+ print("W:", w.ravel(), "B:", b)
48
+ plt.plot(np.asarray(cost)); plt.show()
49
+ reg = lm.LinearRegression().fit(X, y)
50
+ print("sklearn:", reg.intercept_, reg.coef_)