sjlearn 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.
Files changed (42) hide show
  1. set/__init__.py +57 -0
  2. set/clustering.py +136 -0
  3. set/codebook.py +243 -0
  4. set/labs_code/activation_functions.py +124 -0
  5. set/labs_code/lab01_numpy_basics.py +150 -0
  6. set/labs_code/lab02_batch_gradient_descent.py +107 -0
  7. set/labs_code/lab03_linear_regression.py +66 -0
  8. set/labs_code/lab04_logistic_regression.py +78 -0
  9. set/labs_code/lab05_forward_propagation.py +161 -0
  10. set/labs_code/lab06_backward_propagation.py +175 -0
  11. set/labs_code/lab07_tensorflow_keras.py +84 -0
  12. set/labs_code/lab08_pca.py +82 -0
  13. set/labs_code/lab09_image_pca.py +129 -0
  14. set/labs_code/lab10_lda.py +101 -0
  15. set/labs_code/lab11_kmeans.py +57 -0
  16. set/labs_code/lab12_agglomerative.py +59 -0
  17. set/labs_code/lab13_svm_svc.py +128 -0
  18. set/labs_code/lab14_concrete.py +269 -0
  19. set/regression.py +284 -0
  20. set/theory/activation_functions.md +23 -0
  21. set/theory/agglomerative.md +8 -0
  22. set/theory/backward_propagation.md +64 -0
  23. set/theory/batch_gradient_descent.md +63 -0
  24. set/theory/concrete_regression.md +8 -0
  25. set/theory/cross_validation.md +10 -0
  26. set/theory/forward_propagation.md +43 -0
  27. set/theory/image_pca.md +22 -0
  28. set/theory/kmeans.md +10 -0
  29. set/theory/knn.md +8 -0
  30. set/theory/lda.md +20 -0
  31. set/theory/linear_regression.md +35 -0
  32. set/theory/logistic_regression.md +48 -0
  33. set/theory/machine_learning.md +42 -0
  34. set/theory/neural_network.md +42 -0
  35. set/theory/numpy_basics.md +7 -0
  36. set/theory/pca.md +24 -0
  37. set/theory/svm.md +8 -0
  38. set/theory/tensorflow_keras.md +21 -0
  39. sjlearn-0.3.0.dist-info/METADATA +64 -0
  40. sjlearn-0.3.0.dist-info/RECORD +42 -0
  41. sjlearn-0.3.0.dist-info/WHEEL +4 -0
  42. sjlearn-0.3.0.dist-info/licenses/LICENSE +21 -0
set/__init__.py ADDED
@@ -0,0 +1,57 @@
1
+ """set: 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(set) 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()]
set/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"])
set/codebook.py ADDED
@@ -0,0 +1,243 @@
1
+ """The code book: every lab's code AND theory, retrievable by name.
2
+
3
+ import set 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") # prints the theory notes
8
+ ft.learn("pca") # theory first, then code
9
+ ft.run("kmeans", execute=True)
10
+ ft.topics() # table of everything (code / theory columns)
11
+ ft.search("silhouette") # find a topic by keyword
12
+ ft.show_all() # print everything
13
+ help(ft) # same as show_all, inside Python's help viewer
14
+ """
15
+
16
+ import difflib
17
+ import re
18
+ from pathlib import Path
19
+
20
+ _CODE_DIR = Path(__file__).parent / "labs_code"
21
+ _THEORY_DIR = Path(__file__).parent / "theory"
22
+
23
+ GROUPS = {
24
+ "pca_all": ["pca", "image_pca"],
25
+ "gd": ["batch_gradient_descent", "linear_regression", "logistic_regression"],
26
+ "regression": ["linear_regression", "concrete_regression"],
27
+ "nn": ["forward_propagation", "backward_propagation", "tensorflow_keras", "activation_functions"],
28
+ "cluster": ["kmeans", "agglomerative"],
29
+ "dimred": ["pca", "image_pca", "lda"],
30
+ }
31
+
32
+
33
+ def _meta(text, keys=("TOPIC", "LAB", "TITLE", "TAGS", "NEEDS")):
34
+ out = {}
35
+ for line in text.splitlines()[:8]:
36
+ m = re.match(r"#\s*(\w+):\s*(.*)", line)
37
+ if m and m.group(1) in keys:
38
+ out[m.group(1)] = m.group(2).strip()
39
+ return out
40
+
41
+
42
+ def _load_code():
43
+ reg = {}
44
+ for p in sorted(_CODE_DIR.glob("*.py")):
45
+ text = p.read_text(encoding="utf-8")
46
+ m = _meta(text)
47
+ reg[m.get("TOPIC", p.stem)] = {"lab": m.get("LAB", ""), "title": m.get("TITLE", ""),
48
+ "tags": m.get("TAGS", ""), "file": p.name, "code": text}
49
+ return reg
50
+
51
+
52
+ def _load_theory():
53
+ reg = {}
54
+ for p in sorted(_THEORY_DIR.glob("*.md")):
55
+ text = p.read_text(encoding="utf-8")
56
+ m = _meta(text, ("TOPIC", "TITLE", "SOURCE"))
57
+ reg[m.get("TOPIC", p.stem)] = {"title": m.get("TITLE", ""), "text": text}
58
+ return reg
59
+
60
+
61
+ _REGISTRY = _load_code()
62
+ _THEORY = _load_theory()
63
+ _ALL = sorted(set(_REGISTRY) | set(_THEORY), key=lambda k: (int(_REGISTRY[k]["lab"] or 99)
64
+ if k in _REGISTRY and _REGISTRY[k]["lab"].isdigit() else 99, k))
65
+
66
+
67
+ class Topic:
68
+ """A named topic. Printing shows code (or theory if there is no code); calling runs the code."""
69
+
70
+ def __init__(self, name, keys):
71
+ self.name = name
72
+ self.keys = list(keys)
73
+
74
+ @property
75
+ def code(self):
76
+ return "\n\n".join(_REGISTRY[k]["code"] for k in self.keys if k in _REGISTRY)
77
+
78
+ @property
79
+ def theory(self):
80
+ return "\n\n".join(_THEORY[k]["text"] for k in self.keys if k in _THEORY)
81
+
82
+ def __repr__(self):
83
+ return self.code or self.theory
84
+
85
+ __str__ = __repr__
86
+
87
+ def __call__(self):
88
+ return execute(self)
89
+
90
+
91
+ def topic_objects():
92
+ """name -> Topic for every topic and group (exposed as ft.<name>)."""
93
+ objs = {k: Topic(k, [k]) for k in _ALL}
94
+ for g, keys in GROUPS.items():
95
+ objs[g] = Topic(g, keys)
96
+ return objs
97
+
98
+
99
+ def _norm(s):
100
+ return str(s).strip().lower().replace("-", "_").replace(" ", "_")
101
+
102
+
103
+ def _resolve(name):
104
+ if isinstance(name, Topic):
105
+ return name.keys
106
+ key = _norm(name)
107
+ if key in _ALL:
108
+ return [key]
109
+ if key in GROUPS:
110
+ return list(GROUPS[key])
111
+ m = re.fullmatch(r"(?:lab_?)?0*(\d+)", key)
112
+ if m:
113
+ keys = [k for k, v in _REGISTRY.items() if v["lab"] == m.group(1)]
114
+ if keys:
115
+ return keys
116
+ flat = key.replace("_", "")
117
+ hits = [k for k in _ALL if k.startswith(key) or key in k or flat in k.replace("_", "")
118
+ or (k in _REGISTRY and flat in re.sub(r"[\s_\-]", "", _REGISTRY[k]["tags"].lower()))]
119
+ if hits:
120
+ return hits
121
+ close = difflib.get_close_matches(key, _ALL + list(GROUPS), n=3)
122
+ raise KeyError(f"No topic '{name}'." + (f" Did you mean: {', '.join(close)}?" if close else "")
123
+ + " Use ft.topics() to see everything.")
124
+
125
+
126
+ def run(name=None, execute_code=False, execute=None):
127
+ """Print the code for a topic / group / lab number. Theory-only topics print their theory.
128
+
129
+ run("pca"), run("lab9"), run(ft.lda), run("kmeans", execute=True)
130
+ """
131
+ if name is None:
132
+ return topics()
133
+ if execute is not None:
134
+ execute_code = execute
135
+ keys = _resolve(name)
136
+ code = "\n\n".join(_REGISTRY[k]["code"] for k in keys if k in _REGISTRY)
137
+ if not code:
138
+ print("(no lab code for this topic - showing theory)\n")
139
+ print("\n\n".join(_THEORY[k]["text"] for k in keys if k in _THEORY))
140
+ return None
141
+ print(code)
142
+ if execute_code:
143
+ _exec(code)
144
+ return None
145
+
146
+
147
+ def theory(name=None):
148
+ """Print the theory notes for a topic / group."""
149
+ if name is None:
150
+ return topics()
151
+ keys = _resolve(name)
152
+ text = "\n\n".join(_THEORY[k]["text"] for k in keys if k in _THEORY)
153
+ print(text or "No theory file for this topic yet. Try ft.run(...) for the code.")
154
+ return None
155
+
156
+
157
+ def learn(name):
158
+ """Theory first, then code, for a topic / group."""
159
+ keys = _resolve(name)
160
+ for k in keys:
161
+ if k in _THEORY:
162
+ print("=" * 78 + f"\nTHEORY: {k}\n" + "=" * 78)
163
+ print(_THEORY[k]["text"])
164
+ if k in _REGISTRY:
165
+ print("\n" + "=" * 78 + f"\nCODE: {k}\n" + "=" * 78)
166
+ print(_REGISTRY[k]["code"])
167
+ return None
168
+
169
+
170
+ def execute(name):
171
+ """Run the code of a topic and return the namespace it created."""
172
+ ns = {"__name__": "__main__"}
173
+ for k in _resolve(name):
174
+ if k in _REGISTRY:
175
+ _exec(_REGISTRY[k]["code"], ns)
176
+ return ns
177
+
178
+
179
+ def _exec(code, ns=None):
180
+ ns = ns if ns is not None else {"__name__": "__main__"}
181
+ exec(compile(code, "<set>", "exec"), ns)
182
+ return ns
183
+
184
+
185
+ def topics():
186
+ """Print a table of every topic with code / theory flags."""
187
+ lines = [f"{'name':<24}{'lab':<5}{'code':<6}{'theory':<8}description", "-" * 90]
188
+ for k in _ALL:
189
+ v = _REGISTRY.get(k)
190
+ title = (v["title"] if v else _THEORY[k]["title"])
191
+ lines.append(f"{k:<24}{(v['lab'] if v else ''):<5}{'yes' if v else '-':<6}"
192
+ f"{'yes' if k in _THEORY else '-':<8}{title}")
193
+ lines.append("")
194
+ lines.append("groups: " + ", ".join(f"{g} ({len(ks)})" for g, ks in GROUPS.items()))
195
+ print("\n".join(lines))
196
+
197
+
198
+ def search(word):
199
+ """Find topics whose name, title, tags or theory contain ``word``."""
200
+ w = word.lower()
201
+ hits = []
202
+ for k in _ALL:
203
+ v = _REGISTRY.get(k, {})
204
+ blob = " ".join([k, v.get("title", ""), v.get("tags", ""),
205
+ _THEORY.get(k, {}).get("text", "")]).lower()
206
+ if w in blob:
207
+ hits.append(k)
208
+ title = v.get("title") or _THEORY[k]["title"]
209
+ print(f"{k:<24}{title}")
210
+ return hits
211
+
212
+
213
+ def show_all():
214
+ """Print the index, all theory and all code."""
215
+ print(_full_text())
216
+
217
+
218
+ def _index_text():
219
+ rows = []
220
+ for k in _ALL:
221
+ v = _REGISTRY.get(k)
222
+ tag = f"Lab {v['lab']}" if v and v["lab"] else "theory"
223
+ rows.append(f" {k:<24} {tag:<8} {(v['title'] if v else _THEORY[k]['title'])}")
224
+ grp = [f" {g:<12} -> {', '.join(ks)}" for g, ks in GROUPS.items()]
225
+ return "TOPICS\n" + "\n".join(rows) + "\n\nGROUPS\n" + "\n".join(grp)
226
+
227
+
228
+ def _full_text():
229
+ bar = "=" * 78
230
+ parts = [_index_text(), "\n\nTHEORY"]
231
+ for k, v in _THEORY.items():
232
+ parts.append(f"{bar}\n{v['text']}")
233
+ parts.append("\n\nCODE")
234
+ for k in _ALL:
235
+ if k in _REGISTRY:
236
+ v = _REGISTRY[k]
237
+ parts.append(f"{bar}\n{k} (Lab {v['lab']}) - {v['title']}\n{bar}\n{v['code']}")
238
+ return "\n\n".join(parts)
239
+
240
+
241
+ def build_doc():
242
+ """Text used as the package docstring so help(set) shows everything."""
243
+ return (__doc__ or "").strip() + "\n\n" + _full_text()
@@ -0,0 +1,124 @@
1
+ # TOPIC: activation_functions
2
+ # LAB: -
3
+ # TITLE: Activation functions and their derivatives (linear, sigmoid, tanh, ReLU, leaky ReLU, ELU, swish, mish, softmax)
4
+ # TAGS: activation, sigmoid, tanh, relu, leaky relu, elu, swish, mish, softmax, gradient, derivative
5
+ # SOURCE: https://www.v7labs.com/blog/neural-networks-activation-functions
6
+
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+
10
+
11
+ def linear(x):
12
+ return x
13
+
14
+
15
+ def sigmoid(x):
16
+ return 1 / (1 + np.exp(-x))
17
+
18
+
19
+ def tanh(x):
20
+ return np.tanh(x)
21
+
22
+
23
+ def relu(x):
24
+ return np.maximum(0, x)
25
+
26
+
27
+ def leaky_relu(x, alpha=0.01):
28
+ return np.where(x > 0, x, alpha * x)
29
+
30
+
31
+ def prelu(x, alpha=0.25):
32
+ return np.where(x > 0, x, alpha * x) # alpha is learnable in real models
33
+
34
+
35
+ def elu(x, alpha=1.0):
36
+ return np.where(x > 0, x, alpha * (np.exp(x) - 1))
37
+
38
+
39
+ def swish(x):
40
+ return x * sigmoid(x)
41
+
42
+
43
+ def mish(x):
44
+ return x * np.tanh(np.log(1 + np.exp(x)))
45
+
46
+
47
+ def softmax(x):
48
+ e_x = np.exp(x - np.max(x))
49
+ return e_x / e_x.sum(axis=0)
50
+
51
+
52
+ x = np.linspace(-10, 10, 1000)
53
+ plt.figure(figsize=(14, 10))
54
+ plots = [("Linear", linear), ("Sigmoid", sigmoid), ("Tanh", tanh), ("ReLU", relu),
55
+ ("Leaky ReLU", leaky_relu), ("ELU", elu), ("Swish", swish), ("Mish", mish)]
56
+ for i, (name, f) in enumerate(plots, start=1):
57
+ plt.subplot(3, 3, i)
58
+ plt.plot(x, f(x))
59
+ plt.title(name)
60
+ plt.subplot(3, 3, 9) # softmax works on a vector
61
+ sample_input = np.array([1.0, 2.0, 3.0, 4.0])
62
+ plt.bar(range(len(sample_input)), softmax(sample_input))
63
+ plt.title('Softmax (Fixed Vector)')
64
+ plt.tight_layout()
65
+ plt.show()
66
+
67
+
68
+ # ---------------- Derivatives (gradients) ----------------
69
+ def sigmoid_derivative(x):
70
+ s = sigmoid(x)
71
+ return s * (1 - s)
72
+
73
+
74
+ def tanh_derivative(x):
75
+ return 1 - np.tanh(x) ** 2
76
+
77
+
78
+ def relu_derivative(x):
79
+ return np.where(x > 0, 1, 0)
80
+
81
+
82
+ def leaky_relu_derivative(x, alpha=0.01):
83
+ return np.where(x > 0, 1, alpha)
84
+
85
+
86
+ def elu_derivative(x, alpha=1.0):
87
+ return np.where(x >= 0, 1, elu(x, alpha) + alpha)
88
+
89
+
90
+ def swish_derivative(x):
91
+ s = sigmoid(x)
92
+ return s + x * s * (1 - s)
93
+
94
+
95
+ def mish_derivative(x):
96
+ omega = 4 * (x + 1) + 4 * np.exp(2 * x) + np.exp(3 * x) + np.exp(x) * (4 * x + 6)
97
+ delta = (2 * np.exp(x) + np.exp(2 * x) + 2) ** 2
98
+ return np.exp(x) * omega / delta
99
+
100
+
101
+ x = np.linspace(-5, 5, 500)
102
+ plt.figure(figsize=(14, 10))
103
+ grads = [("Sigmoid Gradient", sigmoid_derivative), ("Tanh Gradient", tanh_derivative),
104
+ ("ReLU Gradient", relu_derivative), ("Leaky ReLU Gradient", leaky_relu_derivative),
105
+ ("ELU Gradient", elu_derivative), ("Swish Gradient", swish_derivative),
106
+ ("Mish Gradient", mish_derivative)]
107
+ for i, (name, f) in enumerate(grads, start=1):
108
+ plt.subplot(3, 3, i)
109
+ plt.plot(x, f(x))
110
+ plt.title(name)
111
+ plt.tight_layout()
112
+ plt.show()
113
+
114
+ # ---------------- Softmax and its Jacobian ----------------
115
+ s = softmax(np.array([1.0, 2.0, 3.0, 4.0]))
116
+ print(s)
117
+
118
+
119
+ def softmax_jacobian(s):
120
+ s = s.reshape(-1, 1)
121
+ return np.diagflat(s) - np.dot(s, s.T)
122
+
123
+
124
+ print(softmax_jacobian(s))