nunly 0.3.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.
- nunly-0.3.0.dist-info/METADATA +65 -0
- nunly-0.3.0.dist-info/RECORD +42 -0
- nunly-0.3.0.dist-info/WHEEL +4 -0
- nunly-0.3.0.dist-info/licenses/LICENSE +21 -0
- nunpy/__init__.py +57 -0
- nunpy/clustering.py +136 -0
- nunpy/codebook.py +245 -0
- nunpy/labs_code/activation_functions.py +124 -0
- nunpy/labs_code/lab01_numpy_basics.py +150 -0
- nunpy/labs_code/lab02_batch_gradient_descent.py +107 -0
- nunpy/labs_code/lab03_linear_regression.py +66 -0
- nunpy/labs_code/lab04_logistic_regression.py +78 -0
- nunpy/labs_code/lab05_forward_propagation.py +161 -0
- nunpy/labs_code/lab06_backward_propagation.py +175 -0
- nunpy/labs_code/lab07_tensorflow_keras.py +84 -0
- nunpy/labs_code/lab08_pca.py +82 -0
- nunpy/labs_code/lab09_image_pca.py +129 -0
- nunpy/labs_code/lab10_lda.py +101 -0
- nunpy/labs_code/lab11_kmeans.py +57 -0
- nunpy/labs_code/lab12_agglomerative.py +59 -0
- nunpy/labs_code/lab13_svm_svc.py +128 -0
- nunpy/labs_code/lab14_concrete.py +269 -0
- nunpy/regression.py +284 -0
- nunpy/theory/activation_functions.md +23 -0
- nunpy/theory/agglomerative.md +8 -0
- nunpy/theory/backward_propagation.md +64 -0
- nunpy/theory/batch_gradient_descent.md +63 -0
- nunpy/theory/concrete_regression.md +8 -0
- nunpy/theory/cross_validation.md +10 -0
- nunpy/theory/forward_propagation.md +43 -0
- nunpy/theory/image_pca.md +22 -0
- nunpy/theory/kmeans.md +10 -0
- nunpy/theory/knn.md +8 -0
- nunpy/theory/lda.md +20 -0
- nunpy/theory/linear_regression.md +35 -0
- nunpy/theory/logistic_regression.md +48 -0
- nunpy/theory/machine_learning.md +42 -0
- nunpy/theory/neural_network.md +42 -0
- nunpy/theory/numpy_basics.md +7 -0
- nunpy/theory/pca.md +24 -0
- nunpy/theory/svm.md +8 -0
- nunpy/theory/tensorflow_keras.md +21 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: nunly
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: All FOML lab code (Labs 1-14) with run("pca") and help() code lookup, plus clustering and regression helpers.
|
|
5
|
+
Project-URL: Homepage, https://github.com/YOUR_USERNAME/nunpy
|
|
6
|
+
Author-email: Your Name <you@example.com>
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Requires-Dist: matplotlib
|
|
11
|
+
Requires-Dist: numpy
|
|
12
|
+
Requires-Dist: pandas
|
|
13
|
+
Requires-Dist: scikit-learn
|
|
14
|
+
Requires-Dist: scipy
|
|
15
|
+
Provides-Extra: cv
|
|
16
|
+
Requires-Dist: opencv-python; extra == 'cv'
|
|
17
|
+
Provides-Extra: deep
|
|
18
|
+
Requires-Dist: tensorflow; extra == 'deep'
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: build; extra == 'dev'
|
|
21
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
22
|
+
Requires-Dist: twine; extra == 'dev'
|
|
23
|
+
Provides-Extra: regression
|
|
24
|
+
Requires-Dist: statsmodels; extra == 'regression'
|
|
25
|
+
Requires-Dist: ucimlrepo; extra == 'regression'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# nunpy
|
|
29
|
+
|
|
30
|
+
All FOML lab code (Labs 1-14) plus theory notes in one library.
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from nunpy import *
|
|
34
|
+
run(pca) # code
|
|
35
|
+
theory(pca) # theory of one topic
|
|
36
|
+
theory() # ALL theory
|
|
37
|
+
learn(pca) # theory then code
|
|
38
|
+
run("lab9") # by lab number
|
|
39
|
+
topics() # list everything
|
|
40
|
+
search("eigen") # keyword search (code + theory)
|
|
41
|
+
help(nunpy) # everything
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
| Lab | Topic key |
|
|
45
|
+
|---|---|
|
|
46
|
+
| 1 | numpy_basics |
|
|
47
|
+
| 2 | batch_gradient_descent |
|
|
48
|
+
| 3 | linear_regression |
|
|
49
|
+
| 4 | logistic_regression |
|
|
50
|
+
| 5 | forward_propagation |
|
|
51
|
+
| 6 | backward_propagation |
|
|
52
|
+
| 7 | tensorflow_keras |
|
|
53
|
+
| 8 | pca |
|
|
54
|
+
| 9 | image_pca |
|
|
55
|
+
| 10 | lda |
|
|
56
|
+
| 11 | kmeans |
|
|
57
|
+
| 12 | agglomerative |
|
|
58
|
+
| 13 | svm |
|
|
59
|
+
| 14 | concrete_regression |
|
|
60
|
+
| - | activation_functions |
|
|
61
|
+
| theory only | machine_learning, neural_network, knn, cross_validation |
|
|
62
|
+
|
|
63
|
+
Groups: pca_all, gd, regression, nn, cluster, dimred.
|
|
64
|
+
|
|
65
|
+
Install extras: `pip install "nunpy[regression,cv,deep]"`
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
nunpy/__init__.py,sha256=RJ1OccmeHzrxK7eLNTdnVTuVeDCZmqNCF6I90ogwxCI,1642
|
|
2
|
+
nunpy/clustering.py,sha256=xu_QdbAl5SlU-Wc11I6KYUVlz75JG3_bTX8Y86pucIk,4836
|
|
3
|
+
nunpy/codebook.py,sha256=jAo6k32wdbxUJ6iM7E03qr6pJU17SQwDHMsj53gobPs,8073
|
|
4
|
+
nunpy/regression.py,sha256=rI-eLyhbUMabGgXoH5HdQDo79OweJ0BzGHX81cPFYOk,11613
|
|
5
|
+
nunpy/labs_code/activation_functions.py,sha256=zGiz_AI_IJ8HrhrDD18VbSuilBueuET9xzqsCNqpgY4,3033
|
|
6
|
+
nunpy/labs_code/lab01_numpy_basics.py,sha256=qq1n_C3nJ2QVamOy6dl39uNXuQ9vveY6e7dA5Yyivp4,5273
|
|
7
|
+
nunpy/labs_code/lab02_batch_gradient_descent.py,sha256=JO9s6MHGLYtmNoy9sOwka794klpOpu1Bp_Fp_c7mHH8,3805
|
|
8
|
+
nunpy/labs_code/lab03_linear_regression.py,sha256=qO5q4TAOBTJci1TDQZPNF6sMDkB32tyn0nxqdhL3X58,1952
|
|
9
|
+
nunpy/labs_code/lab04_logistic_regression.py,sha256=SviTIHJOWqBpy09r5XtrAR0GA4J4icbq_FAKPwlDsQE,2034
|
|
10
|
+
nunpy/labs_code/lab05_forward_propagation.py,sha256=f45OLO8vRAZTD9FYgec5r9gX9JJovqEJ4UMa_8HpUMU,4065
|
|
11
|
+
nunpy/labs_code/lab06_backward_propagation.py,sha256=MUkhBSuOsknnHVzfKCU9YULt03k5PcV7A7Qesu0yxT0,4504
|
|
12
|
+
nunpy/labs_code/lab07_tensorflow_keras.py,sha256=SkeJjri-rs0SwM1bgUjpjWfjWHzsz9Skvmw1Ta0rQEs,3831
|
|
13
|
+
nunpy/labs_code/lab08_pca.py,sha256=7aJSS2QbU1L1M_a7-R9qLMnQBlH8S7ScrPhiCU1OcBw,3330
|
|
14
|
+
nunpy/labs_code/lab09_image_pca.py,sha256=PQ9Eo9MVTrvnSjgmP_QKBajqeMxs1Q4jRYc8S9Bc85Q,5424
|
|
15
|
+
nunpy/labs_code/lab10_lda.py,sha256=J_NmkTOaTpPOGgWYSYpSPyemSDg1yFGCoGgbBCMi6dc,3139
|
|
16
|
+
nunpy/labs_code/lab11_kmeans.py,sha256=LPgwsor86DAJJvddAwaNZda8fmWu99CDPaxVzZCPwEE,1911
|
|
17
|
+
nunpy/labs_code/lab12_agglomerative.py,sha256=4wSFTul4t9Xnn0cnyy6ACIvfrJ1FRW36NDTAr08rddE,2219
|
|
18
|
+
nunpy/labs_code/lab13_svm_svc.py,sha256=26-yVATEZHz1xHYoZ_3kO8hqCwnOc-u35IM3XLbrOHk,5795
|
|
19
|
+
nunpy/labs_code/lab14_concrete.py,sha256=h_zIpAseSisjgN7sZ90y7OCNJPP3xYVIxkG9cMuC4bA,12932
|
|
20
|
+
nunpy/theory/activation_functions.md,sha256=DOeQZkDaA1k7IgksyzL095Wr_wVZ_xtQCSB19nmF8vI,1215
|
|
21
|
+
nunpy/theory/agglomerative.md,sha256=Hq2HbQLFW7bSAS7_BOvPlmLotC3Ec78YMb9q_2FXaSc,392
|
|
22
|
+
nunpy/theory/backward_propagation.md,sha256=XPTDtMQkk9tWOyh0uxYr5oYuuUnhYjZSzNgWJ9PaVG4,2671
|
|
23
|
+
nunpy/theory/batch_gradient_descent.md,sha256=ta-jZgI9wEikN-9w5DYB6FyqbwgOpZgNXjvL-tQpTJE,2736
|
|
24
|
+
nunpy/theory/concrete_regression.md,sha256=5AjvvXbPFuGa7OuIvWn9MKKAVwCfUl8By12VxGb94H8,452
|
|
25
|
+
nunpy/theory/cross_validation.md,sha256=lkI8op28_W3EVpHsFeNqHkFlv4ZZR6K7iEtSQRFRr5Q,543
|
|
26
|
+
nunpy/theory/forward_propagation.md,sha256=gU1DkyeLBM4eODmODM0EpkTXN2n6PYscQEmoTCKoCcQ,1717
|
|
27
|
+
nunpy/theory/image_pca.md,sha256=f3SqNyXZ0apYZHDDKrQa2a1dePYPiDeRztVq0dTaOZQ,970
|
|
28
|
+
nunpy/theory/kmeans.md,sha256=-jaimVMiMV06O61SaAzn57XZpAPVe9EMjS_9H-3HwgM,370
|
|
29
|
+
nunpy/theory/knn.md,sha256=dXcoMWcLuusBnjAwQTZcXKYjTiD6kq-8mHK-uEUHMkw,481
|
|
30
|
+
nunpy/theory/lda.md,sha256=md7Gso9Nwaj8U5z-0olKuEiuH094R6ElTdPp14Ep618,753
|
|
31
|
+
nunpy/theory/linear_regression.md,sha256=6anZ9tZ3kh2gNnrFMFbDvqUUeAl2vHluBj3Sdj66Wlk,1296
|
|
32
|
+
nunpy/theory/logistic_regression.md,sha256=Ys1_j54YTiPtUwbMeHFzl12OWhQMsQcsNbyVDzgntqE,2306
|
|
33
|
+
nunpy/theory/machine_learning.md,sha256=cDPuw_mKG1W6g7Sg3u97rULfx_-i5Ec4Nt_cL82Tnyo,3003
|
|
34
|
+
nunpy/theory/neural_network.md,sha256=RwdNCRtmOH4V7apT4kfriHqt16oBmNERcuPwRWIgeFk,2113
|
|
35
|
+
nunpy/theory/numpy_basics.md,sha256=XQpCNwhYKZn-cMYCJ1g_v9zBEIjGrNA5UQvBUtZuyH8,323
|
|
36
|
+
nunpy/theory/pca.md,sha256=wcDnWmOD4LqX009GRCilqvCBYu8nbBitN9YQED0n_TA,1145
|
|
37
|
+
nunpy/theory/svm.md,sha256=wD4GoLa-jzY6JbR7f5kh6CFf0v-k-B88kxXkpUcRKAA,367
|
|
38
|
+
nunpy/theory/tensorflow_keras.md,sha256=FoPj-6CB_CHM-9QoYzRxp2P1mUd_bDFBMZ0wf5juDD8,1474
|
|
39
|
+
nunly-0.3.0.dist-info/METADATA,sha256=9tFLa0ColyxxxEZsxqNC_DYuDD1kIlslvVtC0gOLwhU,1835
|
|
40
|
+
nunly-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
41
|
+
nunly-0.3.0.dist-info/licenses/LICENSE,sha256=v2spsd7N1pKFFh2G8wGP_45iwe5S0DYiJzG4im8Rupc,1066
|
|
42
|
+
nunly-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Your Name
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
nunpy/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""nunpy: 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
|
+
theory, learn,
|
|
33
|
+
run, execute, topics, search, show_all, build_doc, topic_objects, Topic,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
__version__ = "0.3.0"
|
|
37
|
+
|
|
38
|
+
# every topic is also available as a name: ft.pca, ft.kmeans, ft.lda ...
|
|
39
|
+
_TOPICS = topic_objects()
|
|
40
|
+
globals().update(_TOPICS)
|
|
41
|
+
|
|
42
|
+
# help(nunpy) now lists every topic and prints all the code
|
|
43
|
+
__doc__ = build_doc()
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
# clustering (Lab 11 + Lab 12)
|
|
47
|
+
"load_iris_df", "load_wine_df", "scale_features", "run_kmeans",
|
|
48
|
+
"plot_clusters_2d", "plot_dendrogram", "run_agglomerative",
|
|
49
|
+
"compare_linkages", "cluster_vs_actual",
|
|
50
|
+
# regression (Lab 14)
|
|
51
|
+
"load_concrete", "clean_data", "engineer_features",
|
|
52
|
+
"ORIGINAL_FEATURES", "ENGINEERED_REDUCED_FEATURES", "VIF_REDUCED_FEATURES",
|
|
53
|
+
"select_feature_sets", "calculate_vif", "get_model_configs",
|
|
54
|
+
"evaluate_models", "select_best_model", "plot_actual_vs_predicted",
|
|
55
|
+
"plot_residuals", "predict_new_mix",
|
|
56
|
+
]
|
|
57
|
+
__all__ += ["run", "theory", "learn", "execute", "topics", "search", "show_all", *_TOPICS.keys()]
|
nunpy/clustering.py
ADDED
|
@@ -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"])
|
nunpy/codebook.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""The code book: every lab's code AND theory, retrievable by name.
|
|
2
|
+
|
|
3
|
+
import nunpy as ft
|
|
4
|
+
ft.run("pca") # prints the PCA code
|
|
5
|
+
ft.run(ft.pca) # works without quotes too
|
|
6
|
+
ft.run("lab9") # by lab number
|
|
7
|
+
ft.theory("pca") # theory of one topic
|
|
8
|
+
ft.theory() # ALL theory
|
|
9
|
+
ft.learn("pca") # theory first, then code
|
|
10
|
+
ft.run("kmeans", execute=True)
|
|
11
|
+
ft.topics() # table of everything (code / theory columns)
|
|
12
|
+
ft.search("silhouette") # find a topic by keyword
|
|
13
|
+
ft.show_all() # print everything
|
|
14
|
+
help(ft) # same as show_all, inside Python's help viewer
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import difflib
|
|
18
|
+
import re
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
_CODE_DIR = Path(__file__).parent / "labs_code"
|
|
22
|
+
_THEORY_DIR = Path(__file__).parent / "theory"
|
|
23
|
+
|
|
24
|
+
GROUPS = {
|
|
25
|
+
"pca_all": ["pca", "image_pca"],
|
|
26
|
+
"gd": ["batch_gradient_descent", "linear_regression", "logistic_regression"],
|
|
27
|
+
"regression": ["linear_regression", "concrete_regression"],
|
|
28
|
+
"nn": ["forward_propagation", "backward_propagation", "tensorflow_keras", "activation_functions"],
|
|
29
|
+
"cluster": ["kmeans", "agglomerative"],
|
|
30
|
+
"dimred": ["pca", "image_pca", "lda"],
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _meta(text, keys=("TOPIC", "LAB", "TITLE", "TAGS", "NEEDS")):
|
|
35
|
+
out = {}
|
|
36
|
+
for line in text.splitlines()[:8]:
|
|
37
|
+
m = re.match(r"#\s*(\w+):\s*(.*)", line)
|
|
38
|
+
if m and m.group(1) in keys:
|
|
39
|
+
out[m.group(1)] = m.group(2).strip()
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _load_code():
|
|
44
|
+
reg = {}
|
|
45
|
+
for p in sorted(_CODE_DIR.glob("*.py")):
|
|
46
|
+
text = p.read_text(encoding="utf-8")
|
|
47
|
+
m = _meta(text)
|
|
48
|
+
reg[m.get("TOPIC", p.stem)] = {"lab": m.get("LAB", ""), "title": m.get("TITLE", ""),
|
|
49
|
+
"tags": m.get("TAGS", ""), "file": p.name, "code": text}
|
|
50
|
+
return reg
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _load_theory():
|
|
54
|
+
reg = {}
|
|
55
|
+
for p in sorted(_THEORY_DIR.glob("*.md")):
|
|
56
|
+
text = p.read_text(encoding="utf-8")
|
|
57
|
+
m = _meta(text, ("TOPIC", "TITLE", "SOURCE"))
|
|
58
|
+
reg[m.get("TOPIC", p.stem)] = {"title": m.get("TITLE", ""), "text": text}
|
|
59
|
+
return reg
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_REGISTRY = _load_code()
|
|
63
|
+
_THEORY = _load_theory()
|
|
64
|
+
_ALL = sorted(set(_REGISTRY) | set(_THEORY), key=lambda k: (int(_REGISTRY[k]["lab"] or 99)
|
|
65
|
+
if k in _REGISTRY and _REGISTRY[k]["lab"].isdigit() else 99, k))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Topic:
|
|
69
|
+
"""A named topic. Printing shows code (or theory if there is no code); calling runs the code."""
|
|
70
|
+
|
|
71
|
+
def __init__(self, name, keys):
|
|
72
|
+
self.name = name
|
|
73
|
+
self.keys = list(keys)
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def code(self):
|
|
77
|
+
return "\n\n".join(_REGISTRY[k]["code"] for k in self.keys if k in _REGISTRY)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def theory(self):
|
|
81
|
+
return "\n\n".join(_THEORY[k]["text"] for k in self.keys if k in _THEORY)
|
|
82
|
+
|
|
83
|
+
def __repr__(self):
|
|
84
|
+
return self.code or self.theory
|
|
85
|
+
|
|
86
|
+
__str__ = __repr__
|
|
87
|
+
|
|
88
|
+
def __call__(self):
|
|
89
|
+
return execute(self)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def topic_objects():
|
|
93
|
+
"""name -> Topic for every topic and group (exposed as ft.<name>)."""
|
|
94
|
+
objs = {k: Topic(k, [k]) for k in _ALL}
|
|
95
|
+
for g, keys in GROUPS.items():
|
|
96
|
+
objs[g] = Topic(g, keys)
|
|
97
|
+
return objs
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _norm(s):
|
|
101
|
+
return str(s).strip().lower().replace("-", "_").replace(" ", "_")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _resolve(name):
|
|
105
|
+
if isinstance(name, Topic):
|
|
106
|
+
return name.keys
|
|
107
|
+
key = _norm(name)
|
|
108
|
+
if key in _ALL:
|
|
109
|
+
return [key]
|
|
110
|
+
if key in GROUPS:
|
|
111
|
+
return list(GROUPS[key])
|
|
112
|
+
m = re.fullmatch(r"(?:lab_?)?0*(\d+)", key)
|
|
113
|
+
if m:
|
|
114
|
+
keys = [k for k, v in _REGISTRY.items() if v["lab"] == m.group(1)]
|
|
115
|
+
if keys:
|
|
116
|
+
return keys
|
|
117
|
+
flat = key.replace("_", "")
|
|
118
|
+
hits = [k for k in _ALL if k.startswith(key) or key in k or flat in k.replace("_", "")
|
|
119
|
+
or (k in _REGISTRY and flat in re.sub(r"[\s_\-]", "", _REGISTRY[k]["tags"].lower()))]
|
|
120
|
+
if hits:
|
|
121
|
+
return hits
|
|
122
|
+
close = difflib.get_close_matches(key, _ALL + list(GROUPS), n=3)
|
|
123
|
+
raise KeyError(f"No topic '{name}'." + (f" Did you mean: {', '.join(close)}?" if close else "")
|
|
124
|
+
+ " Use ft.topics() to see everything.")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def run(name=None, execute_code=False, execute=None):
|
|
128
|
+
"""Print the code for a topic / group / lab number. Theory-only topics print their theory.
|
|
129
|
+
|
|
130
|
+
run("pca"), run("lab9"), run(ft.lda), run("kmeans", execute=True)
|
|
131
|
+
"""
|
|
132
|
+
if name is None:
|
|
133
|
+
return topics()
|
|
134
|
+
if execute is not None:
|
|
135
|
+
execute_code = execute
|
|
136
|
+
keys = _resolve(name)
|
|
137
|
+
code = "\n\n".join(_REGISTRY[k]["code"] for k in keys if k in _REGISTRY)
|
|
138
|
+
if not code:
|
|
139
|
+
print("(no lab code for this topic - showing theory)\n")
|
|
140
|
+
print("\n\n".join(_THEORY[k]["text"] for k in keys if k in _THEORY))
|
|
141
|
+
return None
|
|
142
|
+
print(code)
|
|
143
|
+
if execute_code:
|
|
144
|
+
_exec(code)
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def theory(name=None):
|
|
149
|
+
"""Print the theory notes for a topic / group. With no argument prints ALL theory."""
|
|
150
|
+
if name is None:
|
|
151
|
+
print("\n\n".join(f"{'=' * 78}\n{v['text']}" for v in _THEORY.values()))
|
|
152
|
+
return None
|
|
153
|
+
keys = _resolve(name)
|
|
154
|
+
text = "\n\n".join(_THEORY[k]["text"] for k in keys if k in _THEORY)
|
|
155
|
+
print(text or "No theory file for this topic yet. Try ft.run(...) for the code.")
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def learn(name):
|
|
160
|
+
"""Theory first, then code, for a topic / group."""
|
|
161
|
+
keys = _resolve(name)
|
|
162
|
+
for k in keys:
|
|
163
|
+
if k in _THEORY:
|
|
164
|
+
print("=" * 78 + f"\nTHEORY: {k}\n" + "=" * 78)
|
|
165
|
+
print(_THEORY[k]["text"])
|
|
166
|
+
if k in _REGISTRY:
|
|
167
|
+
print("\n" + "=" * 78 + f"\nCODE: {k}\n" + "=" * 78)
|
|
168
|
+
print(_REGISTRY[k]["code"])
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def execute(name):
|
|
173
|
+
"""Run the code of a topic and return the namespace it created."""
|
|
174
|
+
ns = {"__name__": "__main__"}
|
|
175
|
+
for k in _resolve(name):
|
|
176
|
+
if k in _REGISTRY:
|
|
177
|
+
_exec(_REGISTRY[k]["code"], ns)
|
|
178
|
+
return ns
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _exec(code, ns=None):
|
|
182
|
+
ns = ns if ns is not None else {"__name__": "__main__"}
|
|
183
|
+
exec(compile(code, "<nunpy>", "exec"), ns)
|
|
184
|
+
return ns
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def topics():
|
|
188
|
+
"""Print a table of every topic with code / theory flags."""
|
|
189
|
+
lines = [f"{'name':<24}{'lab':<5}{'code':<6}{'theory':<8}description", "-" * 90]
|
|
190
|
+
for k in _ALL:
|
|
191
|
+
v = _REGISTRY.get(k)
|
|
192
|
+
title = (v["title"] if v else _THEORY[k]["title"])
|
|
193
|
+
lines.append(f"{k:<24}{(v['lab'] if v else ''):<5}{'yes' if v else '-':<6}"
|
|
194
|
+
f"{'yes' if k in _THEORY else '-':<8}{title}")
|
|
195
|
+
lines.append("")
|
|
196
|
+
lines.append("groups: " + ", ".join(f"{g} ({len(ks)})" for g, ks in GROUPS.items()))
|
|
197
|
+
print("\n".join(lines))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def search(word):
|
|
201
|
+
"""Find topics whose name, title, tags or theory contain ``word``."""
|
|
202
|
+
w = word.lower()
|
|
203
|
+
hits = []
|
|
204
|
+
for k in _ALL:
|
|
205
|
+
v = _REGISTRY.get(k, {})
|
|
206
|
+
blob = " ".join([k, v.get("title", ""), v.get("tags", ""),
|
|
207
|
+
_THEORY.get(k, {}).get("text", "")]).lower()
|
|
208
|
+
if w in blob:
|
|
209
|
+
hits.append(k)
|
|
210
|
+
title = v.get("title") or _THEORY[k]["title"]
|
|
211
|
+
print(f"{k:<24}{title}")
|
|
212
|
+
return hits
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def show_all():
|
|
216
|
+
"""Print the index, all theory and all code."""
|
|
217
|
+
print(_full_text())
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _index_text():
|
|
221
|
+
rows = []
|
|
222
|
+
for k in _ALL:
|
|
223
|
+
v = _REGISTRY.get(k)
|
|
224
|
+
tag = f"Lab {v['lab']}" if v and v["lab"] else "theory"
|
|
225
|
+
rows.append(f" {k:<24} {tag:<8} {(v['title'] if v else _THEORY[k]['title'])}")
|
|
226
|
+
grp = [f" {g:<12} -> {', '.join(ks)}" for g, ks in GROUPS.items()]
|
|
227
|
+
return "TOPICS\n" + "\n".join(rows) + "\n\nGROUPS\n" + "\n".join(grp)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _full_text():
|
|
231
|
+
bar = "=" * 78
|
|
232
|
+
parts = [_index_text(), "\n\nTHEORY"]
|
|
233
|
+
for k, v in _THEORY.items():
|
|
234
|
+
parts.append(f"{bar}\n{v['text']}")
|
|
235
|
+
parts.append("\n\nCODE")
|
|
236
|
+
for k in _ALL:
|
|
237
|
+
if k in _REGISTRY:
|
|
238
|
+
v = _REGISTRY[k]
|
|
239
|
+
parts.append(f"{bar}\n{k} (Lab {v['lab']}) - {v['title']}\n{bar}\n{v['code']}")
|
|
240
|
+
return "\n\n".join(parts)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def build_doc():
|
|
244
|
+
"""Text used as the package docstring so help(nunpy) shows everything."""
|
|
245
|
+
return (__doc__ or "").strip() + "\n\n" + _full_text()
|