joel-ml-lab 0.1.0__tar.gz
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.
- joel_ml_lab-0.1.0/PKG-INFO +5 -0
- joel_ml_lab-0.1.0/README.md +7 -0
- joel_ml_lab-0.1.0/pyproject.toml +13 -0
- joel_ml_lab-0.1.0/setup.cfg +4 -0
- joel_ml_lab-0.1.0/src/joel_ml_lab.egg-info/PKG-INFO +5 -0
- joel_ml_lab-0.1.0/src/joel_ml_lab.egg-info/SOURCES.txt +13 -0
- joel_ml_lab-0.1.0/src/joel_ml_lab.egg-info/dependency_links.txt +1 -0
- joel_ml_lab-0.1.0/src/joel_ml_lab.egg-info/top_level.txt +1 -0
- joel_ml_lab-0.1.0/src/ml_lab/__init__.py +44 -0
- joel_ml_lab-0.1.0/src/ml_lab/programs/p07.txt +18 -0
- joel_ml_lab-0.1.0/src/ml_lab/programs/p08.txt +15 -0
- joel_ml_lab-0.1.0/src/ml_lab/programs/p09.txt +16 -0
- joel_ml_lab-0.1.0/src/ml_lab/programs/p10.txt +12 -0
- joel_ml_lab-0.1.0/src/ml_lab/programs/p11.txt +19 -0
- joel_ml_lab-0.1.0/src/ml_lab/programs/p12.txt +15 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "joel-ml-lab"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "ML lab programs 7-12 (logistic regression, kNN, decision tree, EM, ensembles, policy search)"
|
|
9
|
+
requires-python = ">=3.8"
|
|
10
|
+
dependencies = []
|
|
11
|
+
|
|
12
|
+
[tool.setuptools.package-data]
|
|
13
|
+
ml_lab = ["programs/*.txt"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/joel_ml_lab.egg-info/PKG-INFO
|
|
4
|
+
src/joel_ml_lab.egg-info/SOURCES.txt
|
|
5
|
+
src/joel_ml_lab.egg-info/dependency_links.txt
|
|
6
|
+
src/joel_ml_lab.egg-info/top_level.txt
|
|
7
|
+
src/ml_lab/__init__.py
|
|
8
|
+
src/ml_lab/programs/p07.txt
|
|
9
|
+
src/ml_lab/programs/p08.txt
|
|
10
|
+
src/ml_lab/programs/p09.txt
|
|
11
|
+
src/ml_lab/programs/p10.txt
|
|
12
|
+
src/ml_lab/programs/p11.txt
|
|
13
|
+
src/ml_lab/programs/p12.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ml_lab
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""ML lab programs 7-12. Usage: from ml_lab import show_program; show_program(7)"""
|
|
2
|
+
from importlib.resources import files
|
|
3
|
+
|
|
4
|
+
TITLES = {
|
|
5
|
+
7: "Logistic Regression (Titanic Dataset)",
|
|
6
|
+
8: "k-Nearest Neighbor (Iris Dataset)",
|
|
7
|
+
9: "Decision Tree (Breast Cancer Dataset)",
|
|
8
|
+
10: "Expectation-Maximization (EM) Clustering",
|
|
9
|
+
11: "Ensemble Learning Comparison",
|
|
10
|
+
12: "Policy Search Reinforcement Learning (FrozenLake)",
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
def _check(n):
|
|
14
|
+
if n not in TITLES:
|
|
15
|
+
raise ValueError(f"No program {n}. Available: {sorted(TITLES)}")
|
|
16
|
+
|
|
17
|
+
def list_programs():
|
|
18
|
+
"""Print all available programs."""
|
|
19
|
+
for n, t in TITLES.items():
|
|
20
|
+
print(f"Program {n:02d}: {t}")
|
|
21
|
+
|
|
22
|
+
def get_program(n):
|
|
23
|
+
"""Return the source code of program n as a string."""
|
|
24
|
+
_check(n)
|
|
25
|
+
return files("ml_lab").joinpath(f"programs/p{n:02d}.txt").read_text(encoding="utf-8")
|
|
26
|
+
|
|
27
|
+
def show_program(n):
|
|
28
|
+
"""Print program n so it can be copied into a cell."""
|
|
29
|
+
print(f"# Program {n:02d}: {TITLES[n] if n in TITLES else ''}\n")
|
|
30
|
+
print(get_program(n))
|
|
31
|
+
|
|
32
|
+
def load_program(n):
|
|
33
|
+
"""In Jupyter, put program n's code into the next cell, ready to run."""
|
|
34
|
+
code = f"# Program {n:02d}: {TITLES[n]}\n" + get_program(n) if n in TITLES else get_program(n)
|
|
35
|
+
try:
|
|
36
|
+
get_ipython().set_next_input(code, replace=False) # noqa: F821
|
|
37
|
+
except NameError:
|
|
38
|
+
print(code)
|
|
39
|
+
|
|
40
|
+
def run_program(n):
|
|
41
|
+
"""Run program n directly."""
|
|
42
|
+
exec(compile(get_program(n), f"program_{n:02d}", "exec"), {"__name__": "__main__"})
|
|
43
|
+
|
|
44
|
+
__all__ = ["list_programs", "get_program", "show_program", "load_program", "run_program"]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import pandas as pd, seaborn as sns, matplotlib.pyplot as plt
|
|
2
|
+
from sklearn.linear_model import LogisticRegression
|
|
3
|
+
from sklearn.model_selection import train_test_split
|
|
4
|
+
from sklearn.preprocessing import StandardScaler
|
|
5
|
+
from sklearn.metrics import *
|
|
6
|
+
df = pd.read_csv('https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv')
|
|
7
|
+
df.columns = ['Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']
|
|
8
|
+
print(df.shape, '\n', df.head())
|
|
9
|
+
X, y = pd.get_dummies(df.drop(columns=['Survived', 'Name']), drop_first=True), df.Survived
|
|
10
|
+
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=.2, random_state=42, stratify=y)
|
|
11
|
+
sc = StandardScaler(); m = LogisticRegression(max_iter=1000).fit(sc.fit_transform(Xtr), ytr)
|
|
12
|
+
p, pr = m.predict(sc.transform(Xte)), m.predict_proba(sc.transform(Xte))[:, 1]
|
|
13
|
+
for k, f, a in [('Accuracy', accuracy_score, p), ('Precision', precision_score, p), ('Recall', recall_score, p), ('F1 Score', f1_score, p), ('ROC AUC', roc_auc_score, pr)]: print(f'{k}: {f(yte, a):.4f}')
|
|
14
|
+
print(classification_report(yte, p, target_names=['Not Survived', 'Survived']))
|
|
15
|
+
fpr, tpr, _ = roc_curve(yte, pr)
|
|
16
|
+
plt.plot(fpr, tpr, 'darkorange', label=f'ROC curve (area = {auc(fpr, tpr):.2f})'); plt.plot([0, 1], [0, 1], 'b--', label='Random classifier'); plt.xlabel('False Positive Rate'); plt.ylabel('True Positive Rate'); plt.title('ROC Curve'); plt.legend(); plt.show()
|
|
17
|
+
L = ['Not Survived', 'Survived']
|
|
18
|
+
sns.heatmap(confusion_matrix(yte, p), annot=True, fmt='d', cmap='Blues', xticklabels=L, yticklabels=L); plt.xlabel('Predicted'); plt.ylabel('Actual'); plt.title('Confusion Matrix'); plt.show()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import pandas as pd, seaborn as sns, matplotlib.pyplot as plt
|
|
2
|
+
from sklearn.datasets import load_iris
|
|
3
|
+
from sklearn.model_selection import train_test_split
|
|
4
|
+
from sklearn.preprocessing import StandardScaler
|
|
5
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
6
|
+
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
|
|
7
|
+
d = load_iris(as_frame=True); n = d.target_names
|
|
8
|
+
Xtr, Xte, ytr, yte = train_test_split(d.data, d.target, test_size=.3, random_state=42, stratify=d.target)
|
|
9
|
+
sc = StandardScaler(); m = KNeighborsClassifier(5).fit(sc.fit_transform(Xtr), ytr)
|
|
10
|
+
p = m.predict(sc.transform(Xte)); pr = m.predict_proba(sc.transform(Xte))
|
|
11
|
+
print(f'Accuracy with k=5: {accuracy_score(yte, p):.4f}')
|
|
12
|
+
r = pd.DataFrame({'Actual': n[yte], 'Predicted': n[p], 'Correct': yte == p, **{f'P({s})': pr[:, i] for i, s in enumerate(n)}}, index=yte.index)
|
|
13
|
+
print('CORRECT:', r.Correct.sum(), '/', len(r), '\n', r[r.Correct].head(10), '\nWRONG:\n', r[~r.Correct])
|
|
14
|
+
print(classification_report(yte, p, target_names=n))
|
|
15
|
+
sns.heatmap(confusion_matrix(yte, p), annot=True, cmap='Blues', xticklabels=n, yticklabels=n); plt.xlabel('Predicted'); plt.ylabel('Actual'); plt.title('Confusion Matrix'); plt.show()
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import seaborn as sns, matplotlib.pyplot as plt
|
|
2
|
+
from sklearn.datasets import load_breast_cancer
|
|
3
|
+
from sklearn.model_selection import train_test_split
|
|
4
|
+
from sklearn.tree import DecisionTreeClassifier, plot_tree
|
|
5
|
+
from sklearn.metrics import *
|
|
6
|
+
d = load_breast_cancer(); L = ['Malignant', 'Benign']
|
|
7
|
+
Xtr, Xte, ytr, yte = train_test_split(d.data, d.target, test_size=.3, random_state=42, stratify=d.target)
|
|
8
|
+
m = DecisionTreeClassifier(max_depth=4, min_samples_split=5, min_samples_leaf=2, random_state=42).fit(Xtr, ytr); p = m.predict(Xte)
|
|
9
|
+
for k, f in [('Accuracy', accuracy_score), ('Precision', precision_score), ('Recall', recall_score), ('F1 Score', f1_score)]: print(f'{k}: {f(yte, p):.4f}')
|
|
10
|
+
print(classification_report(yte, p, target_names=L))
|
|
11
|
+
sns.heatmap(confusion_matrix(yte, p), annot=True, cmap='Blues', xticklabels=L, yticklabels=L); plt.xlabel('Predicted'); plt.ylabel('Actual'); plt.title('Confusion Matrix'); plt.show()
|
|
12
|
+
plt.figure(figsize=(20, 10)); plot_tree(m, feature_names=d.feature_names, class_names=L, filled=True, rounded=True); plt.show()
|
|
13
|
+
S = [[20,25,130,1200,.15,.25,.3,.15,.2,.08,.8,1.5,5,90,.01,.03,.04,.02,.03,.01,25,30,160,1800,.2,.35,.4,.25,.3,.1],
|
|
14
|
+
[10,15,80,500,.05,.08,.06,.03,.1,.02,.3,.8,2,30,.005,.01,.01,.005,.01,.002,12,18,90,600,.07,.1,.08,.05,.12,.03],
|
|
15
|
+
[15,20,100,800,.1,.15,.18,.1,.15,.05,.5,1.2,3.5,60,.008,.02,.025,.015,.02,.006,17,25,120,1000,.13,.22,.25,.18,.22,.07]]
|
|
16
|
+
for i, pb in enumerate(m.predict_proba(S), 1): print(f'Sample {i}: {L[pb.argmax()]}, Confidence = {pb.max():.4f} | Malignant = {pb[0]:.4f}, Benign = {pb[1]:.4f}')
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import numpy as np, matplotlib.pyplot as plt
|
|
2
|
+
from scipy.stats import multivariate_normal as mvn
|
|
3
|
+
np.random.seed(42)
|
|
4
|
+
X = np.vstack([np.random.multivariate_normal(c, np.eye(2), 50) for c in ([0, 0], [5, 5])])
|
|
5
|
+
mu, cov, w = np.random.rand(2, 2) * 5, np.array([np.eye(2)] * 2), np.ones(2) / 2
|
|
6
|
+
plt.scatter(*X.T, c='gray', label='Data'); plt.scatter(*mu.T, c='red', marker='x', s=100, label='Initial Means'); plt.legend(); plt.title('Initial Data & Means'); plt.show()
|
|
7
|
+
for it in range(10):
|
|
8
|
+
r = np.column_stack([w[k] * mvn.pdf(X, mu[k], cov[k]) for k in range(2)]); r /= r.sum(1, keepdims=True)
|
|
9
|
+
for k in range(2):
|
|
10
|
+
Nk = r[:, k].sum(); mu[k] = r[:, k] @ X / Nk; d = X - mu[k]; cov[k] = (r[:, k, None] * d).T @ d / Nk; w[k] = Nk / len(X)
|
|
11
|
+
plt.scatter(*X.T, c=r.argmax(1)); plt.scatter(*mu.T, c='red', marker='x', s=100); plt.title(f'Iteration {it+1}'); plt.show()
|
|
12
|
+
print('Final cluster assignments:', r.argmax(1))
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from sklearn.datasets import load_breast_cancer
|
|
2
|
+
from sklearn.model_selection import train_test_split, cross_val_score
|
|
3
|
+
from sklearn.preprocessing import StandardScaler
|
|
4
|
+
from sklearn.ensemble import *
|
|
5
|
+
from sklearn.tree import DecisionTreeClassifier as DT
|
|
6
|
+
from sklearn.linear_model import LogisticRegression
|
|
7
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
8
|
+
from sklearn.svm import SVC
|
|
9
|
+
d = load_breast_cancer()
|
|
10
|
+
Xtr, Xte, ytr, yte = train_test_split(d.data, d.target, test_size=.3, random_state=42, stratify=d.target)
|
|
11
|
+
sc = StandardScaler(); Xtr, Xte = sc.fit_transform(Xtr), sc.transform(Xte)
|
|
12
|
+
M = {'Voting Classifier': VotingClassifier([('dt', DT(max_depth=3, random_state=42)), ('lr', LogisticRegression(max_iter=1000, random_state=42)), ('knn', KNeighborsClassifier()), ('svm', SVC(random_state=42))]),
|
|
13
|
+
'Bagging (Decision Tree)': BaggingClassifier(DT(random_state=42), n_estimators=50, random_state=42),
|
|
14
|
+
'AdaBoost': AdaBoostClassifier(DT(max_depth=1, random_state=42), n_estimators=50, random_state=42),
|
|
15
|
+
'Gradient Boosting': GradientBoostingClassifier(n_estimators=50, random_state=42),
|
|
16
|
+
'Random Forest': RandomForestClassifier(n_estimators=50, random_state=42)}
|
|
17
|
+
for k, m in M.items():
|
|
18
|
+
cv = cross_val_score(m, Xtr, ytr, cv=5)
|
|
19
|
+
print(f'{k}: Accuracy={m.fit(Xtr, ytr).score(Xte, yte):.4f}, CV={cv.mean():.4f} (±{cv.std():.4f})')
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import gymnasium as gym, numpy as np
|
|
2
|
+
env = gym.make('FrozenLake-v1', is_slippery=True); P = np.ones((16, 4)) / 4
|
|
3
|
+
for ep in range(5000):
|
|
4
|
+
s, done, tr, T = env.reset(seed=ep)[0], False, False, []
|
|
5
|
+
while not (done or tr):
|
|
6
|
+
a = np.random.choice(4, p=P[s]); s2, r, done, tr, _ = env.step(a); T.append((s, a, r)); s = s2
|
|
7
|
+
G, mr = 0, np.mean([t[2] for t in T])
|
|
8
|
+
for s, a, r in reversed(T):
|
|
9
|
+
G = .99 * G + r; P[s, a] += .1 * (G - mr); P[s] = np.maximum(P[s], 0); P[s] /= P[s].sum()
|
|
10
|
+
win = 0
|
|
11
|
+
for ep in range(100):
|
|
12
|
+
s, done, tr = env.reset(seed=ep)[0], False, False
|
|
13
|
+
while not (done or tr): s, r, done, tr, _ = env.step(P[s].argmax()); win += r
|
|
14
|
+
print(f'Success rate over 100 episodes: {win/100:.2f}\n\nLearned Policy (state -> best action):')
|
|
15
|
+
for s in range(16): print(f'State {s}: {"←↓→↑"[P[s].argmax()]}')
|