ml-finance-python

python scripts for finance machine learning

git clone https://9o.is/git/ml-finance-python.git

k_nearest_neighbors.py

(851B)


      1 from __future__ import print_function
      2 import numpy as np
      3 import matplotlib.pyplot as plt
      4 from sklearn import datasets
      5 
      6 from mlfromscratch.utils import train_test_split, normalize, accuracy_score
      7 from mlfromscratch.utils import euclidean_distance, Plot
      8 from mlfromscratch.supervised_learning import KNN
      9 
     10 def main():
     11     data = datasets.load_iris()
     12     X = normalize(data.data)
     13     y = data.target
     14     X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
     15 
     16     clf = KNN(k=5)
     17     y_pred = clf.predict(X_test, X_train, y_train)
     18     
     19     accuracy = accuracy_score(y_test, y_pred)
     20 
     21     print ("Accuracy:", accuracy)
     22 
     23     # Reduce dimensions to 2d using pca and plot the results
     24     Plot().plot_in_2d(X_test, y_pred, title="K Nearest Neighbors", accuracy=accuracy, legend_labels=data.target_names)
     25 
     26 
     27 if __name__ == "__main__":
     28     main()