baotrung217

ex1-multiple_var

Dec 11th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. import os
  2. import numpy as np
  3. import pandas as pd
  4. from matplotlib import pyplot
  5. import matplotlib.pyplot as plt
  6.  
  7.  
  8. path = os.path.dirname(os.path.realpath(__file__)) + '\..\data\ex1data2.txt'
  9. data = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
  10. print('Data before normalizing:')
  11. print(data.head(n=5))
  12. #data.plot.bar()
  13.  
  14. # Feature normalization
  15. data = (data - data.mean())/data.std()
  16. print('Data after normalizing:')
  17. print(data.head(n=5))
  18. #data.plot.bar()
  19.  
  20. # Add a column of 1
  21. data.insert(0, 'Ones', 1)
  22. #print(data.head(n=5))
  23.  
  24. # Number of columns
  25. cols = data.shape[1]
  26.  
  27. # some parameters
  28. theta = np.mat(np.zeros(3))
  29. iteration = 1500
  30. alpha = 0.01
  31.  
  32. # inputs and outputs
  33. X = data.iloc[:,:cols-1]
  34. y = data.iloc[:,-1:]
  35. print('Input:')
  36. print(X.head(n=5))
  37. print('Output:')
  38. print(y.head(n=5))
  39.  
  40. X = np.mat(X)
  41. y = np.mat(y)
  42. m = len(X)
  43.  
  44. def computeCost(X, y, theta):
  45.     inner = np.power((X * theta.T - y), 2)
  46.     return np.sum(inner)/(2 * len(X))
  47.  
  48. # print cost before training
  49. print('Initial cost')
  50. print(computeCost(X, y, theta))
  51.  
  52. def gradientDescent(X, y, theta, alpha, iters):
  53.     cost = np.zeros(iters)
  54.     param = int(theta.ravel().shape[1])
  55.     his_theta = np.zeros((iters, 3)) # to store all thetas
  56.    
  57.     for i in range(iters):
  58.         error = X * theta.T - y
  59.        
  60.         for j in range(param):
  61.             temp = np.multiply(error, X[:,j])
  62.             theta[0,j] = theta[0,j] - (alpha / m) * np.sum(temp)
  63.             his_theta[i,j] = theta[0,j]
  64.            
  65.         cost[i] = computeCost(X, y, theta)
  66.        
  67.     return theta, cost, his_theta
  68.  
  69. # perform gradient descent to "fit" the model parameters
  70. g, cost, history = gradientDescent(X, y, theta, alpha, iteration)
  71.  
  72. print('The cost after training:')
  73. print(computeCost(X, y, g))
  74.  
  75. ################################################################
  76. fig, ax = plt.subplots(figsize=(12, 8))
  77.  
  78. ax.plot(np.arange(iteration), cost, 'r')
  79. ax.set_xlabel('Iterations')
  80. ax.set_ylabel('Cost')
  81. ax.set_title('Cost vs. Iterations')
  82. ax.grid()
  83.  
  84. #plt.xticks(np.arange(1000))
  85. #plt.yticks(np.arange(4, 7, 0.5))
  86.  
  87. pyplot.show()
Advertisement
Add Comment
Please, Sign In to add comment