baotrung217

ex4

Jan 25th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.22 KB | None | 0 0
  1. import os
  2. import numpy as np
  3. import scipy.io as sio
  4. import matplotlib.pyplot as plt
  5. from sklearn.preprocessing import OneHotEncoder
  6.  
  7. # Read the dataset
  8. path1 = os.path.dirname(os.path.realpath(__file__)) + '\..\data\ex4data1'
  9. data = sio.loadmat(path1)
  10. # Load weights
  11. path2 = os.path.dirname(os.path.realpath(__file__)) + '\..\data\ex4weights'
  12. weights = sio.loadmat(path2)
  13. theta1_pt = weights['Theta1']
  14. theta2_pt = weights['Theta2']
  15.  
  16. # Visualizing the data
  17. idx = np.random.randint(0, data['X'].shape[0], size=100)
  18.    
  19. def displayData(data, m, n):
  20.     # Create 10x10 sub plots
  21.     f, ax = plt.subplots(m,n)
  22.     for j in range(m):
  23.         for k in range(n):
  24.             ax[j,k].imshow(data['X'][idx[j*m+k]].reshape(20,20))
  25.        
  26. #displayData(data,10,10)
  27.  
  28. X = data['X']
  29. y = data['y']
  30.  
  31. learning_rate = 1
  32.  
  33. #from sklearn.preprocessing import OneHotEncoder
  34. encoder = OneHotEncoder(sparse=False)
  35. y_onehot = encoder.fit_transform(y)
  36. y_onehot.shape
  37.  
  38. # Sigmoid function
  39. def sigmoid(x):
  40.     return 1 / (1 + np.exp(-x))
  41.  
  42. def forward_propagate(X, theta1, theta2):
  43.     m = X.shape[0]
  44.    
  45.     a1 = np.insert(X, 0, values=np.ones(m), axis=1)
  46.     z2 = a1 * theta1.T
  47.     a2 = np.insert(sigmoid(z2), 0, values=np.ones(m), axis=1)
  48.     z3 = a2 * theta2.T
  49.     h = sigmoid(z3)
  50.    
  51.     return a1, z2, a2, z3, h
  52.  
  53. # cost function with pre-trained weights and no regularization
  54. def costPreTrained(X, y, theta1, theta2):
  55.     m = X.shape[0]
  56.     X = np.matrix(X)
  57.     y = np.matrix(y)
  58.    
  59.     a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
  60.    
  61.     first = np.sum(np.multiply(-y, np.log(h)))
  62.     second = np.sum(np.multiply(1-y, np.log(1-h)))
  63.    
  64.     J = 1/m * (first - second)
  65.    
  66.     return J
  67.  
  68. print(costPreTrained(X, y_onehot, theta1_pt, theta2_pt))
  69.  
  70. # Regularized cost function with pre-trained weights
  71. def costRegPreTrained(X, y, theta1, theta2, learning_rate):
  72.     m = X.shape[0]
  73.     X = np.matrix(X)
  74.     y = np.matrix(y)
  75.    
  76.     a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
  77.     first = np.sum(np.multiply(-y, np.log(h)))
  78.     second = np.sum(np.multiply(1-y, np.log(1-h)))
  79.    
  80.     tmp1 = theta1[:,1:]
  81.     tmp2 = theta2[:,1:]
  82.     reg = learning_rate/(2*m) * (np.sum(np.square(tmp1)) + np.sum(np.square(tmp2)))
  83.    
  84.     J = 1/m * (first - second) + reg
  85.    
  86.     return J
  87.  
  88. print(costRegPreTrained(X, y_onehot, theta1_pt, theta2_pt, learning_rate))
  89.  
  90. # Sigmoid Gradient
  91. def sigmoidGradient(z):
  92.     return np.multiply(sigmoid(z), (1 - sigmoid(z)))
  93.  
  94. print(sigmoidGradient(0))
  95.  
  96. # Normally initialize
  97. epsilon_init = 0.25
  98. input_size = 400
  99. hidden_size = 25
  100. num_labels = 10
  101. learning_rate = 1
  102.  
  103. params = np.random.random(size=((input_size+1)*hidden_size + (hidden_size+1)*num_labels)) * 2 * epsilon_init - epsilon_init
  104.  
  105. # Backpropagation
  106. def backpropagate(params, input_size, hidden_size, num_labels, X, y, learning_rate):
  107.     m = X.shape[0]
  108.     X = np.matrix(X)
  109.     y = np.matrix(y)
  110.    
  111.     theta1 = np.reshape(params[:(input_size+1)*hidden_size], (hidden_size, input_size+1))
  112.     theta2 = np.reshape(params[(input_size+1)*hidden_size:], (num_labels, hidden_size+1))
  113.    
  114.     a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
  115.    
  116.     # cost
  117.     J = costRegPreTrained(X, y, theta1, theta2, learning_rate)
  118.    
  119.     # initializations
  120.     delta_1 = np.zeros(theta1.shape)  # shape (25, 401)
  121.     delta_2 = np.zeros(theta2.shape)  # shape (10, 26)
  122.    
  123.     # perform backpropagation
  124.     for i in range(m):
  125.         a1i = a1[i,:]  # (1, 401)
  126.         z2i = z2[i,:]  # (1, 25)
  127.         a2i = a2[i,:]  # (1, 26)
  128.         hi = h[i,:]  # (1, 10)
  129.         yi = y[i,:]  # (1, 10)
  130.        
  131.         d3i = hi - yi  # (1, 10)
  132.        
  133.         # add bias unit
  134.         z2i = np.insert(z2i, 0, values=np.ones(1))  # (1, 26)
  135.         d2i = np.multiply((d3i * theta2), sigmoidGradient(z2i))  # (1, 26)
  136.        
  137.         delta_1 = delta_1 + d2i[:,1:].T * a1i # (25, 401)
  138.         delta_2 = delta_2 + d3i.T * a2i # (10, 26)
  139.        
  140.     # add the gradient regularization term
  141.     delta_1[:,1:] = delta_1[:,1:] + (theta1[:,1:] * learning_rate) / m
  142.     delta_2[:,1:] = delta_2[:,1:] + (theta2[:,1:] * learning_rate) / m
  143.    
  144.     # unravel the gradient matrices into a single array
  145.     grad = np.concatenate((np.ravel(delta_1), np.ravel(delta_2)))
  146.    
  147.     return J, grad
  148.  
  149. J, grad = backpropagate(params, input_size, hidden_size, num_labels, X, y_onehot, learning_rate)
  150.  
  151. print(J)
  152. print(grad.shape)
  153.  
  154. from scipy.optimize import minimize
  155.  
  156. # minimize the objective function
  157. fmin = minimize(fun=backpropagate, x0=params, args=(input_size, hidden_size, num_labels, X, y_onehot, learning_rate), method='TNC', jac=True, options={'maxiter': 250})
  158.  
  159. #print(fmin)
  160.  
  161. def predict(h):
  162.     h_argmax = np.argmax(h, axis=1)
  163.     return h_argmax + 1
  164.  
  165. X = np.matrix(X)
  166. theta1 = np.matrix(np.reshape(fmin.x[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))
  167. theta2 = np.matrix(np.reshape(fmin.x[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))
  168.  
  169. a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
  170. y_pred = predict(h)
  171.  
  172. correct = [1 if a == b else 0 for (a, b) in zip(y_pred, y)]
  173. accuracy = (sum(map(int, correct)) / float(len(correct)))
  174. print('accuracy = {0}%'.format(accuracy * 100))
Advertisement
Add Comment
Please, Sign In to add comment