Spaces:
Sleeping
Sleeping
Jensen Holm
commited on
Commit
•
284dbf2
1
Parent(s):
adc3f91
adding example program 'example.py'
Browse files- example.py +66 -0
example.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sklearn import datasets
|
2 |
+
from sklearn.preprocessing import OneHotEncoder
|
3 |
+
from sklearn.model_selection import train_test_split
|
4 |
+
from sklearn.metrics import accuracy_score, precision_score, recall_score
|
5 |
+
import numpy as np
|
6 |
+
from numpyneuron import (
|
7 |
+
NN,
|
8 |
+
Relu,
|
9 |
+
Sigmoid,
|
10 |
+
CrossEntropyWithLogits,
|
11 |
+
)
|
12 |
+
|
13 |
+
|
14 |
+
RANDOM_SEED = 2
|
15 |
+
|
16 |
+
|
17 |
+
def _preprocess_digits(
|
18 |
+
seed: int,
|
19 |
+
) -> tuple[np.ndarray, ...]:
|
20 |
+
digits = datasets.load_digits(as_frame=False)
|
21 |
+
n_samples = len(digits.images)
|
22 |
+
data = digits.images.reshape((n_samples, -1))
|
23 |
+
y = OneHotEncoder().fit_transform(digits.target.reshape(-1, 1)).toarray()
|
24 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
25 |
+
data,
|
26 |
+
y,
|
27 |
+
test_size=0.2,
|
28 |
+
random_state=seed,
|
29 |
+
)
|
30 |
+
return X_train, X_test, y_train, y_test
|
31 |
+
|
32 |
+
|
33 |
+
def train_nn_classifier() -> None:
|
34 |
+
X_train, X_test, y_train, y_test = _preprocess_digits(seed=RANDOM_SEED)
|
35 |
+
|
36 |
+
nn_classifier = NN(
|
37 |
+
epochs=2_000,
|
38 |
+
hidden_size=16,
|
39 |
+
batch_size=1,
|
40 |
+
learning_rate=0.01,
|
41 |
+
loss_fn=CrossEntropyWithLogits(),
|
42 |
+
hidden_activation_fn=Relu(),
|
43 |
+
output_activation_fn=Sigmoid(),
|
44 |
+
input_size=64, # 8x8 pixel grid images
|
45 |
+
output_size=10, # digits 0-9
|
46 |
+
seed=2,
|
47 |
+
)
|
48 |
+
|
49 |
+
nn_classifier.train(
|
50 |
+
X_train=X_train,
|
51 |
+
y_train=y_train,
|
52 |
+
)
|
53 |
+
|
54 |
+
pred = nn_classifier.predict(X_test=X_test)
|
55 |
+
|
56 |
+
pred = np.argmax(pred, axis=1)
|
57 |
+
y_test = np.argmax(y_test, axis=1)
|
58 |
+
|
59 |
+
accuracy = accuracy_score(y_true=y_test, y_pred=pred)
|
60 |
+
|
61 |
+
print(f"accuracy on validation set: {accuracy:.4f}")
|
62 |
+
|
63 |
+
|
64 |
+
if __name__ == "__main__":
|
65 |
+
train_nn_classifier()
|
66 |
+
|