📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Starter code for a simple regression example using eager execution.1Created by Akshay Agrawal ([email protected])2CS20: "TensorFlow for Deep Learning Research"3cs20.stanford.edu4Lecture 045"""6import time78import tensorflow as tf9import tensorflow.contrib.eager as tfe10import matplotlib.pyplot as plt1112import utils1314DATA_FILE = 'data/birth_life_2010.txt'1516# In order to use eager execution, `tfe.enable_eager_execution()` must be17# called at the very beginning of a TensorFlow program.18tfe.enable_eager_execution()1920# Read the data into a dataset.21data, n_samples = utils.read_birth_life_data(DATA_FILE)22dataset = tf.data.Dataset.from_tensor_slices((data[:,0], data[:,1]))2324# Create variables.25w = tfe.Variable(0.0)26b = tfe.Variable(0.0)2728# Define the linear predictor.29def prediction(x):30return x * w + b3132# Define loss functions of the form: L(y, y_predicted)33def squared_loss(y, y_predicted):34return (y - y_predicted) ** 23536def huber_loss(y, y_predicted, m=1.0):37"""Huber loss."""38t = y - y_predicted39# Note that enabling eager execution lets you use Python control flow and40# specificy dynamic TensorFlow computations. Contrast this implementation41# to the graph-construction one found in `utils`, which uses `tf.cond`.42return t ** 2 if tf.abs(t) <= m else m * (2 * tf.abs(t) - m)4344def train(loss_fn):45"""Train a regression model evaluated using `loss_fn`."""46print('Training; loss function: ' + loss_fn.__name__)47optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)4849# Define the function through which to differentiate.50def loss_for_example(x, y):51return loss_fn(y, prediction(x))5253# `grad_fn(x_i, y_i)` returns (1) the value of `loss_for_example`54# evaluated at `x_i`, `y_i` and (2) the gradients of any variables used in55# calculating it.56grad_fn = tfe.implicit_value_and_gradients(loss_for_example)5758start = time.time()59for epoch in range(100):60total_loss = 0.061for x_i, y_i in tfe.Iterator(dataset):62loss, gradients = grad_fn(x_i, y_i)63# Take an optimization step and update variables.64optimizer.apply_gradients(gradients)65total_loss += loss66if epoch % 10 == 0:67print('Epoch {0}: {1}'.format(epoch, total_loss / n_samples))68print('Took: %f seconds' % (time.time() - start))69print('Eager execution exhibits significant overhead per operation. '70'As you increase your batch size, the impact of the overhead will '71'become less noticeable. Eager execution is under active development: '72'expect performance to increase substantially in the near future!')7374train(huber_loss)75plt.plot(data[:,0], data[:,1], 'bo')76# The `.numpy()` method of a tensor retrieves the NumPy array backing it.77# In future versions of eager, you won't need to call `.numpy()` and will78# instead be able to, in most cases, pass Tensors wherever NumPy arrays are79# expected.80plt.plot(data[:,0], data[:,0] * w.numpy() + b.numpy(), 'r',81label="huber regression")82plt.legend()83plt.show()848586