Guest User

Untitled

a guest
Nov 17th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. import tensorflow as tf
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. # some constants used by the learning algorith
  6. learning_rate = 0.01
  7. training_epochs = 40
  8.  
  9. trX = np.linspace(-1, 1, 101)
  10. num_coeffs = 6
  11. trY_coeffs = [1, 2, 3, 4, 5, 6]
  12. trY = 0
  13.  
  14. # output data based on 5 polynomial
  15. for i in range(num_coeffs):
  16. trY += trY_coeffs[i] * np.power(trX, i)
  17. trY += np.random.randn(*trX.shape) * 1.5 # add some noise
  18.  
  19. X = tf.placeholder(tf.float32)
  20. Y = tf.placeholder(tf.float32)
  21.  
  22. def model(X, w):
  23. terms = []
  24. for i in range(num_coeffs):
  25. term = tf.multiply(w[i], tf.pow(X, i))
  26. terms.append(term)
  27. return tf.add_n(terms)
  28.  
  29. w = tf.Variable([0.0] * num_coeffs, name = "parameters")
  30. y_model = model(X, w)
  31.  
  32. # cost function
  33. cost = tf.pow(Y - y_model, 2)
  34.  
  35. # operation that will be called on each iteration of the learning algorithm
  36. train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
  37.  
  38. sess = tf.Session()
  39. init = tf.global_variables_initializer()
  40. sess.run(init)
  41.  
  42. for epoch in range(training_epochs):
  43. for (x, y) in zip(trX, trY):
  44. sess.run(train_op, feed_dict={X: x, Y: y})
  45. w_val = sess.run(w) # obtain the final parameter value
  46. print(w_val)
  47. sess.close()
  48.  
  49. plt.scatter(trX, trY)
  50. trY2 = 0
  51. for i in range(num_coeffs):
  52. trY2 += w_val[i] * np.power(trX, i)
  53. plt.plot(trX, trY2, 'r')
  54. plt.show()
Add Comment
Please, Sign In to add comment