Advertisement
makispaiktis

ML - Lab 4 - ANN with training and testing error

Oct 19th, 2022 (edited)
1,132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import sklearn
  5. from math import floor
  6.  
  7. # Load the csv file
  8. alldata = pd.read_csv("./alldata.txt")
  9. N = len(alldata)
  10. stop = floor(0.75*N)
  11. xtrain = alldata.loc[0:stop-1, ["X1", "X2"]]
  12. ytrain = alldata.loc[0:stop-1, "y"]
  13. xtest = alldata.loc[stop:N, ["X1", "X2"]]
  14. ytest = alldata.loc[stop:N, "y"]
  15.  
  16. # Scatter the training data
  17. plt.scatter(xtrain[ytrain == 1].X1, xtrain[ytrain == 1].X2, c="blue", marker="o", label="1")
  18. plt.scatter(xtrain[ytrain == 2].X1, xtrain[ytrain == 2].X2, c="red", marker="+", label="2")
  19. plt.title("Initial points and their class")
  20. plt.legend()
  21. plt.show()
  22.  
  23.  
  24. # ANN Creation
  25. # 2 hidden layers, 20 hidden nodes/layer, max_iter = 10000
  26. from sklearn.neural_network import MLPRegressor
  27. clf = MLPRegressor(hidden_layer_sizes=(2, 2), tol=0.01)
  28. clf = clf.fit(xtrain, ytrain)
  29.  
  30. # Training Error - Compare 'pred' with 'ytrain'
  31. pred = clf.predict(xtrain)
  32. trainingError = [(t - p) for (t, p) in zip(ytrain, pred)]
  33. MA_TrE = np.mean(np.abs(trainingError))
  34. print("Training Error = MA_TrE = " + str(MA_TrE))
  35. plt.hist(trainingError, range=(-1, 1), rwidth=0.5)
  36. plt.title("Training Error")
  37. plt.show()
  38.  
  39. # Testing Error - Compare 'pred' with 'ytest'
  40. pred = clf.predict(xtest)
  41. testingError = [(t - p) for (t, p) in zip(ytest, pred)]
  42. MA_TeE = np.mean(np.abs(testingError))
  43. print("Testing Error = MA_TeE = " + str(MA_TeE))
  44. plt.hist(testingError, range=(-1, 1), rwidth=0.5)
  45. plt.title("Testing Error")
  46. plt.show()
  47.  
  48. print(trainingError)
  49. print(testingError)
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement