After four posts on linear regression, we are finally at the door of deep learning. Today we will build a simple feed-forward neural network (but not deep) with the help of Tensorflow to solve the linear regression problem. Tensorflow is a popular open-source deep learning library, especially after the retirement of Theano. To learn more about installing and using Tensorflow, their official website offers a lot of interesting materials.
Tensorflow structure consists of two phases – Graphs and Sessions. Usually you start with building a graph and then let the data (in the format of multidimensional array or tensor) flow through the graph, hence the name Tensorflow.
The building blocks of a graph are tf.Operation (node) and tf.Tensor (edge). There are three main data types of tensors namely tf.Constant, tf.Variable, and tf.placeholder. In our linear regression example, the slope and intercept are referred to as weights and biases in the conext of Tensorflow. They are examples of tf.Variable. The dataset x and y are examples of tf.placeholder or more exactly, things fed into tf.placeholder during Session.run.
Tensorflow operations take any number of inputs and produce any number of outputs. The gradient descent minimizer we will use shortly is an example of tf.Operation. Finally, after the graph is constructed, a session fires up the program by Session.run() to perform the desired operations on input data.
As in the classical linear regresion post, the easiest way to solve linear equation is to use the closed-form Normal equation. It is also true in Tensorflow, where we only use tf.Constant and tf.Operations.
import tensorflow as tf
The results are, as expected, 0.6565181 and 2.0086851.
It is time to construct a full example by using tf.Variable and tf.placeholder, define batch and feed them foward into feed dictionary, and propagate back the errors into a Gradient Descent optimizer.
import tensorflow as tf
Below graph shows how x and y combine with intercept and slope to form prediction; then pass through two operations of sub and square to reach mse; and eventually how they contribute to the gradient descent optimizer. This code snippet scratched the surface of Tensorflow; deep down, it is still a traditional numerical minimization. Next step we are going to investigate a real deep neutral network called Long Short Term Memory (LSTM), which suits very well in financial time series analysis such as stock market forecast.
- Géron, Aurélien. Hands-on machine learning with Scikit-Learn and TensorFlow: concepts, tools, and techniques to build intelligent systems. “ O’Reilly Media, Inc.”, 2017.