LostInMyThoughts137

Assignment3 - Single Layer Perceptron Leaky Relu

Jun 22nd, 2021 (edited)
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.05 KB | None | 0 0
  1. """
  2. @author: chrispellegrino
  3. Class: CS 767
  4. Assignment: 3
  5. Using single layer Perceptron neural network which is connected to “Leaky ReLU”
  6. activation function with (a=0.05) to predict salary of baseball players using the data set
  7. “Assignment_3_Hitters.csv”.
  8. Use batch gradient descent to adjust the weights and predict salary
  9. with L2 regularization and Lasso with lambda = 0.01 and 10.
  10. (i) Input data is Assignment_3_Hitters.csv data, which is available in Blackboard.
  11. (ii)    Write a code and build a single layer Perceptron with Leaky ReLU activation function as follows.
  12. (iii)   Use all the features to predict Salary.
  13. (iv)    Assume anything that is needed to solve the problem. Make sure to state your assumptions.
  14. a. (30 points) Choose a learning rate. Show details of your work and all the steps that you take to choose a suitable learning rate.
  15. b. (20 points) Plot total cost (MSE - Mean Square Error + regularization cost) as a function of iterations for both regularizations.
  16. c. (50 points) Create a table of the weights and show the final weights of the solution
  17. i. Without regularization
  18. ii. With L2 regularization and two different lambdas
  19. iii. With Lasso regularization and two different lambdas
  20. """
  21.  
  22. import pandas as pd
  23. import numpy as np
  24. import matplotlib.pyplot as plt
  25.  
  26. hitters = pd.read_csv('/Users/chrispellegrino/Desktop/CS 767 Machine Learning/Assignments/Assignment 3/Assignment_3_Hitters.csv')
  27. hitters = hitters.dropna()
  28. print(hitters)
  29. print(hitters.dtypes)
  30.  
  31. #converts column to category so python knows each unique value is category
  32. hitters['League'] = hitters.League.astype('category').cat.codes
  33. hitters['NewLeague'] = hitters.NewLeague.astype('category').cat.codes
  34. hitters['Division'] = hitters.Division.astype('category').cat.codes
  35.  
  36. #iloc means accessing by number, and loc is by name
  37. x = hitters.loc[:, ['AtBat', 'Hits', 'HmRun', 'Runs', 'RBI', 'Walks', 'Years',
  38.        'CAtBat', 'CHits', 'CHmRun', 'CRuns', 'CRBI', 'CWalks', 'League',
  39.        'Division', 'PutOuts', 'Assists', 'Errors', 'NewLeague']]
  40.  
  41. at_bat = hitters.loc[:, ['AtBat']]
  42. hits = hitters.loc[:, ['Hits']]
  43. home_runs = hitters.loc[:, ['HmRun']]
  44. runs = hitters.loc[:, ['Runs']]
  45. rbi = hitters.loc[:, ['RBI']]
  46. walks = hitters.loc[:, ['Walks']]
  47. years = hitters.loc[:, ['Years']]
  48. catbat = hitters.loc[:, ['CAtBat']]
  49. chits = hitters.loc[:, ['CHits']]
  50. chmrun = hitters.loc[:, ['CHmRun']]
  51. cruns = hitters.loc[:, ['CRuns']]
  52. crbi = hitters.loc[:, ['CRBI']]
  53. cwalks = hitters.loc[:, ['CWalks']]
  54. league = hitters.loc[:, ['League']]
  55. division = hitters.loc[:, ['League']]
  56. putouts = hitters.loc[:, ['PutOuts']]
  57. assists = hitters.loc[:, ['Assists']]
  58. errors = hitters.loc[:, ['Errors']]
  59. new_league = hitters.loc[:, ['NewLeague']]
  60. y = hitters.loc[:, ['Salary']]
  61. x = x.to_numpy()
  62. y = y.to_numpy()
  63.  
  64.  
  65. #convert every row into a numpy array
  66. x = [
  67.      np.array(at_bat).reshape(1, 263),
  68.      np.array(hits).reshape(1, 263),
  69.      np.array(home_runs).reshape(1, 263),
  70.      np.array(rbi).reshape(1, 263),
  71.      np.array(walks).reshape(1, 263),
  72.      np.array(years).reshape(1, 263),
  73.      np.array(catbat).reshape(1, 263),
  74.      np.array(chits).reshape(1, 263),
  75.      np.array(chmrun).reshape(1, 263),
  76.      np.array(cruns).reshape(1, 263),
  77.      np.array(crbi).reshape(1, 263),
  78.      np.array(cwalks).reshape(1, 263),
  79.      np.array(league).reshape(1, 263),
  80.      np.array(division).reshape(1, 263),
  81.      np.array(putouts).reshape(1, 263),
  82.      np.array(assists).reshape(1, 263),
  83.      np.array(errors).reshape(1, 263),
  84.      np.array(new_league).reshape(1, 263)
  85.      ]
  86.  
  87.  
  88.  
  89. '''
  90. def generate_weight(x, y):
  91.    list1 =[]
  92.    for i in range(x * y):
  93.        list1.append(np.random.randn())
  94.    return(np.array(list1).reshape(x, y)) #reshape keeps dimensions of weight (20, 5)
  95.  
  96. #20 features and 5 selected arbitrarily
  97. weight1 = generate_weight(20, 5)
  98. weight2 = generate_weight(5, 1) #1 because we are just trying to predict one output
  99.  
  100.  
  101. #leaky relu
  102. def leaky_relu(x):
  103.    x = np.where(x > 0, x, x * 0.01)    
  104.    return x
  105.  
  106. #feed foward, x is the feature
  107. def feed_forward(x, weight1, weight2):
  108.    # input layer to hidden layer
  109.    input_layer_input = x.dot(weight1)# input from layer 1
  110.    input_layer_output = leaky_relu(input_layer_input)# output of layer 2 (output is the hidden layer)
  111.      
  112.    # hidden layer to output layer
  113.    hidden_layer_input = input_layer_output.dot(weight2)# input of 1st output layer
  114.    hidden_layer_output = leaky_relu(hidden_layer_input)# output of out layer
  115.    return(hidden_layer_output)
  116.  
  117.  
  118. # for loss we will be using mean square error(MSE)
  119. def loss(out, Y): #out is the output from feed forward, and Y is actualy salary
  120.    s =(np.square(out-Y))
  121.    s = np.sum(s)/len(Y)
  122.    return(s)
  123.  
  124. # Back propagation of error
  125. def back_prop(x, y, weight1, weight2, learning_rate):
  126.      
  127.    # output layer back to hidden layer
  128.    output_layer_input = x.dot(weight1)# input from layer 1
  129.    output_layer_output = leaky_relu(output_layer_input)# output of layer 2
  130.      
  131.    # hidden layer back to input layer
  132.    hidden_layer_input2 = output_layer_output.dot(weight2)# input of out layer
  133.    hidden_layer_output2 = leaky_relu(hidden_layer_input2)# output of out layer
  134.    # error in output layer
  135.    d2 =(hidden_layer_output2-y)
  136.    d1 = np.multiply((weight2.dot((d2.transpose()))).transpose(),
  137.                                   (np.multiply(output_layer_output, 1-output_layer_output)))
  138.  
  139.    # Gradient for weight1 and weight2
  140.    weight1_adj = x.transpose().dot(d1)
  141.    weight2_adj = output_layer_output.transpose().dot(d2)
  142.      
  143.    # Updating parameters
  144.    weight1 = weight1-(learning_rate*(weight1_adj))
  145.    weight2 = weight2-(learning_rate*(weight2_adj))
  146.      
  147.    return(weight1, weight2)
  148.  
  149.  
  150. #train is method to measure accuracy of model
  151. def train(x, Y, weight1, weight2, learning_rate = 0.01, epoch = 10):
  152.    accuracy_training_set =[]
  153.    test_set =[]
  154.    for j in range(epoch):
  155.        list2 =[]
  156.        for i in range(len(x)): #looping through all features
  157.            out = feed_forward(x[i], weight1, weight2) #running through feed forward
  158.            list2.append((test_set(out, Y[i]))) #adding output to the list
  159.            weight1, weight2 = back_prop(x[i], Y[i], weight1, weight2, learning_rate) #back propogate to get new weights and update network
  160.        accuracy_training_set.append((1-(sum(list2)/len(x)))*100)
  161.        test_set.append(sum(list2)/len(x))
  162.    return(accuracy_training_set, test_set, weight1, weight2)
  163.  
  164.  
  165. def predict_salary(x, weight1, weight2):
  166.    Out = feed_forward(x, weight1, weight2)
  167.    for i in range(len(Out[0])):
  168.        Out[0[i]]
  169.        
  170. # x is take all the features except salary, which is Y        
  171. accuracy_training_set, test_set, weight1, weight2 = train(x, y, weight1, weight2, 0.01, 100)
  172.  
  173. # ploting accuracy
  174. plt.plot(accuracy_training_set)
  175. plt.ylabel('Accuracy Training Set')
  176. plt.xlabel('Epochs/Iterations:')
  177. plt.show()
  178.  
  179. # plotting Loss
  180. plt.plot(test_set)
  181. plt.ylabel('Test Set')
  182. plt.xlabel('Epochs/Iterations:')
  183. plt.show()
  184.  
  185. #predict salary of players
  186. predict_salary(x[i], weight1, weight2)
  187.  
  188. '''
Add Comment
Please, Sign In to add comment