baotrung217

ex5

Feb 23rd, 2018
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.52 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.  
  6.  
  7. # Read the dataset
  8. path = os.path.dirname(os.path.realpath(__file__)) + '\ex5\ex5data1'
  9. data = sio.loadmat(path)
  10.  
  11. # training set
  12. X = data['X']
  13. y = data['y']
  14. # validation set
  15. Xval = data['Xval']
  16. yval = data['yval']
  17. # test set
  18. Xtest = data['Xtest']
  19. ytest = data['ytest']
  20.  
  21. # Number of training examples
  22. m = X.shape[0]
  23. # Learning rate
  24. learningRate = 0
  25. # Theta
  26. theta = np.ones(X.shape[1]+1)
  27.  
  28. # Visualize the data
  29. def plotData():
  30.     plt.figure(figsize=(10,8))
  31.     plt.ylabel('Water flowing out of the dam (y)')
  32.     plt.xlabel('Change in water level (x)')
  33.     plt.plot(X, y, 'rx', label='Training')
  34.     plt.legend()
  35.  
  36. plotData()
  37.  
  38. ##############################################################
  39. # 1.2. Regularized linear regression cost function
  40. ##############################################################
  41. def computeCost(theta, X, y, learningRate):
  42.     theta = np.matrix(theta).T
  43.     X = np.insert(X, 0, 1, axis=1)
  44.     y = np.matrix(y)
  45.    
  46.     inner = (1 / (2 * m)) * np.sum(np.power((X.dot(theta) - y), 2))
  47.     reg = np.sum(np.power(theta[1:], 2))
  48.     return inner + (learningRate / (2 * m)) * reg
  49.  
  50. print(computeCost(theta, X, y, learningRate))
  51.  
  52. ##############################################################
  53. # 1.3. Regularized linear regression gradient
  54. ##############################################################
  55. def computeGradient(theta, X, y, learningRate):
  56.    theta = np.matrix(theta).T
  57.    X = np.insert(X, 0, 1, axis=1)
  58.    y = np.matrix(y)
  59.    
  60.    parameters = int(theta.ravel().shape[1])
  61.    grad = np.zeros(parameters)
  62.    
  63.    error = X.dot(theta) - y
  64.    
  65.    for i in range(parameters):
  66.        term = np.multiply(error.T, X[:,i])
  67.        
  68.        if (i == 0):
  69.           grad[i] = np.sum(term) / m
  70.        else:
  71.           grad[i] = (np.sum(term) / m) + ((learningRate / m) * theta[i])
  72.    
  73.    return grad
  74.  
  75. print(computeGradient(theta, X, y, learningRate))
  76.  
  77. ##############################################################
  78. # 1.4. Fitting linear regression
  79. ##############################################################
  80. import scipy.optimize
  81.  
  82. def optimizeTheta(theta, X, y, learningRate=0.):
  83.    fit_theta = scipy.optimize.fmin_cg(computeCost, x0=theta,
  84.                                        fprime=computeGradient,
  85.                                        args=(X,y,learningRate),
  86.                                        epsilon=1.49e-12,
  87.                                        maxiter=1000)
  88.    return fit_theta
  89.  
  90. fit_theta = optimizeTheta(theta, X, y, 0.)
  91. print(computeCost(fit_theta, X, y, 0))
  92. # Plot the data
  93. XOne = np.insert(X, 0, values=np.ones(m), axis=1)
  94. plotData()
  95. plt.plot(X, XOne.dot(fit_theta).flatten())
  96.  
  97. ##############################################################
  98. # 2.1. Learning curves
  99. ##############################################################
  100. def plotLearningCurve():
  101.     """
  102.    Loop over first training point, then first 2 training points, then first 3 ...
  103.    and use each training-set-subset to find trained parameters.
  104.    With those parameters, compute the cost on that subset (Jtrain)
  105.    remembering that for Jtrain, lambda = 0 (even if you are using regularization).
  106.    Then, use the trained parameters to compute Jval on the entire validation set
  107.    again forcing lambda = 0 even if using regularization.
  108.    Store the computed errors, error_train and error_val and plot them.
  109.    """
  110.     mym, error_train, error_val = [], [], []
  111.     for i in range(1,13,1):
  112.        x_subset = X[:i]
  113.        y_subset = y[:i]
  114.        fit_theta = optimizeTheta(theta, x_subset, y_subset, learningRate=0)
  115.        error_train.append(computeCost(fit_theta, x_subset, y_subset, learningRate=0.))
  116.        error_val.append(computeCost(fit_theta, Xval, yval, learningRate=0))
  117.        mym.append(i)
  118.        
  119.     plt.figure(figsize=(10,8))
  120.     plt.ylabel('Error')
  121.     plt.xlabel('Number of training examples')
  122.     plt.title('Learning curve for linear regression')
  123.     plt.plot(mym, error_train, 'b-', label='Train')
  124.     plt.plot(mym, error_val, 'g-', label='Cross Validation')
  125.     plt.legend()
  126.    
  127. plotLearningCurve()
  128.  
  129. ##############################################################
  130. # 3. Polynomial Regression
  131. ##############################################################
  132. def genPolyFeatures(X, p):
  133.    myX = X.copy()
  134.    for i in range(2, p+1):
  135.       myX = np.insert(myX, myX.shape[1], np.power(myX[:,0], i), axis=1)
  136.      
  137.    return myX
  138.  
  139. #print(genPolyFeatures(X, 2))
  140. def featureNormalize(X):
  141.     Xnorm = X.copy()
  142.     stored_feature_means = np.mean(Xnorm,axis=0) #column-by-column
  143.     Xnorm[:,:] = Xnorm[:,:] - stored_feature_means[:]
  144.     stored_feature_stds = np.std(Xnorm,axis=0,ddof=1)
  145.     Xnorm[:,:] = Xnorm[:,:] / stored_feature_stds[:]
  146.     return Xnorm, stored_feature_means, stored_feature_stds
  147.    
  148. ##############################################################
  149. # 3.1. Learning polynomial regression
  150. ##############################################################
  151. degree = 6
  152. newX = genPolyFeatures(X, degree)
  153. newX_norm, stored_means, stored_stds = featureNormalize(newX)
  154. mytheta = np.ones((newX_norm.shape[1]+1, 1))
  155. fit_theta = optimizeTheta(mytheta, newX_norm, y, 1)
  156. #print(len(fit_theta))
  157.  
  158. def plotFit(fit_theta,means,stds):
  159.     """
  160.    Function that takes in some learned fit values (on feature-normalized data)
  161.    It sets x-points as a linspace, constructs an appropriate X matrix,
  162.    un-does previous feature normalization, computes the hypothesis values,
  163.    and plots on top of data
  164.    """
  165.     n_points_to_plot = 50
  166.     xvals = np.linspace(-50, 50, n_points_to_plot)
  167.    
  168.     xmat = np.ones((n_points_to_plot,1)) # shape (50,1)
  169.     xmat = np.insert(xmat,xmat.shape[1],xvals.T,axis=1) # shape (50,2)
  170.    
  171.     for i in range(2, len(fit_theta)):
  172.         xmat = np.insert(xmat, xmat.shape[1], np.power(xmat[:,1], i), axis=1)
  173.     #xmat_new = np.insert(xmat,0,1,axis=1)
  174.     #print(xmat.shape)
  175.     #This is undoing feature normalization
  176.     xmat[:,1:] = xmat[:,1:] - means[:]
  177.     xmat[:,1:] = xmat[:,1:] / stds[:]
  178.     plotData()
  179.     plt.plot(xvals, xmat.dot(fit_theta).flatten(), 'b--')
  180.  
  181. plotFit(fit_theta,stored_means,stored_stds)
  182.  
  183. ##############################################################
  184. # 3.2. Adjusting the regularization parameter
  185. ##############################################################
  186.  
  187. ##############################################################
  188. # 3.3. Selecting λ using a cross validation set
  189. ##############################################################
  190.  
  191. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment