forgeproof-cli 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.
- forge_gate/__init__.py +44 -0
- forge_gate/_deprecated_cli.py +16 -0
- forgeproof/__init__.py +3 -0
- forgeproof/catalog.py +110 -0
- forgeproof/cli.py +560 -0
- forgeproof/config.py +339 -0
- forgeproof/data/gate_catalog.json +66 -0
- forgeproof/data/host_sets.json +7 -0
- forgeproof/debug_caller.py +271 -0
- forgeproof/debug_core.py +368 -0
- forgeproof/fixture_engine.py +81 -0
- forgeproof/fixtures/__init__.py +19 -0
- forgeproof/fixtures/decision_tree_id3.py +90 -0
- forgeproof/fixtures/gradient_descent_momentum.py +73 -0
- forgeproof/fixtures/kmeans_clustering.py +98 -0
- forgeproof/fixtures/knn_classifier.py +79 -0
- forgeproof/fixtures/linear_regression_gd.py +77 -0
- forgeproof/fixtures/logistic_regression.py +85 -0
- forgeproof/fixtures/naive_bayes_text.py +114 -0
- forgeproof/fixtures/perceptron.py +84 -0
- forgeproof/fixtures/polynomial_regression.py +67 -0
- forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
- forgeproof/ledger.py +633 -0
- forgeproof/lens_tools/__init__.py +11 -0
- forgeproof/lens_tools/guard_lens.py +1250 -0
- forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
- forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
- forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
- forgeproof/lens_tools/invariant_gate.py +199 -0
- forgeproof/lens_tools/metamorphic/__init__.py +9 -0
- forgeproof/lens_tools/metamorphic/relations.py +962 -0
- forgeproof/lens_tools/metamorphic/runner.py +112 -0
- forgeproof/lens_tools/twin_consensus.py +395 -0
- forgeproof/lenses.py +923 -0
- forgeproof/paths.py +56 -0
- forgeproof/reference/ORIGIN.md +29 -0
- forgeproof/reference/decision_tree_id3.py +197 -0
- forgeproof/reference/gradient_descent_momentum.py +141 -0
- forgeproof/reference/kmeans_clustering.py +139 -0
- forgeproof/reference/knn_classifier.py +118 -0
- forgeproof/reference/linear_regression_gd.py +106 -0
- forgeproof/reference/logistic_regression.py +141 -0
- forgeproof/reference/naive_bayes_text.py +152 -0
- forgeproof/reference/perceptron.py +123 -0
- forgeproof/reference/polynomial_regression.py +125 -0
- forgeproof/reference/ridge_regression_normal_eq.py +165 -0
- forgeproof/runner.py +147 -0
- forgeproof/scout/__init__.py +7 -0
- forgeproof/scout/behaviour.py +365 -0
- forgeproof/scout/box.py +581 -0
- forgeproof/scout/cards.py +180 -0
- forgeproof/scout/contract.py +37 -0
- forgeproof/scout/corpus.py +104 -0
- forgeproof/scout/embed.py +217 -0
- forgeproof/scout/engines/__init__.py +1 -0
- forgeproof/scout/engines/chaos.py +454 -0
- forgeproof/scout/engines/chaos_port.py +1331 -0
- forgeproof/scout/engines/chaos_runner.py +178 -0
- forgeproof/scout/engines/executor_port.py +239 -0
- forgeproof/scout/envfit.py +54 -0
- forgeproof/scout/experience.py +161 -0
- forgeproof/scout/fetchproxy.py +368 -0
- forgeproof/scout/ghcache.py +395 -0
- forgeproof/scout/ghpool.py +253 -0
- forgeproof/scout/ghsearch.py +248 -0
- forgeproof/scout/ids.py +82 -0
- forgeproof/scout/intent_lens.py +170 -0
- forgeproof/scout/learn.py +583 -0
- forgeproof/scout/meaning_lens.py +231 -0
- forgeproof/scout/outcomes.py +42 -0
- forgeproof/scout/plant.py +327 -0
- forgeproof/scout/ratify.py +214 -0
- forgeproof/scout/report.py +448 -0
- forgeproof/scout/rule2.py +177 -0
- forgeproof/scout/shape.py +107 -0
- forgeproof/scout/shape_lens.py +71 -0
- forgeproof/scout/signature.py +52 -0
- forgeproof/scout/slots.py +39 -0
- forgeproof/scout/upstream_facts.py +536 -0
- forgeproof/unsupported.py +83 -0
- forgeproof/verifier.py +208 -0
- forgeproof/view_coverage.py +166 -0
- forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
- forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
- forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
- forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
- forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
- forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
- forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""
|
|
2
|
+
k-Nearest Neighbors Classifier (from scratch).
|
|
3
|
+
|
|
4
|
+
Core idea: To classify a new point, find the k nearest training samples using
|
|
5
|
+
Euclidean distance and predict the majority class among them. No training phase;
|
|
6
|
+
prediction is expensive but the model is simple and often effective.
|
|
7
|
+
|
|
8
|
+
When to use: Non-linear boundaries; small to medium datasets; quick prototypes.
|
|
9
|
+
"""
|
|
10
|
+
# △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
|
|
11
|
+
#
|
|
12
|
+
_AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
|
|
13
|
+
|
|
14
|
+
import random
|
|
15
|
+
import math
|
|
16
|
+
from typing import List, Tuple
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def euclidean_distance(p1: List[float], p2: List[float]) -> float:
|
|
20
|
+
"""Compute Euclidean distance between two points."""
|
|
21
|
+
return math.sqrt(sum((p1[i] - p2[i]) ** 2 for i in range(len(p1))))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def knn_predict(
|
|
25
|
+
x_test: List[float],
|
|
26
|
+
X_train: List[List[float]],
|
|
27
|
+
y_train: List[int],
|
|
28
|
+
k: int = 3
|
|
29
|
+
) -> int:
|
|
30
|
+
"""
|
|
31
|
+
Predict the class of a single test point using kNN.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
x_test: feature vector of test point
|
|
35
|
+
X_train: list of training feature vectors
|
|
36
|
+
y_train: list of training labels
|
|
37
|
+
k: number of neighbors to consider
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
predicted class label
|
|
41
|
+
"""
|
|
42
|
+
# Compute distances to all training points
|
|
43
|
+
distances = []
|
|
44
|
+
for i in range(len(X_train)):
|
|
45
|
+
dist = euclidean_distance(x_test, X_train[i])
|
|
46
|
+
distances.append((dist, y_train[i]))
|
|
47
|
+
|
|
48
|
+
# Sort by distance and take k nearest
|
|
49
|
+
distances.sort()
|
|
50
|
+
k_nearest = distances[:k]
|
|
51
|
+
|
|
52
|
+
# Majority vote
|
|
53
|
+
votes = {}
|
|
54
|
+
for _, label in k_nearest:
|
|
55
|
+
votes[label] = votes.get(label, 0) + 1
|
|
56
|
+
|
|
57
|
+
return max(votes, key=votes.get)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def knn_predict_batch(
|
|
61
|
+
X_test: List[List[float]],
|
|
62
|
+
X_train: List[List[float]],
|
|
63
|
+
y_train: List[int],
|
|
64
|
+
k: int = 3
|
|
65
|
+
) -> List[int]:
|
|
66
|
+
"""
|
|
67
|
+
Predict classes for multiple test points.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
X_test: list of test feature vectors
|
|
71
|
+
X_train: list of training feature vectors
|
|
72
|
+
y_train: list of training labels
|
|
73
|
+
k: number of neighbors
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
list of predicted labels
|
|
77
|
+
"""
|
|
78
|
+
return [knn_predict(X_test[i], X_train, y_train, k) for i in range(len(X_test))]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == "__main__":
|
|
82
|
+
random.seed(42)
|
|
83
|
+
|
|
84
|
+
# Generate synthetic classification data (two classes)
|
|
85
|
+
n_train = 50
|
|
86
|
+
X_train = []
|
|
87
|
+
y_train = []
|
|
88
|
+
|
|
89
|
+
# Class 0: around (0, 0)
|
|
90
|
+
for _ in range(n_train // 2):
|
|
91
|
+
X_train.append([random.gauss(0, 1), random.gauss(0, 1)])
|
|
92
|
+
y_train.append(0)
|
|
93
|
+
|
|
94
|
+
# Class 1: around (5, 5)
|
|
95
|
+
for _ in range(n_train // 2):
|
|
96
|
+
X_train.append([random.gauss(5, 1), random.gauss(5, 1)])
|
|
97
|
+
y_train.append(1)
|
|
98
|
+
|
|
99
|
+
# Generate test data
|
|
100
|
+
n_test = 20
|
|
101
|
+
X_test = []
|
|
102
|
+
y_test = []
|
|
103
|
+
|
|
104
|
+
for _ in range(n_test // 2):
|
|
105
|
+
X_test.append([random.gauss(0, 0.8), random.gauss(0, 0.8)])
|
|
106
|
+
y_test.append(0)
|
|
107
|
+
|
|
108
|
+
for _ in range(n_test // 2):
|
|
109
|
+
X_test.append([random.gauss(5, 0.8), random.gauss(5, 0.8)])
|
|
110
|
+
y_test.append(1)
|
|
111
|
+
|
|
112
|
+
# Predict and check accuracy
|
|
113
|
+
preds = knn_predict_batch(X_test, X_train, y_train, k=5)
|
|
114
|
+
accuracy = sum(preds[i] == y_test[i] for i in range(n_test)) / n_test
|
|
115
|
+
|
|
116
|
+
assert accuracy >= 0.8, f"Accuracy = {accuracy} is too low"
|
|
117
|
+
|
|
118
|
+
print(f"KNN_CLASSIFIER PASS: accuracy = {accuracy:.3f}, k = 5")
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Linear Regression via Batch Gradient Descent (from scratch).
|
|
3
|
+
|
|
4
|
+
Core idea: Given labeled training data (X, y), fit a linear model y = Xw + b
|
|
5
|
+
by iteratively updating weights w and bias b to minimize mean squared error.
|
|
6
|
+
Gradient descent computes ∂loss/∂w and ∂loss/∂b each iteration and moves opposite
|
|
7
|
+
the gradient to reduce loss.
|
|
8
|
+
|
|
9
|
+
When to use: Continuous target prediction; interpretable model; small to medium datasets.
|
|
10
|
+
"""
|
|
11
|
+
# △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
|
|
12
|
+
#
|
|
13
|
+
_AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
|
|
14
|
+
|
|
15
|
+
import random
|
|
16
|
+
import math
|
|
17
|
+
from typing import List, Tuple
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def mean(values: List[float]) -> float:
|
|
21
|
+
"""Compute arithmetic mean."""
|
|
22
|
+
return sum(values) / len(values) if values else 0.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def variance(values: List[float]) -> float:
|
|
26
|
+
"""Compute sample variance."""
|
|
27
|
+
if not values:
|
|
28
|
+
return 0.0
|
|
29
|
+
m = mean(values)
|
|
30
|
+
return sum((v - m) ** 2 for v in values) / len(values)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def linear_regression_gd(
|
|
34
|
+
X: List[List[float]],
|
|
35
|
+
y: List[float],
|
|
36
|
+
learning_rate: float = 0.01,
|
|
37
|
+
iterations: int = 100
|
|
38
|
+
) -> Tuple[List[float], float]:
|
|
39
|
+
"""
|
|
40
|
+
Fit a linear regression model using batch gradient descent.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
X: list of feature vectors (each row is a sample)
|
|
44
|
+
y: list of target values
|
|
45
|
+
learning_rate: step size for gradient descent
|
|
46
|
+
iterations: number of update steps
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
(weights, bias): fitted parameters
|
|
50
|
+
"""
|
|
51
|
+
n_samples = len(X)
|
|
52
|
+
n_features = len(X[0]) if X else 0
|
|
53
|
+
|
|
54
|
+
# Initialize weights and bias
|
|
55
|
+
weights = [0.0] * n_features
|
|
56
|
+
bias = 0.0
|
|
57
|
+
|
|
58
|
+
loss_history = []
|
|
59
|
+
|
|
60
|
+
for _ in range(iterations):
|
|
61
|
+
# Compute predictions
|
|
62
|
+
predictions = []
|
|
63
|
+
for i in range(n_samples):
|
|
64
|
+
pred = bias + sum(weights[j] * X[i][j] for j in range(n_features))
|
|
65
|
+
predictions.append(pred)
|
|
66
|
+
|
|
67
|
+
# Compute MSE loss
|
|
68
|
+
errors = [predictions[i] - y[i] for i in range(n_samples)]
|
|
69
|
+
mse = mean([e ** 2 for e in errors])
|
|
70
|
+
loss_history.append(mse)
|
|
71
|
+
|
|
72
|
+
# Compute gradients (batch)
|
|
73
|
+
dw = [sum(errors[i] * X[i][j] for i in range(n_samples)) / n_samples
|
|
74
|
+
for j in range(n_features)]
|
|
75
|
+
db = sum(errors) / n_samples
|
|
76
|
+
|
|
77
|
+
# Update parameters
|
|
78
|
+
weights = [weights[j] - learning_rate * dw[j] for j in range(n_features)]
|
|
79
|
+
bias = bias - learning_rate * db
|
|
80
|
+
|
|
81
|
+
return weights, bias
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
random.seed(42)
|
|
86
|
+
|
|
87
|
+
# Generate synthetic regression data: y ≈ 2*x1 + 3*x2 + noise
|
|
88
|
+
n_samples = 30
|
|
89
|
+
X = [[random.uniform(-5, 5), random.uniform(-5, 5)] for _ in range(n_samples)]
|
|
90
|
+
y = [2.0 * X[i][0] + 3.0 * X[i][1] + random.gauss(0, 0.5) for i in range(n_samples)]
|
|
91
|
+
|
|
92
|
+
# Train model
|
|
93
|
+
weights, bias = linear_regression_gd(X, y, learning_rate=0.01, iterations=200)
|
|
94
|
+
|
|
95
|
+
# Test: compute R² on training data
|
|
96
|
+
predictions = [bias + sum(weights[j] * X[i][j] for j in range(2))
|
|
97
|
+
for i in range(n_samples)]
|
|
98
|
+
ss_res = sum((predictions[i] - y[i]) ** 2 for i in range(n_samples))
|
|
99
|
+
ss_tot = sum((y[i] - mean(y)) ** 2 for i in range(n_samples))
|
|
100
|
+
r2 = 1.0 - (ss_res / ss_tot) if ss_tot > 0 else 0.0
|
|
101
|
+
|
|
102
|
+
assert r2 > 0.8, f"R² = {r2} is too low"
|
|
103
|
+
assert abs(weights[0] - 2.0) < 0.5, f"w[0] = {weights[0]}, expected ~2.0"
|
|
104
|
+
assert abs(weights[1] - 3.0) < 0.5, f"w[1] = {weights[1]}, expected ~3.0"
|
|
105
|
+
|
|
106
|
+
print(f"LINEAR_REGRESSION_GD PASS: R² = {r2:.3f}, weights = {[f'{w:.2f}' for w in weights]}")
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Binary Logistic Regression via Gradient Descent (from scratch).
|
|
3
|
+
|
|
4
|
+
Core idea: Model binary classification via sigmoid(z) = 1 / (1 + e^-z).
|
|
5
|
+
Given labeled data (X, y) where y ∈ {0, 1}, fit weights w and bias b
|
|
6
|
+
by minimizing binary cross-entropy loss via gradient descent.
|
|
7
|
+
|
|
8
|
+
When to use: Binary classification; interpretable probabilities; small to medium data.
|
|
9
|
+
"""
|
|
10
|
+
# △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
|
|
11
|
+
#
|
|
12
|
+
_AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
|
|
13
|
+
|
|
14
|
+
import random
|
|
15
|
+
import math
|
|
16
|
+
from typing import List, Tuple
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AuraInputError(ValueError):
|
|
22
|
+
"""All input-contract violations, reported together (accumulate-then-raise)."""
|
|
23
|
+
def __init__(self, violations):
|
|
24
|
+
self.violations = violations
|
|
25
|
+
super().__init__("input contract violated:\n " + "\n ".join(violations))
|
|
26
|
+
|
|
27
|
+
def _aura_validate_sigmoid(z):
|
|
28
|
+
v = []
|
|
29
|
+
if isinstance(z, (int, float)) and not math.isfinite(z):
|
|
30
|
+
v.append(f"AURA-E008: z must be finite, got {z}")
|
|
31
|
+
if v:
|
|
32
|
+
raise AuraInputError(v)
|
|
33
|
+
|
|
34
|
+
def sigmoid(z: float) -> float:
|
|
35
|
+
"""Compute sigmoid(z) = 1 / (1 + exp(-z))."""
|
|
36
|
+
_aura_validate_sigmoid(z)
|
|
37
|
+
if z > 100: # Prevent overflow
|
|
38
|
+
return 1.0
|
|
39
|
+
if z < -100:
|
|
40
|
+
return 0.0
|
|
41
|
+
return 1.0 / (1.0 + math.exp(-z))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def logistic_regression_fit(
|
|
45
|
+
X: List[List[float]],
|
|
46
|
+
y: List[int],
|
|
47
|
+
learning_rate: float = 0.01,
|
|
48
|
+
iterations: int = 100
|
|
49
|
+
) -> Tuple[List[float], float]:
|
|
50
|
+
"""
|
|
51
|
+
Fit a logistic regression model using gradient descent.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
X: list of feature vectors
|
|
55
|
+
y: list of binary labels (0 or 1)
|
|
56
|
+
learning_rate: step size for gradient descent
|
|
57
|
+
iterations: number of update steps
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
(weights, bias): fitted parameters
|
|
61
|
+
"""
|
|
62
|
+
n_samples = len(X)
|
|
63
|
+
n_features = len(X[0]) if X else 0
|
|
64
|
+
|
|
65
|
+
# Initialize weights and bias
|
|
66
|
+
weights = [0.0] * n_features
|
|
67
|
+
bias = 0.0
|
|
68
|
+
|
|
69
|
+
for _ in range(iterations):
|
|
70
|
+
# Compute predictions (probabilities)
|
|
71
|
+
predictions = []
|
|
72
|
+
for i in range(n_samples):
|
|
73
|
+
z = bias + sum(weights[j] * X[i][j] for j in range(n_features))
|
|
74
|
+
predictions.append(sigmoid(z))
|
|
75
|
+
|
|
76
|
+
# Compute gradients (binary cross-entropy)
|
|
77
|
+
errors = [predictions[i] - y[i] for i in range(n_samples)]
|
|
78
|
+
dw = [sum(errors[i] * X[i][j] for i in range(n_samples)) / n_samples
|
|
79
|
+
for j in range(n_features)]
|
|
80
|
+
db = sum(errors) / n_samples
|
|
81
|
+
|
|
82
|
+
# Update parameters
|
|
83
|
+
weights = [weights[j] - learning_rate * dw[j] for j in range(n_features)]
|
|
84
|
+
bias = bias - learning_rate * db
|
|
85
|
+
|
|
86
|
+
return weights, bias
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def logistic_regression_predict(
|
|
90
|
+
X: List[List[float]],
|
|
91
|
+
weights: List[float],
|
|
92
|
+
bias: float,
|
|
93
|
+
threshold: float = 0.5
|
|
94
|
+
) -> List[int]:
|
|
95
|
+
"""
|
|
96
|
+
Predict binary labels for samples X.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
X: list of feature vectors
|
|
100
|
+
weights: fitted weights
|
|
101
|
+
bias: fitted bias
|
|
102
|
+
threshold: probability threshold for class 1
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
list of predicted labels (0 or 1)
|
|
106
|
+
"""
|
|
107
|
+
predictions = []
|
|
108
|
+
for i in range(len(X)):
|
|
109
|
+
z = bias + sum(weights[j] * X[i][j] for j in range(len(weights)))
|
|
110
|
+
prob = sigmoid(z)
|
|
111
|
+
predictions.append(1 if prob >= threshold else 0)
|
|
112
|
+
return predictions
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
if __name__ == "__main__":
|
|
116
|
+
random.seed(42)
|
|
117
|
+
|
|
118
|
+
# Generate synthetic binary classification data
|
|
119
|
+
# Class 0: centered around (-2, -2), Class 1: centered around (2, 2)
|
|
120
|
+
n_samples = 40
|
|
121
|
+
X = []
|
|
122
|
+
y = []
|
|
123
|
+
|
|
124
|
+
for _ in range(n_samples // 2):
|
|
125
|
+
X.append([random.gauss(-2, 1), random.gauss(-2, 1)])
|
|
126
|
+
y.append(0)
|
|
127
|
+
|
|
128
|
+
for _ in range(n_samples // 2):
|
|
129
|
+
X.append([random.gauss(2, 1), random.gauss(2, 1)])
|
|
130
|
+
y.append(1)
|
|
131
|
+
|
|
132
|
+
# Fit model
|
|
133
|
+
weights, bias = logistic_regression_fit(X, y, learning_rate=0.1, iterations=100)
|
|
134
|
+
|
|
135
|
+
# Predict and check accuracy
|
|
136
|
+
preds = logistic_regression_predict(X, weights, bias)
|
|
137
|
+
accuracy = sum(preds[i] == y[i] for i in range(n_samples)) / n_samples
|
|
138
|
+
|
|
139
|
+
assert accuracy >= 0.85, f"Accuracy = {accuracy} is too low"
|
|
140
|
+
|
|
141
|
+
print(f"LOGISTIC_REGRESSION PASS: accuracy = {accuracy:.3f}, weights = {[f'{w:.2f}' for w in weights]}")
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Multinomial Naive Bayes for Text Classification (from scratch).
|
|
3
|
+
|
|
4
|
+
Core idea: Represent documents as word-frequency vectors. Assume features
|
|
5
|
+
(word counts) are conditionally independent given class. Compute P(class|doc)
|
|
6
|
+
using Bayes' rule and word probabilities per class (with Laplace smoothing).
|
|
7
|
+
|
|
8
|
+
When to use: Text classification (spam/ham, sentiment); fast training; baseline.
|
|
9
|
+
"""
|
|
10
|
+
# △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
|
|
11
|
+
#
|
|
12
|
+
_AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
|
|
13
|
+
|
|
14
|
+
import random
|
|
15
|
+
import math
|
|
16
|
+
from collections import defaultdict
|
|
17
|
+
from typing import List, Tuple, Dict
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def naive_bayes_train(
|
|
21
|
+
texts: List[List[str]],
|
|
22
|
+
labels: List[int]
|
|
23
|
+
) -> Tuple[Dict[int, float], Dict[int, Dict[str, float]]]:
|
|
24
|
+
"""
|
|
25
|
+
Train a Multinomial Naive Bayes classifier on tokenized text.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
texts: list of documents, each a list of word tokens
|
|
29
|
+
labels: list of class labels (0 or 1)
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
(class_priors, word_probs): priors and conditional word probabilities
|
|
33
|
+
"""
|
|
34
|
+
n_docs = len(texts)
|
|
35
|
+
classes = set(labels)
|
|
36
|
+
|
|
37
|
+
# Count class occurrences
|
|
38
|
+
class_counts = {c: 0 for c in classes}
|
|
39
|
+
for label in labels:
|
|
40
|
+
class_counts[label] += 1
|
|
41
|
+
|
|
42
|
+
# Compute class priors
|
|
43
|
+
class_priors = {c: class_counts[c] / n_docs for c in classes}
|
|
44
|
+
|
|
45
|
+
# Build word frequency tables per class (with Laplace smoothing)
|
|
46
|
+
word_counts = {c: defaultdict(int) for c in classes}
|
|
47
|
+
total_words = {c: 0 for c in classes}
|
|
48
|
+
|
|
49
|
+
for i in range(n_docs):
|
|
50
|
+
label = labels[i]
|
|
51
|
+
for word in texts[i]:
|
|
52
|
+
word_counts[label][word] += 1
|
|
53
|
+
total_words[label] += 1
|
|
54
|
+
|
|
55
|
+
# Compute word probabilities per class (Laplace smoothing: add 1)
|
|
56
|
+
vocab_size = len(set(w for text in texts for w in text))
|
|
57
|
+
word_probs = {}
|
|
58
|
+
|
|
59
|
+
for c in classes:
|
|
60
|
+
word_probs[c] = {}
|
|
61
|
+
for word in set(w for text in texts for w in text):
|
|
62
|
+
word_probs[c][word] = (word_counts[c][word] + 1) / (total_words[c] + vocab_size)
|
|
63
|
+
|
|
64
|
+
return class_priors, word_probs
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def naive_bayes_predict(
|
|
68
|
+
text: List[str],
|
|
69
|
+
class_priors: Dict[int, float],
|
|
70
|
+
word_probs: Dict[int, Dict[str, float]]
|
|
71
|
+
) -> int:
|
|
72
|
+
"""
|
|
73
|
+
Predict the class of a document using Naive Bayes.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
text: document as a list of word tokens
|
|
77
|
+
class_priors: class prior probabilities
|
|
78
|
+
word_probs: word probability tables per class
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
predicted class label
|
|
82
|
+
"""
|
|
83
|
+
best_class = None
|
|
84
|
+
best_score = -float('inf')
|
|
85
|
+
|
|
86
|
+
for c in class_priors:
|
|
87
|
+
# Start with log(prior)
|
|
88
|
+
score = math.log(class_priors[c])
|
|
89
|
+
|
|
90
|
+
# Add log of word probabilities
|
|
91
|
+
for word in text:
|
|
92
|
+
if word in word_probs[c]:
|
|
93
|
+
score += math.log(word_probs[c][word])
|
|
94
|
+
else:
|
|
95
|
+
# Unseen word: use Laplace smoothing
|
|
96
|
+
vocab_size = len(word_probs[c])
|
|
97
|
+
score += math.log(1.0 / (sum(len(wp) for wp in word_probs.values()) + vocab_size))
|
|
98
|
+
|
|
99
|
+
if score > best_score:
|
|
100
|
+
best_score = score
|
|
101
|
+
best_class = c
|
|
102
|
+
|
|
103
|
+
return best_class
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == "__main__":
|
|
107
|
+
random.seed(42)
|
|
108
|
+
|
|
109
|
+
# Simple synthetic text classification: spam vs ham
|
|
110
|
+
# Spam: contains "cheap", "free", "buy"; Ham: contains "meeting", "report", "data"
|
|
111
|
+
spam_words = ["cheap", "free", "buy", "offer", "click"]
|
|
112
|
+
ham_words = ["meeting", "report", "data", "project", "deadline"]
|
|
113
|
+
|
|
114
|
+
texts = []
|
|
115
|
+
labels = []
|
|
116
|
+
|
|
117
|
+
# Generate spam documents
|
|
118
|
+
for _ in range(10):
|
|
119
|
+
doc = [random.choice(spam_words) for _ in range(random.randint(3, 5))]
|
|
120
|
+
texts.append(doc)
|
|
121
|
+
labels.append(1) # spam
|
|
122
|
+
|
|
123
|
+
# Generate ham documents
|
|
124
|
+
for _ in range(10):
|
|
125
|
+
doc = [random.choice(ham_words) for _ in range(random.randint(3, 5))]
|
|
126
|
+
texts.append(doc)
|
|
127
|
+
labels.append(0) # ham
|
|
128
|
+
|
|
129
|
+
# Train
|
|
130
|
+
class_priors, word_probs = naive_bayes_train(texts, labels)
|
|
131
|
+
|
|
132
|
+
# Test on training data (sanity check)
|
|
133
|
+
correct = 0
|
|
134
|
+
for i in range(len(texts)):
|
|
135
|
+
pred = naive_bayes_predict(texts[i], class_priors, word_probs)
|
|
136
|
+
if pred == labels[i]:
|
|
137
|
+
correct += 1
|
|
138
|
+
|
|
139
|
+
accuracy = correct / len(texts)
|
|
140
|
+
assert accuracy >= 0.9, f"Accuracy = {accuracy} is too low"
|
|
141
|
+
|
|
142
|
+
# Test on new example
|
|
143
|
+
test_spam = ["cheap", "free", "buy"]
|
|
144
|
+
test_ham = ["meeting", "data", "report"]
|
|
145
|
+
|
|
146
|
+
pred_spam = naive_bayes_predict(test_spam, class_priors, word_probs)
|
|
147
|
+
pred_ham = naive_bayes_predict(test_ham, class_priors, word_probs)
|
|
148
|
+
|
|
149
|
+
assert pred_spam == 1, "Failed to classify spam"
|
|
150
|
+
assert pred_ham == 0, "Failed to classify ham"
|
|
151
|
+
|
|
152
|
+
print(f"NAIVE_BAYES_TEXT PASS: accuracy = {accuracy:.3f}, test_spam → {pred_spam}, test_ham → {pred_ham}")
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Perceptron Learning Algorithm (from scratch).
|
|
3
|
+
|
|
4
|
+
Core idea: A linear classifier for linearly separable data. The perceptron
|
|
5
|
+
iteratively updates weights on misclassified samples using the rule:
|
|
6
|
+
w ← w + y_i * x_i for each error. Converges in finite steps on separable data.
|
|
7
|
+
|
|
8
|
+
When to use: Binary classification on linearly separable data; fast training.
|
|
9
|
+
"""
|
|
10
|
+
# △ AURA Pattern Library — © Reality Optimizer ⟦AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO⟧
|
|
11
|
+
#
|
|
12
|
+
_AURA_MARK = "AE1.PMRGG3ZCHIRFEZLBNRUXI6JAJ5YHI2LNNF5GK4RCFQRG2IR2EJAUKTKBKJFTCIRMEJXCEORCGARCYITQNFSCEORCEIWCE5DNEI5CEQKVKJASAUDBOR2GK4TOEBGGSYTSMFZHSIRMEJ3CEORRPWYSJPXO"
|
|
13
|
+
|
|
14
|
+
import random
|
|
15
|
+
from typing import List, Tuple
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def perceptron_fit(
|
|
19
|
+
X: List[List[float]],
|
|
20
|
+
y: List[int],
|
|
21
|
+
learning_rate: float = 1.0,
|
|
22
|
+
max_iterations: int = 100
|
|
23
|
+
) -> Tuple[List[float], float]:
|
|
24
|
+
"""
|
|
25
|
+
Fit a perceptron using the learning rule.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
X: list of feature vectors
|
|
29
|
+
y: list of binary labels (must be -1 or 1, or converted from 0/1)
|
|
30
|
+
learning_rate: step size for weight updates (usually 1.0)
|
|
31
|
+
max_iterations: maximum passes over data
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
(weights, bias): fitted parameters
|
|
35
|
+
"""
|
|
36
|
+
n_samples = len(X)
|
|
37
|
+
n_features = len(X[0]) if X else 0
|
|
38
|
+
|
|
39
|
+
# Convert labels to {-1, 1} if needed
|
|
40
|
+
y_labels = [2 * label - 1 if label in (0, 1) else label for label in y]
|
|
41
|
+
|
|
42
|
+
# Initialize weights and bias
|
|
43
|
+
weights = [0.0] * n_features
|
|
44
|
+
bias = 0.0
|
|
45
|
+
|
|
46
|
+
for _ in range(max_iterations):
|
|
47
|
+
num_errors = 0
|
|
48
|
+
for i in range(n_samples):
|
|
49
|
+
# Compute prediction
|
|
50
|
+
z = bias + sum(weights[j] * X[i][j] for j in range(n_features))
|
|
51
|
+
pred = 1 if z >= 0 else -1
|
|
52
|
+
|
|
53
|
+
# Update on error
|
|
54
|
+
if pred != y_labels[i]:
|
|
55
|
+
error = y_labels[i] - pred
|
|
56
|
+
weights = [weights[j] + learning_rate * error * X[i][j] / 2.0
|
|
57
|
+
for j in range(n_features)]
|
|
58
|
+
bias = bias + learning_rate * error / 2.0
|
|
59
|
+
num_errors += 1
|
|
60
|
+
|
|
61
|
+
# Early stop if no errors
|
|
62
|
+
if num_errors == 0:
|
|
63
|
+
break
|
|
64
|
+
|
|
65
|
+
return weights, bias
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def perceptron_predict(
|
|
69
|
+
X: List[List[float]],
|
|
70
|
+
weights: List[float],
|
|
71
|
+
bias: float
|
|
72
|
+
) -> List[int]:
|
|
73
|
+
"""
|
|
74
|
+
Predict binary labels (0 or 1) for samples X.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
X: list of feature vectors
|
|
78
|
+
weights: fitted weights
|
|
79
|
+
bias: fitted bias
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
list of predicted labels (0 or 1)
|
|
83
|
+
"""
|
|
84
|
+
predictions = []
|
|
85
|
+
for i in range(len(X)):
|
|
86
|
+
z = bias + sum(weights[j] * X[i][j] for j in range(len(weights)))
|
|
87
|
+
pred = 1 if z >= 0 else 0
|
|
88
|
+
predictions.append(pred)
|
|
89
|
+
return predictions
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
if __name__ == "__main__":
|
|
93
|
+
random.seed(42)
|
|
94
|
+
|
|
95
|
+
# Generate linearly separable data
|
|
96
|
+
n_samples = 40
|
|
97
|
+
X = []
|
|
98
|
+
y = []
|
|
99
|
+
|
|
100
|
+
# Class 0: mostly below the line y = x
|
|
101
|
+
for _ in range(n_samples // 2):
|
|
102
|
+
x1 = random.uniform(-3, 3)
|
|
103
|
+
x2 = x1 - random.uniform(0.5, 2.5)
|
|
104
|
+
X.append([x1, x2])
|
|
105
|
+
y.append(0)
|
|
106
|
+
|
|
107
|
+
# Class 1: mostly above the line y = x
|
|
108
|
+
for _ in range(n_samples // 2):
|
|
109
|
+
x1 = random.uniform(-3, 3)
|
|
110
|
+
x2 = x1 + random.uniform(0.5, 2.5)
|
|
111
|
+
X.append([x1, x2])
|
|
112
|
+
y.append(1)
|
|
113
|
+
|
|
114
|
+
# Fit perceptron
|
|
115
|
+
weights, bias = perceptron_fit(X, y, learning_rate=1.0, max_iterations=50)
|
|
116
|
+
|
|
117
|
+
# Test accuracy
|
|
118
|
+
preds = perceptron_predict(X, weights, bias)
|
|
119
|
+
accuracy = sum(preds[i] == y[i] for i in range(n_samples)) / n_samples
|
|
120
|
+
|
|
121
|
+
assert accuracy >= 0.9, f"Accuracy = {accuracy} is too low on linearly separable data"
|
|
122
|
+
|
|
123
|
+
print(f"PERCEPTRON PASS: accuracy = {accuracy:.3f}, weights = {[f'{w:.2f}' for w in weights]}")
|