baotrung217

ex3-nn

Jan 5th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. import numpy as np
  2. import scipy.io
  3. import matplotlib.pyplot as plt
  4.  
  5. # load data
  6. data = scipy.io.loadmat('machine-learning-ex3\ex3\ex3data1')
  7. # load weights
  8. weights = scipy.io.loadmat('machine-learning-ex3\ex3\ex3weights')
  9. theta1 = weights['Theta1']
  10. theta2 = weights['Theta2']
  11.  
  12. print('Data shape:')
  13. print(data['X'].shape)
  14. print(data['y'].shape)
  15.  
  16. # diplay data
  17. idx = np.random.randint(0, data['X'].shape[0], 100)
  18.  
  19. def displayData(data, m, n):
  20.    fig, ax = plt.subplots(m, n)
  21.    
  22.    for i in range(m):
  23.       for j in range(n):
  24.          ax[i,j].imshow(data['X'][idx[m*i + j]].reshape(20,20))
  25.          
  26. #displayData(data, 10, 10)
  27.  
  28. def sigmoid(z):
  29.     return 1 / (1 + np.exp(-z))
  30.  
  31. # One-hot encoder
  32. #from sklearn.preprocessing import OneHotEncoder
  33. #encoder = OneHotEncoder(sparse=False)
  34. #y_onehot = encoder.fit_transform(data['y'])
  35.  
  36. def forward_propagation(X, theta1, theta2):
  37.    m = X.shape[0]
  38.    
  39.    a1 = np.insert(X, 0, values=np.ones(m), axis=1)
  40.    z2 = a1.dot(theta1.T)
  41.    a2 = np.insert(sigmoid(z2), 0, values=np.ones(m), axis=1)
  42.    z3 = a2.dot(theta2.T)
  43.    h = sigmoid(z3)
  44.    return h
  45.  
  46. def predict(h):
  47.    m = h.shape[0]
  48.    n = h.shape[1]
  49.    print(m,n)
  50.    ret = np.zeros((m,n))
  51.    for i in range(m):
  52.       for j in range(n):
  53.          if h[i][j] >= 0.5:
  54.             ret[i][j] = 1
  55.          else:
  56.             ret[i][j] = 0
  57.    
  58.    return ret
  59.  
  60. h = forward_propagation(data['X'], theta1, theta2)
  61. y_pred = np.array(np.argmax(h, axis=1) + 1)
  62. correct = [1 if a == b else 0 for (a, b) in zip(y_pred, data['y'])]
  63. accuracy = (sum(map(int, correct)) / float(len(correct)))
  64. print('accuracy = {0}%'.format(accuracy * 100))
Advertisement
Add Comment
Please, Sign In to add comment