ml-finance-python
python scripts for finance machine learning
git clone https://9o.is/git/ml-finance-python.git
perceptron.py
(1253B)
1 from __future__ import print_function
2 from sklearn import datasets
3 import numpy as np
4
5 # Import helper functions
6 from mlfromscratch.utils import train_test_split, normalize, to_categorical, accuracy_score
7 from mlfromscratch.deep_learning.activation_functions import Sigmoid
8 from mlfromscratch.deep_learning.loss_functions import CrossEntropy
9 from mlfromscratch.utils import Plot
10 from mlfromscratch.supervised_learning import Perceptron
11
12
13 def main():
14 data = datasets.load_digits()
15 X = normalize(data.data)
16 y = data.target
17
18 # One-hot encoding of nominal y-values
19 y = to_categorical(y)
20
21 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, seed=1)
22
23 # Perceptron
24 clf = Perceptron(n_iterations=5000,
25 learning_rate=0.001,
26 loss=CrossEntropy,
27 activation_function=Sigmoid)
28 clf.fit(X_train, y_train)
29
30 y_pred = np.argmax(clf.predict(X_test), axis=1)
31 y_test = np.argmax(y_test, axis=1)
32
33 accuracy = accuracy_score(y_test, y_pred)
34
35 print ("Accuracy:", accuracy)
36
37 # Reduce dimension to two using PCA and plot the results
38 Plot().plot_in_2d(X_test, y_pred, title="Perceptron", accuracy=accuracy, legend_labels=np.unique(y))
39
40
41 if __name__ == "__main__":
42 main()