linear_regression_eager_api.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. ''' Linear Regression with Eager API.
  2. A linear regression learning algorithm example using TensorFlow's Eager API.
  3. Author: Aymeric Damien
  4. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  5. '''
  6. from __future__ import absolute_import, division, print_function
  7. import matplotlib.pyplot as plt
  8. import numpy as np
  9. import tensorflow as tf
  10. # Set Eager API
  11. tf.enable_eager_execution()
  12. tfe = tf.contrib.eager
  13. # Training Data
  14. train_X = [3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167,
  15. 7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1]
  16. train_Y = [1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221,
  17. 2.827, 3.465, 1.65, 2.904, 2.42, 2.94, 1.3]
  18. n_samples = len(train_X)
  19. # Parameters
  20. learning_rate = 0.01
  21. display_step = 100
  22. num_steps = 1000
  23. # Weight and Bias
  24. W = tfe.Variable(np.random.randn())
  25. b = tfe.Variable(np.random.randn())
  26. # Linear regression (Wx + b)
  27. def linear_regression(inputs):
  28. return inputs * W + b
  29. # Mean square error
  30. def mean_square_fn(model_fn, inputs, labels):
  31. return tf.reduce_sum(tf.pow(model_fn(inputs) - labels, 2)) / (2 * n_samples)
  32. # SGD Optimizer
  33. optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
  34. # Compute gradients
  35. grad = tfe.implicit_gradients(mean_square_fn)
  36. # Initial cost, before optimizing
  37. print("Initial cost= {:.9f}".format(
  38. mean_square_fn(linear_regression, train_X, train_Y)),
  39. "W=", W.numpy(), "b=", b.numpy())
  40. # Training
  41. for step in range(num_steps):
  42. optimizer.apply_gradients(grad(linear_regression, train_X, train_Y))
  43. if (step + 1) % display_step == 0 or step == 0:
  44. print("Epoch:", '%04d' % (step + 1), "cost=",
  45. "{:.9f}".format(mean_square_fn(linear_regression, train_X, train_Y)),
  46. "W=", W.numpy(), "b=", b.numpy())
  47. # Graphic display
  48. plt.plot(train_X, train_Y, 'ro', label='Original data')
  49. plt.plot(train_X, np.array(W * train_X + b), label='Fitted line')
  50. plt.legend()
  51. plt.show()