Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. import numpy as np
  2.  
  3. # Init sequence
  4. data =
  5. [
  6. [0, 1.0], [1, 3.0], [2, 7.0], [3, 8.0],
  7. [4, 21.0], [5, 49.0], [6, 76.0], [7, 224.0],
  8. [8, 467.0], [9, 514.0], [10, 1155.0], [11, 2683.0],[12, 5212.0]
  9. ]
  10.  
  11. X = np.matrix(data)[:, 0]
  12. y = np.matrix(data)[:, 1]
  13.  
  14. def J(X, y, theta):
  15. theta = np.matrix(theta).T
  16. m = len(y)
  17. predictions = X * theta
  18. sqError = np.power((predictions-y), [2])
  19. return 1/(2*m) * sum(sqError)
  20.  
  21. dataX = np.matrix(data)[:, 0:1]
  22. X = np.ones((len(dataX), 2))
  23. X[:, 1:] = dataX
  24.  
  25. # gradient descent function
  26. def gradient(X, y, alpha, theta, iters):
  27. J_history = np.zeros(iters)
  28. m = len(y)
  29. theta = np.matrix(theta).T
  30. for i in range(iters):
  31. h0 = X * theta
  32. delta = (1 / m) * (X.T * h0 - X.T * y)
  33. theta = theta - alpha * delta
  34. J_history[i] = J(X, y, theta.T)
  35. return J_history, theta
  36. print('n'+40*'=')
  37.  
  38. # Theta initialization
  39. theta = np.matrix([np.random.random(), np.random.random()])
  40.  
  41. # Learning rate
  42. alpha = 0.02
  43.  
  44. # Iterations
  45. iters = 1000000
  46.  
  47. print('n== Model summary ==nLearning rate: {}nIterations: {}nInitial
  48. theta: {}nInitial J: {:.2f}n'
  49. .format(alpha, iters, theta, J(X, y, theta).item()))
  50. print('Training model... ')
  51.  
  52. # Train model and find optimal Theta value
  53. J_history, theta_min = gradient(X, y, alpha, theta, iters)
  54. print('Done, Model is trained')
  55. print('nModelled prediction function is:ny = {:.2f} * x + {:.2f}'
  56. .format(theta_min[1].item(), theta_min[0].item()))
  57. print('Cost is: {:.2f}'.format(J(X, y, theta_min.T).item()))
  58.  
  59. # Calculate the predicted profit
  60. def predict(pop):
  61. return [1, pop] * theta_min
  62.  
  63. # Now
  64. p = len(data)
  65. print('n'+40*'=')
  66. print('Initial sequence was:n', *np.array(data)[:, 1])
  67. print('nNext numbers should be: {:,.1f}'
  68. .format(predict(p).item()))
  69.  
  70. import numpy as np
  71. from sklearn import datasets, linear_model
  72.  
  73. # Define the problem
  74. problem = [1, 3, 7, 8, 21, 49, 76, 224]
  75.  
  76. # create x and y for the problem
  77.  
  78. x = []
  79. y = []
  80.  
  81. for (xi, yi) in enumerate(problem):
  82. x.append([xi])
  83. y.append(yi)
  84.  
  85. x = np.array(x)
  86. y = np.array(y)
  87. # Create linear regression object
  88. regr = linear_model.LinearRegression()
  89. regr.fit(x, y)
  90.  
  91. # create the testing set
  92. x_test = [[i] for i in range(len(x), 3 + len(x))]
  93.  
  94. # The coefficients
  95. print('Coefficients: n', regr.coef_)
  96. # The mean squared error
  97. print("Mean squared error: %.2f" % np.mean((regr.predict(x) - y) ** 2))
  98. # Explained variance score: 1 is perfect prediction
  99. print('Variance score: %.2f' % regr.score(x, y))
  100.  
  101. # Do predictions
  102. y_predicted = regr.predict(x_test)
  103.  
  104. print("Next few numbers in the series are")
  105. for pred in y_predicted:
  106. print(pred)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement