Files
FYS-STK4155/doc/pub/week42/ipynb/week42.ipynb
T
2020-10-22 14:35:45 +02:00

301 KiB

Week 42 Convolutional (CNN) and Recurrent (RNN) Neural Networks

Morten Hjorth-Jensen, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

Date: Oct 17, 2020

Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license

Plan for week 42

Reading suggestions for both days: Aurelien Geron's chapters 13 and 14. Autoencoders are discussed in chapter 15 of Geron's text.

See also the handwritten notes from October 15 and October 16.

Excellent lectures on CNNs and RNNs.

Convolutional Neural Networks (recognizing images)

Convolutional neural networks (CNNs) were developed during the last decade of the previous century, with a focus on character recognition tasks. Nowadays, CNNs are a central element in the spectacular success of deep learning methods. The success in for example image classifications have made them a central tool for most machine learning practitioners.

CNNs are very similar to ordinary Neural Networks. They are made up of neurons that have learnable weights and biases. Each neuron receives some inputs, performs a dot product and optionally follows it with a non-linearity. The whole network still expresses a single differentiable score function: from the raw image pixels on one end to class scores at the other. And they still have a loss function (for example Softmax) on the last (fully-connected) layer and all the tips/tricks we developed for learning regular Neural Networks still apply (back propagation, gradient descent etc etc).

What is the difference? CNN architectures make the explicit assumption that the inputs are images, which allows us to encode certain properties into the architecture. These then make the forward function more efficient to implement and vastly reduce the amount of parameters in the network.

Here we provide only a superficial overview, for the more interested, we recommend highly the course IN5400 – Machine Learning for Image Analysis and the slides of CS231.

Another good read is the article here https://arxiv.org/pdf/1603.07285.pdf.

Neural Networks vs CNNs

Neural networks are defined as affine transformations, that is a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an output (to which a bias vector is usually added before passing the result through a nonlinear activation function). This is applicable to any type of input, be it an image, a sound clip or an unordered collection of features: whatever their dimensionality, their representation can always be flattened into a vector before the transformation.

Why CNNS for images, sound files, medical images from CT scans etc?

However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic structure. More formally, they share these important properties:

  • They are stored as multi-dimensional arrays (think of the pixels of a figure) .

  • They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).

  • One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).

These properties are not exploited when an affine transformation is applied; in fact, all the axes are treated in the same way and the topological information is not taken into account. Still, taking advantage of the implicit structure of the data may prove very handy in solving some tasks, like computer vision and speech recognition, and in these cases it would be best to preserve it. This is where discrete convolutions come into play.

A discrete convolution is a linear transformation that preserves this notion of ordering. It is sparse (only a few input units contribute to a given output unit) and reuses parameters (the same weights are applied to multiple locations in the input).

Regular NNs don’t scale well to full images

As an example, consider an image of size 32\times 32\times 3 (32 wide, 32 high, 3 color channels), so a single fully-connected neuron in a first hidden layer of a regular Neural Network would have 32\times 32\times 3 = 3072 weights. This amount still seems manageable, but clearly this fully-connected structure does not scale to larger images. For example, an image of more respectable size, say 200\times 200\times 3, would lead to neurons that have 200\times 200\times 3 = 120,000 weights.

We could have several such neurons, and the parameters would add up quickly! Clearly, this full connectivity is wasteful and the huge number of parameters would quickly lead to possible overfitting.

A regular 3-layer Neural Network.

3D volumes of neurons

Convolutional Neural Networks take advantage of the fact that the input consists of images and they constrain the architecture in a more sensible way.

In particular, unlike a regular Neural Network, the layers of a CNN have neurons arranged in 3 dimensions: width, height, depth. (Note that the word depth here refers to the third dimension of an activation volume, not to the depth of a full Neural Network, which can refer to the total number of layers in a network.)

To understand it better, the above example of an image with an input volume of activations has dimensions 32\times 32\times 3 (width, height, depth respectively).

The neurons in a layer will only be connected to a small region of the layer before it, instead of all of the neurons in a fully-connected manner. Moreover, the final output layer could for this specific image have dimensions 1\times 1 \times 10, because by the end of the CNN architecture we will reduce the full image into a single vector of class scores, arranged along the depth dimension.

A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).

Layers used to build CNNs

A simple CNN is a sequence of layers, and every layer of a CNN transforms one volume of activations to another through a differentiable function. We use three main types of layers to build CNN architectures: Convolutional Layer, Pooling Layer, and Fully-Connected Layer (exactly as seen in regular Neural Networks). We will stack these layers to form a full CNN architecture.

A simple CNN for image classification could have the architecture:

  • INPUT (32\times 32 \times 3) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.

  • CONV (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as [32\times 32\times 12] if we decided to use 12 filters.

  • RELU layer will apply an elementwise activation function, such as the max(0,x) thresholding at zero. This leaves the size of the volume unchanged ([32\times 32\times 12]).

  • POOL (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as [16\times 16\times 12].

  • FC (i.e. fully-connected) layer will compute the class scores, resulting in volume of size [1\times 1\times 10], where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.

Transforming images

CNNs transform the original image layer by layer from the original pixel values to the final class scores.

Observe that some layers contain parameters and other don’t. In particular, the CNN layers perform transformations that are a function of not only the activations in the input volume, but also of the parameters (the weights and biases of the neurons). On the other hand, the RELU/POOL layers will implement a fixed function. The parameters in the CONV/FC layers will be trained with gradient descent so that the class scores that the CNN computes are consistent with the labels in the training set for each image.

CNNs in brief

In summary:

  • A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)

  • There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)

  • Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function

  • Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)

  • Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)

For more material on convolutional networks, we strongly recommend the course IN5400 – Machine Learning for Image Analysis and the slides of CS231 which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs.

CNNs in more detail, building convolutional neural networks in Tensorflow and Keras

As discussed above, CNNs are neural networks built from the assumption that the inputs to the network are 2D images. This is important because the number of features or pixels in images grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.

As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D matrices, typically 1 for each color dimension (Red, Green, Blue).

Setting it up

It means that to represent the entire dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions:


(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .

The MNIST dataset again

The MNIST dataset consists of grayscale images with a pixel size of 28\times 28, meaning we require 28 \times 28 = 724 weights to each neuron in the first hidden layer.

If we were to analyze images of size 128\times 128 we would require 128 \times 128 = 16384 weights to each neuron. Even worse if we were dealing with color images, as most images are, we have an image matrix of size 128\times 128 for each color dimension (Red, Green, Blue), meaning 3 times the number of weights = 49152 are required for every single neuron in the first hidden layer.

Strong correlations

Images typically have strong local correlations, meaning that a small part of the image varies little from its neighboring regions. If for example we have an image of a blue car, we can roughly assume that a small blue part of the image is surrounded by other blue regions.

Therefore, instead of connecting every single pixel to a neuron in the first hidden layer, as we have previously done with deep neural networks, we can instead connect each neuron to a small part of the image (in all 3 RGB depth dimensions). The size of each small area is fixed, and known as a receptive.

Layers of a CNN

The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
The input image is typically a square matrix of depth 3.

A convolution is performed on the image which outputs a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters.

Each filter slides along the input image, taking the dot product between each small part of the image and the filter, in all depth dimensions. This is then passed through a non-linear function, typically the Rectified Linear (ReLu) function, which serves as the activation of the neurons in the first convolutional layer. This is further passed through a pooling layer, which reduces the size of the convolutional layer, e.g. by taking the maximum or average across some small regions, and this serves as input to the next convolutional layer.

Systematic reduction

By systematically reducing the size of the input volume, through convolution and pooling, the network should create representations of small parts of the input, and then from them assemble representations of larger areas. The final pooling layer is flattened to serve as input to a hidden layer, such that each neuron in the final pooling layer is connected to every single neuron in the hidden layer. This then serves as input to the output layer, e.g. a softmax output for classification.

Prerequisites: Collect and pre-process data

In [1]:
%matplotlib inline

# import necessary packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets


# ensure the same random numbers appear every time
np.random.seed(0)

# display images in notebook
%matplotlib inline
plt.rcParams['figure.figsize'] = (12,12)


# download MNIST dataset
digits = datasets.load_digits()

# define inputs and labels
inputs = digits.images
labels = digits.target

# RGB images have a depth of 3
# our images are grayscale so they should have a depth of 1
inputs = inputs[:,:,:,np.newaxis]

print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
print("labels = (n_inputs) = " + str(labels.shape))


# choose some random images to display
n_inputs = len(inputs)
indices = np.arange(n_inputs)
random_indices = np.random.choice(indices, size=5)

for i, image in enumerate(digits.images[random_indices]):
    plt.subplot(1, 5, i+1)
    plt.axis('off')
    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title("Label: %d" % digits.target[random_indices[i]])
plt.show()

Importing Keras and Tensorflow

In [2]:
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
#from tensorflow.keras import Conv2D
#from tensorflow.keras import MaxPooling2D
#from tensorflow.keras import Flatten

from sklearn.model_selection import train_test_split

# representation of labels
labels = to_categorical(labels)

# split into train and test data
# one-liner from scikit-learn library
train_size = 0.8
test_size = 1 - train_size
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
                                                    test_size=test_size)

Running with Keras

In [3]:
def create_convolutional_neural_network_keras(input_shape, receptive_field,
                                              n_filters, n_neurons_connected, n_categories,
                                              eta, lmbd):
    model = Sequential()
    model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
              activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    model.add(layers.Flatten())
    model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
    
    sgd = optimizers.SGD(lr=eta)
    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    
    return model

epochs = 100
batch_size = 100
input_shape = X_train.shape[1:4]
receptive_field = 3
n_filters = 10
n_neurons_connected = 50
n_categories = 10

eta_vals = np.logspace(-5, 1, 7)
lmbd_vals = np.logspace(-5, 1, 7)

Final part

In [4]:
CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
        
for i, eta in enumerate(eta_vals):
    for j, lmbd in enumerate(lmbd_vals):
        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
                                              n_filters, n_neurons_connected, n_categories,
                                              eta, lmbd)
        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
        scores = CNN.evaluate(X_test, Y_test)
        
        CNN_keras[i][j] = CNN
        
        print("Learning rate = ", eta)
        print("Lambda = ", lmbd)
        print("Test accuracy: %.3f" % scores[1])
        print()

Final visualization

In [5]:
# visual representation of grid search
# uses seaborn heatmap, could probably do this in matplotlib
import seaborn as sns

sns.set()

train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))

for i in range(len(eta_vals)):
    for j in range(len(lmbd_vals)):
        CNN = CNN_keras[i][j]

        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]

        
fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
ax.set_title("Training Accuracy")
ax.set_ylabel("$\eta$")
ax.set_xlabel("$\lambda$")
plt.show()

fig, ax = plt.subplots(figsize = (10, 10))
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
ax.set_title("Test Accuracy")
ax.set_ylabel("$\eta$")
ax.set_xlabel("$\lambda$")
plt.show()

The CIFAR01 data set

The CIFAR10 dataset contains 60,000 color images in 10 classes, with 6,000 images in each class. The dataset is divided into 50,000 training images and 10,000 testing images. The classes are mutually exclusive and there is no overlap between them.

In [6]:
import tensorflow as tf

from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

# We import the data set
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1 by dividing by 255. 
train_images, test_images = train_images / 255.0, test_images / 255.0

Verifying the data set

To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.

In [7]:
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    # The CIFAR labels happen to be arrays, 
    # which is why you need the extra index
    plt.xlabel(class_names[train_labels[i][0]])
plt.show()

Set up the model

The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.

As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.

In [8]:
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))

# Let's display the architecture of our model so far.

model.summary()

You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.

Add Dense layers on top

To complete our model, you will feed the last output tensor from the convolutional base (of shape (4, 4, 64)) into one or more Dense layers to perform classification. Dense layers take vectors as input (which are 1D), while the current output is a 3D tensor. First, you will flatten (or unroll) the 3D output to 1D, then add one or more Dense layers on top. CIFAR has 10 output classes, so you use a final Dense layer with 10 outputs and a softmax activation.

In [9]:
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
Here's the complete architecture of our model.

model.summary()

As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.

Compile and train the model

In [10]:
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels))

Finally, evaluate the model

In [11]:
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

print(test_acc)

Recurrent neural networks: Overarching view

Till now our focus has been, including convolutional neural networks as well, on feedforward neural networks. The output or the activations flow only in one direction, from the input layer to the output layer.

A recurrent neural network (RNN) looks very much like a feedforward neural network, except that it also has connections pointing backward.

RNNs are used to analyze time series data such as stock prices, and tell you when to buy or sell. In autonomous driving systems, they can anticipate car trajectories and help avoid accidents. More generally, they can work on sequences of arbitrary lengths, rather than on fixed-sized inputs like all the nets we have discussed so far. For example, they can take sentences, documents, or audio samples as input, making them extremely useful for natural language processing systems such as automatic translation and speech-to-text.

Set up of an RNN

Text to come.

A simple example

In [9]:
# Start importing packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model, Sequential 
from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
from tensorflow.keras import optimizers     
from tensorflow.keras import regularizers           
from tensorflow.keras.utils import to_categorical 



# convert into dataset matrix
def convertToMatrix(data, step):
 X, Y =[], []
 for i in range(len(data)-step):
  d=i+step  
  X.append(data[i:d,])
  Y.append(data[d,])
 return np.array(X), np.array(Y)

step = 4
N = 1000    
Tp = 800    

t=np.arange(0,N)
x=np.sin(0.02*t)#+2*np.random.rand(N)
df = pd.DataFrame(x)
df.head()

plt.plot(df)
plt.show()

values=df.values
train,test = values[0:Tp,:], values[Tp:N,:]

# add step elements into train and test
test = np.append(test,np.repeat(test[-1,],step))
train = np.append(train,np.repeat(train[-1,],step))
 
trainX,trainY =convertToMatrix(train,step)
testX,testY =convertToMatrix(test,step)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))

model = Sequential()
model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu"))
model.add(Dense(8, activation="relu")) 
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
model.summary()

model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)
trainPredict = model.predict(trainX)
testPredict= model.predict(testX)
predicted=np.concatenate((trainPredict,testPredict),axis=0)

trainScore = model.evaluate(trainX, trainY, verbose=0)
print(trainScore)

index = df.index.values
plt.plot(index,df)
plt.plot(index,predicted)
plt.axvline(df.index[Tp], c="r")
plt.show()
Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
simple_rnn_3 (SimpleRNN)     (None, 32)                1184      
_________________________________________________________________
dense_6 (Dense)              (None, 8)                 264       
_________________________________________________________________
dense_7 (Dense)              (None, 1)                 9         
=================================================================
Total params: 1,457
Trainable params: 1,457
Non-trainable params: 0
_________________________________________________________________
Train on 800 samples
Epoch 1/100
800/800 - 1s - loss: 0.0514
Epoch 2/100
800/800 - 0s - loss: 0.0018
Epoch 3/100
800/800 - 0s - loss: 0.0014
Epoch 4/100
800/800 - 0s - loss: 0.0011
Epoch 5/100
800/800 - 0s - loss: 9.2288e-04
Epoch 6/100
800/800 - 0s - loss: 6.6099e-04
Epoch 7/100
800/800 - 0s - loss: 6.3764e-04
Epoch 8/100
800/800 - 0s - loss: 5.5979e-04
Epoch 9/100
800/800 - 0s - loss: 4.3787e-04
Epoch 10/100
800/800 - 0s - loss: 4.0324e-04
Epoch 11/100
800/800 - 0s - loss: 3.8522e-04
Epoch 12/100
800/800 - 0s - loss: 3.1503e-04
Epoch 13/100
800/800 - 0s - loss: 2.7446e-04
Epoch 14/100
800/800 - 0s - loss: 2.6675e-04
Epoch 15/100
800/800 - 0s - loss: 2.6732e-04
Epoch 16/100
800/800 - 0s - loss: 2.2674e-04
Epoch 17/100
800/800 - 0s - loss: 2.1244e-04
Epoch 18/100
800/800 - 0s - loss: 2.2549e-04
Epoch 19/100
800/800 - 0s - loss: 1.9280e-04
Epoch 20/100
800/800 - 0s - loss: 1.8731e-04
Epoch 21/100
800/800 - 0s - loss: 1.9714e-04
Epoch 22/100
800/800 - 0s - loss: 1.9504e-04
Epoch 23/100
800/800 - 0s - loss: 1.6790e-04
Epoch 24/100
800/800 - 0s - loss: 1.9574e-04
Epoch 25/100
800/800 - 0s - loss: 1.8750e-04
Epoch 26/100
800/800 - 0s - loss: 1.6123e-04
Epoch 27/100
800/800 - 0s - loss: 1.7403e-04
Epoch 28/100
800/800 - 0s - loss: 1.7009e-04
Epoch 29/100
800/800 - 0s - loss: 1.7947e-04
Epoch 30/100
800/800 - 0s - loss: 1.6500e-04
Epoch 31/100
800/800 - 0s - loss: 1.8887e-04
Epoch 32/100
800/800 - 0s - loss: 1.6606e-04
Epoch 33/100
800/800 - 0s - loss: 1.7915e-04
Epoch 34/100
800/800 - 0s - loss: 1.4721e-04
Epoch 35/100
800/800 - 0s - loss: 1.5625e-04
Epoch 36/100
800/800 - 0s - loss: 1.7096e-04
Epoch 37/100
800/800 - 0s - loss: 1.6003e-04
Epoch 38/100
800/800 - 0s - loss: 1.4871e-04
Epoch 39/100
800/800 - 0s - loss: 1.5593e-04
Epoch 40/100
800/800 - 0s - loss: 1.7317e-04
Epoch 41/100
800/800 - 0s - loss: 1.4376e-04
Epoch 42/100
800/800 - 0s - loss: 1.6535e-04
Epoch 43/100
800/800 - 0s - loss: 1.7260e-04
Epoch 44/100
800/800 - 0s - loss: 1.3047e-04
Epoch 45/100
800/800 - 0s - loss: 1.5961e-04
Epoch 46/100
800/800 - 0s - loss: 1.3984e-04
Epoch 47/100
800/800 - 0s - loss: 1.3803e-04
Epoch 48/100
800/800 - 0s - loss: 1.5756e-04
Epoch 49/100
800/800 - 0s - loss: 1.2493e-04
Epoch 50/100
800/800 - 0s - loss: 1.4878e-04
Epoch 51/100
800/800 - 0s - loss: 1.5015e-04
Epoch 52/100
800/800 - 0s - loss: 1.5677e-04
Epoch 53/100
800/800 - 0s - loss: 1.3344e-04
Epoch 54/100
800/800 - 0s - loss: 1.5097e-04
Epoch 55/100
800/800 - 0s - loss: 1.2382e-04
Epoch 56/100
800/800 - 0s - loss: 1.7050e-04
Epoch 57/100
800/800 - 0s - loss: 1.2556e-04
Epoch 58/100
800/800 - 0s - loss: 1.3869e-04
Epoch 59/100
800/800 - 0s - loss: 1.1679e-04
Epoch 60/100
800/800 - 0s - loss: 1.3685e-04
Epoch 61/100
800/800 - 0s - loss: 1.3343e-04
Epoch 62/100
800/800 - 0s - loss: 1.3688e-04
Epoch 63/100
800/800 - 0s - loss: 1.3404e-04
Epoch 64/100
800/800 - 0s - loss: 1.5220e-04
Epoch 65/100
800/800 - 0s - loss: 1.1903e-04
Epoch 66/100
800/800 - 0s - loss: 1.4193e-04
Epoch 67/100
800/800 - 0s - loss: 1.2046e-04
Epoch 68/100
800/800 - 0s - loss: 1.2802e-04
Epoch 69/100
800/800 - 0s - loss: 1.4217e-04
Epoch 70/100
800/800 - 0s - loss: 1.2776e-04
Epoch 71/100
800/800 - 0s - loss: 1.3739e-04
Epoch 72/100
800/800 - 0s - loss: 1.2671e-04
Epoch 73/100
800/800 - 0s - loss: 1.4373e-04
Epoch 74/100
800/800 - 0s - loss: 1.1278e-04
Epoch 75/100
800/800 - 0s - loss: 1.3868e-04
Epoch 76/100
800/800 - 0s - loss: 1.2244e-04
Epoch 77/100
800/800 - 0s - loss: 1.3907e-04
Epoch 78/100
800/800 - 0s - loss: 1.0773e-04
Epoch 79/100
800/800 - 0s - loss: 1.3242e-04
Epoch 80/100
800/800 - 0s - loss: 1.3939e-04
Epoch 81/100
800/800 - 0s - loss: 1.1780e-04
Epoch 82/100
800/800 - 0s - loss: 1.2618e-04
Epoch 83/100
800/800 - 0s - loss: 1.1762e-04
Epoch 84/100
800/800 - 0s - loss: 1.2867e-04
Epoch 85/100
800/800 - 0s - loss: 1.2770e-04
Epoch 86/100
800/800 - 0s - loss: 1.2059e-04
Epoch 87/100
800/800 - 0s - loss: 1.1521e-04
Epoch 88/100
800/800 - 0s - loss: 1.2102e-04
Epoch 89/100
800/800 - 0s - loss: 1.3655e-04
Epoch 90/100
800/800 - 0s - loss: 9.8586e-05
Epoch 91/100
800/800 - 0s - loss: 1.2793e-04
Epoch 92/100
800/800 - 0s - loss: 1.2712e-04
Epoch 93/100
800/800 - 0s - loss: 1.2134e-04
Epoch 94/100
800/800 - 0s - loss: 1.0156e-04
Epoch 95/100
800/800 - 0s - loss: 1.2183e-04
Epoch 96/100
800/800 - 0s - loss: 1.4013e-04
Epoch 97/100
800/800 - 0s - loss: 1.2038e-04
Epoch 98/100
800/800 - 0s - loss: 1.3983e-04
Epoch 99/100
800/800 - 0s - loss: 1.1230e-04
Epoch 100/100
800/800 - 0s - loss: 1.1429e-04
0.0004728160643389856

An extrapolation example

The following code provides an example of how recurrent neural networks can be used to extrapolate to unknown values of physics data sets. Specifically, the data sets used in this program come from a quantum mechanical many-body calculation of energies as functions of the number of particles.

In [3]:

# For matrices and calculations
import numpy as np
# For machine learning (backend for keras)
import tensorflow as tf
# User-friendly machine learning library
# Front end for TensorFlow
import tensorflow.keras
# Different methods from Keras needed to create an RNN
# This is not necessary but it shortened function calls 
# that need to be used in the code.
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.layers import Input
from tensorflow.keras import regularizers
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
# For timing the code
from timeit import default_timer as timer
# For plotting
import matplotlib.pyplot as plt


# The data set
datatype='VaryDimension'
X_tot = np.arange(2, 42, 2)
y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,
	-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, 
	-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])

Formatting the Data

The way the recurrent neural networks are trained in this program differs from how machine learning algorithms are usually trained. Typically a machine learning algorithm is trained by learning the relationship between the x data and the y data. In this program, the recurrent neural network will be trained to recognize the relationship in a sequence of y values. This is type of data formatting is typically used time series forcasting, but it can also be used in any extrapolation (time series forecasting is just a specific type of extrapolation along the time axis). This method of data formatting does not use the x data and assumes that the y data are evenly spaced.

For a standard machine learning algorithm, the training data has the form of (x,y) so the machine learning algorithm learns to assiciate a y value with a given x value. This is useful when the test data has x values within the same range as the training data. However, for this application, the x values of the test data are outside of the x values of the training data and the traditional method of training a machine learning algorithm does not work as well. For this reason, the recurrent neural network is trained on sequences of y values of the form ((y1, y2), y3), so that the network is concerned with learning the pattern of the y data and not the relation between the x and y data. As long as the pattern of y data outside of the training region stays relatively stable compared to what was inside the training region, this method of training can produce accurate extrapolations to y values far removed from the training data set.

In [4]:
# FORMAT_DATA
def format_data(data, length_of_sequence = 2):  
    """
        Inputs:
            data(a numpy array): the data that will be the inputs to the recurrent neural
                network
            length_of_sequence (an int): the number of elements in one iteration of the
                sequence patter.  For a function approximator use length_of_sequence = 2.
        Returns:
            rnn_input (a 3D numpy array): the input data for the recurrent neural network.  Its
                dimensions are length of data - length of sequence, length of sequence, 
                dimnsion of data
            rnn_output (a numpy array): the training data for the neural network
        Formats data to be used in a recurrent neural network.
    """

    X, Y = [], []
    for i in range(len(data)-length_of_sequence):
        # Get the next length_of_sequence elements
        a = data[i:i+length_of_sequence]
        # Get the element that immediately follows that
        b = data[i+length_of_sequence]
        # Reshape so that each data point is contained in its own array
        a = np.reshape (a, (len(a), 1))
        X.append(a)
        Y.append(b)
    rnn_input = np.array(X)
    rnn_output = np.array(Y)

    return rnn_input, rnn_output


# ## Defining the Recurrent Neural Network Using Keras
# 
# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.

def rnn(length_of_sequences, batch_size = None, stateful = False):
    """
        Inputs:
            length_of_sequences (an int): the number of y values in "x data".  This is determined
                when the data is formatted
            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
        Returns:
            model (a Keras model): The recurrent neural network that is built and compiled by this
                method
        Builds and compiles a recurrent neural network with one hidden layer and returns the model.
    """
    # Number of neurons in the input and output layers
    in_out_neurons = 1
    # Number of neurons in the hidden layer
    hidden_neurons = 200
    # Define the input layer
    inp = Input(batch_shape=(batch_size, 
                length_of_sequences, 
                in_out_neurons))  
    # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to 
    # the network immediately after the input layer
    rnn = SimpleRNN(hidden_neurons, 
                    return_sequences=False,
                    stateful = stateful,
                    name="RNN")(inp)
    # Define the output layer as a dense neural network layer (standard neural network layer)
    #and add it to the network immediately after the hidden layer.
    dens = Dense(in_out_neurons,name="dense")(rnn)
    # Create the machine learning model starting with the input layer and ending with the 
    # output layer
    model = Model(inputs=[inp],outputs=[dens])
    # Compile the machine learning model using the mean squared error function as the loss 
    # function and an Adams optimizer.
    model.compile(loss="mean_squared_error", optimizer="adam")  
    return model

Predicting New Points With A Trained Recurrent Neural Network

In [5]:
def test_rnn (x1, y_test, plot_min, plot_max):
    """
        Inputs:
            x1 (a list or numpy array): The complete x component of the data set
            y_test (a list or numpy array): The complete y component of the data set
            plot_min (an int or float): the smallest x value used in the training data
            plot_max (an int or float): the largest x valye used in the training data
        Returns:
            None.
        Uses a trained recurrent neural network model to predict future points in the 
        series.  Computes the MSE of the predicted data set from the true data set, saves
        the predicted data set to a csv file, and plots the predicted and true data sets w
        while also displaying the data range used for training.
    """
    # Add the training data as the first dim points in the predicted data array as these
    # are known values.
    y_pred = y_test[:dim].tolist()
    # Generate the first input to the trained recurrent neural network using the last two 
    # points of the training data.  Based on how the network was trained this means that it
    # will predict the first point in the data set after the training data.  All of the 
    # brackets are necessary for Tensorflow.
    next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])
    # Save the very last point in the training data set.  This will be used later.
    last = [y_test[dim-1]]

    # Iterate until the complete data set is created.
    for i in range (dim, len(y_test)):
        # Predict the next point in the data set using the previous two points.
        next = model.predict(next_input)
        # Append just the number of the predicted data set
        y_pred.append(next[0][0])
        # Create the input that will be used to predict the next data point in the data set.
        next_input = np.array([[last, next[0]]], dtype=np.float64)
        last = next

    # Print the mean squared error between the known data set and the predicted data set.
    print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())
    # Save the predicted data set as a csv file for later use
    name = datatype + 'Predicted'+str(dim)+'.csv'
    np.savetxt(name, y_pred, delimiter=',')
    # Plot the known data set and the predicted data set.  The red box represents the region that was used
    # for the training data.
    fig, ax = plt.subplots()
    ax.plot(x1, y_test, label="true", linewidth=3)
    ax.plot(x1, y_pred, 'g-.',label="predicted", linewidth=4)
    ax.legend()
    # Created a red region to represent the points used in the training data.
    ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')
    plt.show()

# Check to make sure the data set is complete
assert len(X_tot) == len(y_tot)

# This is the number of points that will be used in as the training data
dim=12

# Separate the training data from the whole data set
X_train = X_tot[:dim]
y_train = y_tot[:dim]


# Generate the training data for the RNN, using a sequence of 2
rnn_input, rnn_training = format_data(y_train, 2)


# Create a recurrent neural network in Keras and produce a summary of the 
# machine learning model
model = rnn(length_of_sequences = rnn_input.shape[1])
model.summary()

# Start the timer.  Want to time training+testing
start = timer()
# Fit the model using the training data genenerated above using 150 training iterations and a 5%
# validation split.  Setting verbose to True prints information about each training iteration.
hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
                 verbose=True,validation_split=0.05)

for label in ["loss","val_loss"]:
    plt.plot(hist.history[label],label=label)

plt.ylabel("loss")
plt.xlabel("epoch")
plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
plt.legend()
plt.show()

# Use the trained neural network to predict more points of the data set
test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
# Stop the timer and calculate the total time needed.
end = timer()
print('Time: ', end-start)
Model: "model"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         [(None, 2, 1)]            0         
_________________________________________________________________
RNN (SimpleRNN)              (None, 200)               40400     
_________________________________________________________________
dense (Dense)                (None, 1)                 201       
=================================================================
Total params: 40,601
Trainable params: 40,601
Non-trainable params: 0
_________________________________________________________________
Train on 9 samples, validate on 1 samples
Epoch 1/150
9/9 [==============================] - 1s 76ms/sample - loss: 0.2402 - val_loss: 0.3869
Epoch 2/150
9/9 [==============================] - 0s 748us/sample - loss: 0.1266 - val_loss: 0.1450
Epoch 3/150
9/9 [==============================] - 0s 695us/sample - loss: 0.0504 - val_loss: 0.0223
Epoch 4/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0097 - val_loss: 0.0039
Epoch 5/150
9/9 [==============================] - 0s 3ms/sample - loss: 6.4447e-04 - val_loss: 0.0570
Epoch 6/150
9/9 [==============================] - 0s 3ms/sample - loss: 0.0139 - val_loss: 0.1296
Epoch 7/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0338 - val_loss: 0.1763
Epoch 8/150
9/9 [==============================] - 0s 3ms/sample - loss: 0.0465 - val_loss: 0.1823
Epoch 9/150
9/9 [==============================] - 0s 893us/sample - loss: 0.0475 - val_loss: 0.1556
Epoch 10/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0393 - val_loss: 0.1122
Epoch 11/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0269 - val_loss: 0.0673
Epoch 12/150
9/9 [==============================] - 0s 699us/sample - loss: 0.0148 - val_loss: 0.0312
Epoch 13/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0060 - val_loss: 0.0089
Epoch 14/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0016 - val_loss: 3.3912e-04
Epoch 15/150
9/9 [==============================] - 0s 879us/sample - loss: 0.0013 - val_loss: 0.0022
Epoch 16/150
9/9 [==============================] - 0s 730us/sample - loss: 0.0038 - val_loss: 0.0097
Epoch 17/150
9/9 [==============================] - 0s 808us/sample - loss: 0.0076 - val_loss: 0.0181
Epoch 18/150
9/9 [==============================] - 0s 958us/sample - loss: 0.0111 - val_loss: 0.0239
Epoch 19/150
9/9 [==============================] - 0s 748us/sample - loss: 0.0133 - val_loss: 0.0256
Epoch 20/150
9/9 [==============================] - 0s 892us/sample - loss: 0.0137 - val_loss: 0.0230
Epoch 21/150
9/9 [==============================] - 0s 772us/sample - loss: 0.0125 - val_loss: 0.0174
Epoch 22/150
9/9 [==============================] - 0s 694us/sample - loss: 0.0102 - val_loss: 0.0106
Epoch 23/150
9/9 [==============================] - 0s 685us/sample - loss: 0.0072 - val_loss: 0.0046
Epoch 24/150
9/9 [==============================] - 0s 913us/sample - loss: 0.0043 - val_loss: 8.0742e-04
Epoch 25/150
9/9 [==============================] - 0s 860us/sample - loss: 0.0021 - val_loss: 1.3698e-04
Epoch 26/150
9/9 [==============================] - 0s 958us/sample - loss: 8.4772e-04 - val_loss: 0.0025
Epoch 27/150
9/9 [==============================] - 0s 778us/sample - loss: 6.0774e-04 - val_loss: 0.0071
Epoch 28/150
9/9 [==============================] - 0s 854us/sample - loss: 0.0012 - val_loss: 0.0124
Epoch 29/150
9/9 [==============================] - 0s 887us/sample - loss: 0.0022 - val_loss: 0.0171
Epoch 30/150
9/9 [==============================] - 0s 886us/sample - loss: 0.0033 - val_loss: 0.0198
Epoch 31/150
9/9 [==============================] - 0s 793us/sample - loss: 0.0039 - val_loss: 0.0200
Epoch 32/150
9/9 [==============================] - 0s 931us/sample - loss: 0.0041 - val_loss: 0.0179
Epoch 33/150
9/9 [==============================] - 0s 867us/sample - loss: 0.0036 - val_loss: 0.0141
Epoch 34/150
9/9 [==============================] - 0s 851us/sample - loss: 0.0028 - val_loss: 0.0096
Epoch 35/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0018 - val_loss: 0.0055
Epoch 36/150
9/9 [==============================] - 0s 1ms/sample - loss: 9.3775e-04 - val_loss: 0.0023
Epoch 37/150
9/9 [==============================] - 0s 1ms/sample - loss: 3.7408e-04 - val_loss: 5.3772e-04
Epoch 38/150
9/9 [==============================] - 0s 737us/sample - loss: 1.6695e-04 - val_loss: 7.8647e-08
Epoch 39/150
9/9 [==============================] - 0s 705us/sample - loss: 2.7229e-04 - val_loss: 3.6125e-04
Epoch 40/150
9/9 [==============================] - 0s 729us/sample - loss: 5.7101e-04 - val_loss: 0.0011
Epoch 41/150
9/9 [==============================] - 0s 926us/sample - loss: 9.1568e-04 - val_loss: 0.0019
Epoch 42/150
9/9 [==============================] - 0s 933us/sample - loss: 0.0012 - val_loss: 0.0022
Epoch 43/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0013 - val_loss: 0.0021
Epoch 44/150
9/9 [==============================] - 0s 852us/sample - loss: 0.0012 - val_loss: 0.0017
Epoch 45/150
9/9 [==============================] - 0s 816us/sample - loss: 9.3627e-04 - val_loss: 9.8664e-04
Epoch 46/150
9/9 [==============================] - 0s 931us/sample - loss: 6.2403e-04 - val_loss: 3.8188e-04
Epoch 47/150
9/9 [==============================] - 0s 1ms/sample - loss: 3.2660e-04 - val_loss: 3.9207e-05
Epoch 48/150
9/9 [==============================] - 0s 950us/sample - loss: 1.1524e-04 - val_loss: 5.1660e-05
Epoch 49/150
9/9 [==============================] - 0s 901us/sample - loss: 2.6645e-05 - val_loss: 3.8494e-04
Epoch 50/150
9/9 [==============================] - 0s 654us/sample - loss: 5.6145e-05 - val_loss: 9.0012e-04
Epoch 51/150
9/9 [==============================] - 0s 709us/sample - loss: 1.6422e-04 - val_loss: 0.0014
Epoch 52/150
9/9 [==============================] - 0s 1ms/sample - loss: 2.9340e-04 - val_loss: 0.0017
Epoch 53/150
9/9 [==============================] - 0s 1ms/sample - loss: 3.8915e-04 - val_loss: 0.0018
Epoch 54/150
9/9 [==============================] - 0s 965us/sample - loss: 4.1744e-04 - val_loss: 0.0016
Epoch 55/150
9/9 [==============================] - 0s 973us/sample - loss: 3.7302e-04 - val_loss: 0.0012
Epoch 56/150
9/9 [==============================] - 0s 742us/sample - loss: 2.7672e-04 - val_loss: 7.1274e-04
Epoch 57/150
9/9 [==============================] - 0s 710us/sample - loss: 1.6404e-04 - val_loss: 3.1516e-04
Epoch 58/150
9/9 [==============================] - 0s 829us/sample - loss: 7.0575e-05 - val_loss: 7.0400e-05
Epoch 59/150
9/9 [==============================] - 0s 899us/sample - loss: 1.9775e-05 - val_loss: 2.8230e-07
Epoch 60/150
9/9 [==============================] - 0s 816us/sample - loss: 1.6980e-05 - val_loss: 6.8329e-05
Epoch 61/150
9/9 [==============================] - 0s 834us/sample - loss: 5.0708e-05 - val_loss: 2.0270e-04
Epoch 62/150
9/9 [==============================] - 0s 942us/sample - loss: 9.9443e-05 - val_loss: 3.2668e-04
Epoch 63/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.4064e-04 - val_loss: 3.8528e-04
Epoch 64/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.5855e-04 - val_loss: 3.5985e-04
Epoch 65/150
9/9 [==============================] - 0s 929us/sample - loss: 1.4844e-04 - val_loss: 2.6773e-04
Epoch 66/150
9/9 [==============================] - 0s 808us/sample - loss: 1.1637e-04 - val_loss: 1.4952e-04
Epoch 67/150
9/9 [==============================] - 0s 785us/sample - loss: 7.5303e-05 - val_loss: 5.0371e-05
Epoch 68/150
9/9 [==============================] - 0s 1ms/sample - loss: 3.9458e-05 - val_loss: 2.4146e-06
Epoch 69/150
9/9 [==============================] - 0s 757us/sample - loss: 1.9015e-05 - val_loss: 1.4619e-05
Epoch 70/150
9/9 [==============================] - 0s 826us/sample - loss: 1.7072e-05 - val_loss: 7.2547e-05
Epoch 71/150
9/9 [==============================] - 0s 1ms/sample - loss: 2.9580e-05 - val_loss: 1.4686e-04
Epoch 72/150
9/9 [==============================] - 0s 857us/sample - loss: 4.7932e-05 - val_loss: 2.0623e-04
Epoch 73/150
9/9 [==============================] - 0s 771us/sample - loss: 6.2884e-05 - val_loss: 2.2919e-04
Epoch 74/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.8132e-05 - val_loss: 2.1050e-04
Epoch 75/150
9/9 [==============================] - 0s 708us/sample - loss: 6.2238e-05 - val_loss: 1.6050e-04
Epoch 76/150
9/9 [==============================] - 0s 889us/sample - loss: 4.8366e-05 - val_loss: 9.8577e-05
Epoch 77/150
9/9 [==============================] - 0s 840us/sample - loss: 3.2296e-05 - val_loss: 4.4432e-05
Epoch 78/150
9/9 [==============================] - 0s 869us/sample - loss: 1.9727e-05 - val_loss: 1.0770e-05
Epoch 79/150
9/9 [==============================] - 0s 753us/sample - loss: 1.4077e-05 - val_loss: 2.4313e-08
Epoch 80/150
9/9 [==============================] - 0s 804us/sample - loss: 1.5541e-05 - val_loss: 5.7214e-06
Epoch 81/150
9/9 [==============================] - 0s 840us/sample - loss: 2.1567e-05 - val_loss: 1.7056e-05
Epoch 82/150
9/9 [==============================] - 0s 740us/sample - loss: 2.8329e-05 - val_loss: 2.4330e-05
Epoch 83/150
9/9 [==============================] - 0s 747us/sample - loss: 3.2443e-05 - val_loss: 2.2877e-05
Epoch 84/150
9/9 [==============================] - 0s 723us/sample - loss: 3.2219e-05 - val_loss: 1.4200e-05
Epoch 85/150
9/9 [==============================] - 0s 730us/sample - loss: 2.8039e-05 - val_loss: 4.2480e-06
Epoch 86/150
9/9 [==============================] - 0s 751us/sample - loss: 2.1851e-05 - val_loss: 1.1093e-08
Epoch 87/150
9/9 [==============================] - 0s 854us/sample - loss: 1.6117e-05 - val_loss: 6.0833e-06
Epoch 88/150
9/9 [==============================] - 0s 760us/sample - loss: 1.2736e-05 - val_loss: 2.2631e-05
Epoch 89/150
9/9 [==============================] - 0s 710us/sample - loss: 1.2357e-05 - val_loss: 4.5442e-05
Epoch 90/150
9/9 [==============================] - 0s 745us/sample - loss: 1.4315e-05 - val_loss: 6.7822e-05
Epoch 91/150
9/9 [==============================] - 0s 759us/sample - loss: 1.7126e-05 - val_loss: 8.3294e-05
Epoch 92/150
9/9 [==============================] - 0s 811us/sample - loss: 1.9233e-05 - val_loss: 8.7945e-05
Epoch 93/150
9/9 [==============================] - 0s 829us/sample - loss: 1.9671e-05 - val_loss: 8.1520e-05
Epoch 94/150
9/9 [==============================] - 0s 800us/sample - loss: 1.8371e-05 - val_loss: 6.6964e-05
Epoch 95/150
9/9 [==============================] - 0s 877us/sample - loss: 1.6035e-05 - val_loss: 4.8896e-05
Epoch 96/150
9/9 [==============================] - 0s 766us/sample - loss: 1.3699e-05 - val_loss: 3.1748e-05
Epoch 97/150
9/9 [==============================] - 0s 853us/sample - loss: 1.2237e-05 - val_loss: 1.8402e-05
Epoch 98/150
9/9 [==============================] - 0s 790us/sample - loss: 1.2004e-05 - val_loss: 9.7389e-06
Epoch 99/150
9/9 [==============================] - 0s 742us/sample - loss: 1.2776e-05 - val_loss: 5.0838e-06
Epoch 100/150
9/9 [==============================] - 0s 807us/sample - loss: 1.3944e-05 - val_loss: 3.1372e-06
Epoch 101/150
9/9 [==============================] - 0s 746us/sample - loss: 1.4843e-05 - val_loss: 2.8800e-06
Epoch 102/150
9/9 [==============================] - 0s 707us/sample - loss: 1.5054e-05 - val_loss: 4.0295e-06
Epoch 103/150
9/9 [==============================] - 0s 874us/sample - loss: 1.4539e-05 - val_loss: 6.9329e-06
Epoch 104/150
9/9 [==============================] - 0s 710us/sample - loss: 1.3595e-05 - val_loss: 1.2056e-05
Epoch 105/150
9/9 [==============================] - 0s 840us/sample - loss: 1.2663e-05 - val_loss: 1.9409e-05
Epoch 106/150
9/9 [==============================] - 0s 750us/sample - loss: 1.2105e-05 - val_loss: 2.8216e-05
Epoch 107/150
9/9 [==============================] - 0s 838us/sample - loss: 1.2058e-05 - val_loss: 3.7000e-05
Epoch 108/150
9/9 [==============================] - 0s 714us/sample - loss: 1.2408e-05 - val_loss: 4.4034e-05
Epoch 109/150
9/9 [==============================] - 0s 818us/sample - loss: 1.2882e-05 - val_loss: 4.7904e-05
Epoch 110/150
9/9 [==============================] - 0s 832us/sample - loss: 1.3207e-05 - val_loss: 4.7988e-05
Epoch 111/150
9/9 [==============================] - 0s 775us/sample - loss: 1.3224e-05 - val_loss: 4.4586e-05
Epoch 112/150
9/9 [==============================] - 0s 864us/sample - loss: 1.2949e-05 - val_loss: 3.8736e-05
Epoch 113/150
9/9 [==============================] - 0s 780us/sample - loss: 1.2533e-05 - val_loss: 3.1827e-05
Epoch 114/150
9/9 [==============================] - 0s 842us/sample - loss: 1.2168e-05 - val_loss: 2.5136e-05
Epoch 115/150
9/9 [==============================] - 0s 773us/sample - loss: 1.1989e-05 - val_loss: 1.9550e-05
Epoch 116/150
9/9 [==============================] - 0s 810us/sample - loss: 1.2024e-05 - val_loss: 1.5486e-05
Epoch 117/150
9/9 [==============================] - 0s 722us/sample - loss: 1.2196e-05 - val_loss: 1.2993e-05
Epoch 118/150
9/9 [==============================] - 0s 944us/sample - loss: 1.2379e-05 - val_loss: 1.1939e-05
Epoch 119/150
9/9 [==============================] - 0s 765us/sample - loss: 1.2467e-05 - val_loss: 1.2159e-05
Epoch 120/150
9/9 [==============================] - 0s 812us/sample - loss: 1.2419e-05 - val_loss: 1.3513e-05
Epoch 121/150
9/9 [==============================] - 0s 854us/sample - loss: 1.2267e-05 - val_loss: 1.5843e-05
Epoch 122/150
9/9 [==============================] - 0s 822us/sample - loss: 1.2091e-05 - val_loss: 1.8891e-05
Epoch 123/150
9/9 [==============================] - 0s 716us/sample - loss: 1.1968e-05 - val_loss: 2.2255e-05
Epoch 124/150
9/9 [==============================] - 0s 931us/sample - loss: 1.1937e-05 - val_loss: 2.5414e-05
Epoch 125/150
9/9 [==============================] - 0s 694us/sample - loss: 1.1987e-05 - val_loss: 2.7838e-05
Epoch 126/150
9/9 [==============================] - 0s 794us/sample - loss: 1.2071e-05 - val_loss: 2.9127e-05
Epoch 127/150
9/9 [==============================] - 0s 803us/sample - loss: 1.2132e-05 - val_loss: 2.9105e-05
Epoch 128/150
9/9 [==============================] - 0s 755us/sample - loss: 1.2140e-05 - val_loss: 2.7874e-05
Epoch 129/150
9/9 [==============================] - 0s 788us/sample - loss: 1.2092e-05 - val_loss: 2.5760e-05
Epoch 130/150
9/9 [==============================] - 0s 773us/sample - loss: 1.2018e-05 - val_loss: 2.3197e-05
Epoch 131/150
9/9 [==============================] - 0s 736us/sample - loss: 1.1955e-05 - val_loss: 2.0619e-05
Epoch 132/150
9/9 [==============================] - 0s 938us/sample - loss: 1.1928e-05 - val_loss: 1.8380e-05
Epoch 133/150
9/9 [==============================] - 0s 712us/sample - loss: 1.1940e-05 - val_loss: 1.6699e-05
Epoch 134/150
9/9 [==============================] - 0s 780us/sample - loss: 1.1974e-05 - val_loss: 1.5686e-05
Epoch 135/150
9/9 [==============================] - 0s 702us/sample - loss: 1.2007e-05 - val_loss: 1.5359e-05
Epoch 136/150
9/9 [==============================] - 0s 751us/sample - loss: 1.2019e-05 - val_loss: 1.5673e-05
Epoch 137/150
9/9 [==============================] - 0s 761us/sample - loss: 1.2004e-05 - val_loss: 1.6536e-05
Epoch 138/150
9/9 [==============================] - 0s 880us/sample - loss: 1.1974e-05 - val_loss: 1.7804e-05
Epoch 139/150
9/9 [==============================] - 0s 966us/sample - loss: 1.1944e-05 - val_loss: 1.9291e-05
Epoch 140/150
9/9 [==============================] - 0s 769us/sample - loss: 1.1928e-05 - val_loss: 2.0776e-05
Epoch 141/150
9/9 [==============================] - 0s 730us/sample - loss: 1.1930e-05 - val_loss: 2.2031e-05
Epoch 142/150
9/9 [==============================] - 0s 885us/sample - loss: 1.1944e-05 - val_loss: 2.2875e-05
Epoch 143/150
9/9 [==============================] - 0s 721us/sample - loss: 1.1959e-05 - val_loss: 2.3206e-05
Epoch 144/150
9/9 [==============================] - 0s 769us/sample - loss: 1.1965e-05 - val_loss: 2.3012e-05
Epoch 145/150
9/9 [==============================] - 0s 803us/sample - loss: 1.1960e-05 - val_loss: 2.2382e-05
Epoch 146/150
9/9 [==============================] - 0s 793us/sample - loss: 1.1946e-05 - val_loss: 2.1463e-05
Epoch 147/150
9/9 [==============================] - 0s 853us/sample - loss: 1.1933e-05 - val_loss: 2.0436e-05
Epoch 148/150
9/9 [==============================] - 0s 804us/sample - loss: 1.1924e-05 - val_loss: 1.9467e-05
Epoch 149/150
9/9 [==============================] - 0s 715us/sample - loss: 1.1924e-05 - val_loss: 1.8698e-05
Epoch 150/150
9/9 [==============================] - 0s 717us/sample - loss: 1.1930e-05 - val_loss: 1.8213e-05
MSE:  4.058867016844987e-05
Time:  2.6944892699830234

Other Things to Try

Changing the size of the recurrent neural network and its parameters can drastically change the results you get from the model. The below code takes the simple recurrent neural network from above and adds a second hidden layer, changes the number of neurons in the hidden layer, and explicitly declares the activation function of the hidden layers to be a sigmoid function. The loss function and optimizer can also be changed but are kept the same as the above network. These parameters can be tuned to provide the optimal result from the network. For some ideas on how to improve the performance of a recurrent neural network.

In [6]:
def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):
    """
        Inputs:
            length_of_sequences (an int): the number of y values in "x data".  This is determined
                when the data is formatted
            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
        Returns:
            model (a Keras model): The recurrent neural network that is built and compiled by this
                method
        Builds and compiles a recurrent neural network with two hidden layers and returns the model.
    """
    # Number of neurons in the input and output layers
    in_out_neurons = 1
    # Number of neurons in the hidden layer, increased from the first network
    hidden_neurons = 500
    # Define the input layer
    inp = Input(batch_shape=(batch_size, 
                length_of_sequences, 
                in_out_neurons))  
    # Create two hidden layers instead of one hidden layer.  Explicitly set the activation
    # function to be the sigmoid function (the default value is hyperbolic tangent)
    rnn1 = SimpleRNN(hidden_neurons, 
                    return_sequences=True,  # This needs to be True if another hidden layer is to follow
                    stateful = stateful, activation = 'sigmoid',
                    name="RNN1")(inp)
    rnn2 = SimpleRNN(hidden_neurons, 
                    return_sequences=False, activation = 'sigmoid',
                    stateful = stateful,
                    name="RNN2")(rnn1)
    # Define the output layer as a dense neural network layer (standard neural network layer)
    #and add it to the network immediately after the hidden layer.
    dens = Dense(in_out_neurons,name="dense")(rnn2)
    # Create the machine learning model starting with the input layer and ending with the 
    # output layer
    model = Model(inputs=[inp],outputs=[dens])
    # Compile the machine learning model using the mean squared error function as the loss 
    # function and an Adams optimizer.
    model.compile(loss="mean_squared_error", optimizer="adam")  
    return model

# Check to make sure the data set is complete
assert len(X_tot) == len(y_tot)

# This is the number of points that will be used in as the training data
dim=12

# Separate the training data from the whole data set
X_train = X_tot[:dim]
y_train = y_tot[:dim]


# Generate the training data for the RNN, using a sequence of 2
rnn_input, rnn_training = format_data(y_train, 2)


# Create a recurrent neural network in Keras and produce a summary of the 
# machine learning model
model = rnn_2layers(length_of_sequences = 2)
model.summary()

# Start the timer.  Want to time training+testing
start = timer()
# Fit the model using the training data genenerated above using 150 training iterations and a 5%
# validation split.  Setting verbose to True prints information about each training iteration.
hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
                 verbose=True,validation_split=0.05)


# This section plots the training loss and the validation loss as a function of training iteration.
# This is not required for analyzing the couple cluster data but can help determine if the network is
# being overtrained.
for label in ["loss","val_loss"]:
    plt.plot(hist.history[label],label=label)

plt.ylabel("loss")
plt.xlabel("epoch")
plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
plt.legend()
plt.show()

# Use the trained neural network to predict more points of the data set
test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
# Stop the timer and calculate the total time needed.
end = timer()
print('Time: ', end-start)
Model: "model_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_2 (InputLayer)         [(None, 2, 1)]            0         
_________________________________________________________________
RNN1 (SimpleRNN)             (None, 2, 500)            251000    
_________________________________________________________________
RNN2 (SimpleRNN)             (None, 500)               500500    
_________________________________________________________________
dense (Dense)                (None, 1)                 501       
=================================================================
Total params: 752,001
Trainable params: 752,001
Non-trainable params: 0
_________________________________________________________________
Train on 9 samples, validate on 1 samples
Epoch 1/150
9/9 [==============================] - 1s 144ms/sample - loss: 0.9308 - val_loss: 5.2922
Epoch 2/150
9/9 [==============================] - 0s 1ms/sample - loss: 7.4592 - val_loss: 0.4159
Epoch 3/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.1833 - val_loss: 1.7606
Epoch 4/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.8576 - val_loss: 4.9398
Epoch 5/150
9/9 [==============================] - 0s 3ms/sample - loss: 3.2772 - val_loss: 3.7854
Epoch 6/150
9/9 [==============================] - 0s 4ms/sample - loss: 2.3581 - val_loss: 1.2405
Epoch 7/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.5185 - val_loss: 0.0361
Epoch 8/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0965 - val_loss: 0.2449
Epoch 9/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.8848 - val_loss: 0.6068
Epoch 10/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.4868 - val_loss: 0.4607
Epoch 11/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.2558 - val_loss: 0.0942
Epoch 12/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.5748 - val_loss: 0.0386
Epoch 13/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0934 - val_loss: 0.4789
Epoch 14/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.1143 - val_loss: 1.1294
Epoch 15/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.4510 - val_loss: 1.5341
Epoch 16/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.7068 - val_loss: 1.4615
Epoch 17/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.6594 - val_loss: 1.0237
Epoch 18/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.3886 - val_loss: 0.5085
Epoch 19/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.1262 - val_loss: 0.1506
Epoch 20/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0432 - val_loss: 0.0113
Epoch 21/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.1421 - val_loss: 0.0064
Epoch 22/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.2946 - val_loss: 0.0209
Epoch 23/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.3638 - val_loss: 0.0080
Epoch 24/150
9/9 [==============================] - 0s 4ms/sample - loss: 0.3042 - val_loss: 0.0037
Epoch 25/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.1728 - val_loss: 0.0714
Epoch 26/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0661 - val_loss: 0.2337
Epoch 27/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0456 - val_loss: 0.4439
Epoch 28/150
9/9 [==============================] - 0s 3ms/sample - loss: 0.1012 - val_loss: 0.6127
Epoch 29/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.1716 - val_loss: 0.6665
Epoch 30/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.1970 - val_loss: 0.5910
Epoch 31/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.1617 - val_loss: 0.4320
Epoch 32/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0970 - val_loss: 0.2603
Epoch 33/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0496 - val_loss: 0.1296
Epoch 34/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0458 - val_loss: 0.0560
Epoch 35/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0763 - val_loss: 0.0264
Epoch 36/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.1094 - val_loss: 0.0218
Epoch 37/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.1173 - val_loss: 0.0359
Epoch 38/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0960 - val_loss: 0.0754
Epoch 39/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0636 - val_loss: 0.1459
Epoch 40/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0434 - val_loss: 0.2377
Epoch 41/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0461 - val_loss: 0.3245
Epoch 42/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0636 - val_loss: 0.3760
Epoch 43/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0783 - val_loss: 0.3751
Epoch 44/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0781 - val_loss: 0.3266
Epoch 45/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0641 - val_loss: 0.2525
Epoch 46/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0483 - val_loss: 0.1786
Epoch 47/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0418 - val_loss: 0.1226
Epoch 48/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0469 - val_loss: 0.0900
Epoch 49/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0566 - val_loss: 0.0791
Epoch 50/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0615 - val_loss: 0.0871
Epoch 51/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0577 - val_loss: 0.1129
Epoch 52/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0491 - val_loss: 0.1538
Epoch 53/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0426 - val_loss: 0.2023
Epoch 54/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0425 - val_loss: 0.2456
Epoch 55/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0472 - val_loss: 0.2706
Epoch 56/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0514 - val_loss: 0.2700
Epoch 57/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0513 - val_loss: 0.2463
Epoch 58/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0473 - val_loss: 0.2093
Epoch 59/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0430 - val_loss: 0.1712
Epoch 60/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0417 - val_loss: 0.1413
Epoch 61/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0437 - val_loss: 0.1243
Epoch 62/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0463 - val_loss: 0.1210
Epoch 63/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0470 - val_loss: 0.1306
Epoch 64/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0452 - val_loss: 0.1508
Epoch 65/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0427 - val_loss: 0.1771
Epoch 66/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0416 - val_loss: 0.2028
Epoch 67/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0424 - val_loss: 0.2206
Epoch 68/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0440 - val_loss: 0.2256
Epoch 69/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0445 - val_loss: 0.2171
Epoch 70/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0436 - val_loss: 0.1991
Epoch 71/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0422 - val_loss: 0.1779
Epoch 72/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0415 - val_loss: 0.1595
Epoch 73/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0420 - val_loss: 0.1479
Epoch 74/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0428 - val_loss: 0.1449
Epoch 75/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0431 - val_loss: 0.1502
Epoch 76/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0426 - val_loss: 0.1622
Epoch 77/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0418 - val_loss: 0.1773
Epoch 78/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0415 - val_loss: 0.1914
Epoch 79/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0418 - val_loss: 0.2005
Epoch 80/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0422 - val_loss: 0.2020
Epoch 81/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0423 - val_loss: 0.1962
Epoch 82/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0419 - val_loss: 0.1855
Epoch 83/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0415 - val_loss: 0.1736
Epoch 84/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0414 - val_loss: 0.1639
Epoch 85/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0416 - val_loss: 0.1588
Epoch 86/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0418 - val_loss: 0.1589
Epoch 87/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0418 - val_loss: 0.1640
Epoch 88/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0416 - val_loss: 0.1721
Epoch 89/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0414 - val_loss: 0.1808
Epoch 90/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0414 - val_loss: 0.1875
Epoch 91/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0415 - val_loss: 0.1902
Epoch 92/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0416 - val_loss: 0.1884
Epoch 93/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0415 - val_loss: 0.1831
Epoch 94/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0414 - val_loss: 0.1762
Epoch 95/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0413 - val_loss: 0.1700
Epoch 96/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0413 - val_loss: 0.1662
Epoch 97/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0414 - val_loss: 0.1656
Epoch 98/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0414 - val_loss: 0.1680
Epoch 99/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0413 - val_loss: 0.1726
Epoch 100/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0412 - val_loss: 0.1777
Epoch 101/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0412 - val_loss: 0.1817
Epoch 102/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0412 - val_loss: 0.1834
Epoch 103/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0413 - val_loss: 0.1824
Epoch 104/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0412 - val_loss: 0.1792
Epoch 105/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0412 - val_loss: 0.1752
Epoch 106/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0411 - val_loss: 0.1716
Epoch 107/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0411 - val_loss: 0.1695
Epoch 108/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0411 - val_loss: 0.1694
Epoch 109/150
9/9 [==============================] - 0s 3ms/sample - loss: 0.0411 - val_loss: 0.1711
Epoch 110/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0411 - val_loss: 0.1739
Epoch 111/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0411 - val_loss: 0.1768
Epoch 112/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0411 - val_loss: 0.1788
Epoch 113/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0411 - val_loss: 0.1793
Epoch 114/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0411 - val_loss: 0.1783
Epoch 115/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0410 - val_loss: 0.1762
Epoch 116/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0410 - val_loss: 0.1737
Epoch 117/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0410 - val_loss: 0.1718
Epoch 118/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0410 - val_loss: 0.1710
Epoch 119/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0410 - val_loss: 0.1714
Epoch 120/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0410 - val_loss: 0.1728
Epoch 121/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0409 - val_loss: 0.1746
Epoch 122/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0409 - val_loss: 0.1761
Epoch 123/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0409 - val_loss: 0.1768
Epoch 124/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0409 - val_loss: 0.1765
Epoch 125/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0409 - val_loss: 0.1754
Epoch 126/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0409 - val_loss: 0.1740
Epoch 127/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0408 - val_loss: 0.1726
Epoch 128/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0408 - val_loss: 0.1719
Epoch 129/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0408 - val_loss: 0.1719
Epoch 130/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0408 - val_loss: 0.1725
Epoch 131/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0408 - val_loss: 0.1735
Epoch 132/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0408 - val_loss: 0.1745
Epoch 133/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0407 - val_loss: 0.1750
Epoch 134/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0407 - val_loss: 0.1749
Epoch 135/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0407 - val_loss: 0.1743
Epoch 136/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0407 - val_loss: 0.1734
Epoch 137/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0407 - val_loss: 0.1726
Epoch 138/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0407 - val_loss: 0.1720
Epoch 139/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0407 - val_loss: 0.1720
Epoch 140/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0406 - val_loss: 0.1723
Epoch 141/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0406 - val_loss: 0.1729
Epoch 142/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0406 - val_loss: 0.1734
Epoch 143/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0406 - val_loss: 0.1737
Epoch 144/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0406 - val_loss: 0.1736
Epoch 145/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0406 - val_loss: 0.1732
Epoch 146/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0405 - val_loss: 0.1726
Epoch 147/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0405 - val_loss: 0.1721
Epoch 148/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0405 - val_loss: 0.1718
Epoch 149/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0405 - val_loss: 0.1717
Epoch 150/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0405 - val_loss: 0.1719
MSE:  0.32999046353248707
Time:  4.114079531747848

Other Types of Recurrent Neural Networks

Besides a simple recurrent neural network layer, there are two other commonly used types of recurrent neural network layers: Long Short Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short introduction to these layers see https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b and https://medium.com/mindboard/lstm-vs-gru-experimental-comparison-955820c21e8b.

The first network created below is similar to the previous network, but it replaces the SimpleRNN layers with LSTM layers. The second network below has two hidden layers made up of GRUs, which are preceeded by two dense (feeddorward) neural network layers. These dense layers "preprocess" the data before it reaches the recurrent layers. This architecture has been shown to improve the performance of recurrent neural networks (see the link above and also https://arxiv.org/pdf/1807.02857.pdf.

In [7]:
def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):
    """
        Inputs:
            length_of_sequences (an int): the number of y values in "x data".  This is determined
                when the data is formatted
            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
        Returns:
            model (a Keras model): The recurrent neural network that is built and compiled by this
                method
        Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.
    """
    # Number of neurons on the input/output layer and the number of neurons in the hidden layer
    in_out_neurons = 1
    hidden_neurons = 250
    # Input Layer
    inp = Input(batch_shape=(batch_size, 
                length_of_sequences, 
                in_out_neurons)) 
    # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)
    rnn= LSTM(hidden_neurons, 
                    return_sequences=True,
                    stateful = stateful,
                    name="RNN", use_bias=True, activation='tanh')(inp)
    rnn1 = LSTM(hidden_neurons, 
                    return_sequences=False,
                    stateful = stateful,
                    name="RNN1", use_bias=True, activation='tanh')(rnn)
    # Output layer
    dens = Dense(in_out_neurons,name="dense")(rnn1)
    # Define the midel
    model = Model(inputs=[inp],outputs=[dens])
    # Compile the model
    model.compile(loss='mean_squared_error', optimizer='adam')  
    # Return the model
    return model

def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):
    """
        Inputs:
            length_of_sequences (an int): the number of y values in "x data".  This is determined
                when the data is formatted
            batch_size (an int): Default value is None.  See Keras documentation of SimpleRNN.
            stateful (a boolean): Default value is False.  See Keras documentation of SimpleRNN.
        Returns:
            model (a Keras model): The recurrent neural network that is built and compiled by this
                method
        Builds and compiles a recurrent neural network with four hidden layers (two dense followed by
        two GRU layers) and returns the model.
    """    
    # Number of neurons on the input/output layers and hidden layers
    in_out_neurons = 1
    hidden_neurons = 250
    # Input layer
    inp = Input(batch_shape=(batch_size, 
                length_of_sequences, 
                in_out_neurons)) 
    # Hidden Dense (feedforward) layers
    dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)
    dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)
    # Hidden GRU layers
    rnn1 = GRU(hidden_neurons, 
                    return_sequences=True,
                    stateful = stateful,
                    name="RNN1", use_bias=True)(dnn1)
    rnn = GRU(hidden_neurons, 
                    return_sequences=False,
                    stateful = stateful,
                    name="RNN", use_bias=True)(rnn1)
    # Output layer
    dens = Dense(in_out_neurons,name="dense")(rnn)
    # Define the model
    model = Model(inputs=[inp],outputs=[dens])
    # Compile the mdoel
    model.compile(loss='mean_squared_error', optimizer='adam')  
    # Return the model
    return model

# Check to make sure the data set is complete
assert len(X_tot) == len(y_tot)

# This is the number of points that will be used in as the training data
dim=12

# Separate the training data from the whole data set
X_train = X_tot[:dim]
y_train = y_tot[:dim]


# Generate the training data for the RNN, using a sequence of 2
rnn_input, rnn_training = format_data(y_train, 2)


# Create a recurrent neural network in Keras and produce a summary of the 
# machine learning model
# Change the method name to reflect which network you want to use
model = dnn2_gru2(length_of_sequences = 2)
model.summary()

# Start the timer.  Want to time training+testing
start = timer()
# Fit the model using the training data genenerated above using 150 training iterations and a 5%
# validation split.  Setting verbose to True prints information about each training iteration.
hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, 
                 verbose=True,validation_split=0.05)


# This section plots the training loss and the validation loss as a function of training iteration.
# This is not required for analyzing the couple cluster data but can help determine if the network is
# being overtrained.
for label in ["loss","val_loss"]:
    plt.plot(hist.history[label],label=label)

plt.ylabel("loss")
plt.xlabel("epoch")
plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
plt.legend()
plt.show()

# Use the trained neural network to predict more points of the data set
test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])
# Stop the timer and calculate the total time needed.
end = timer()
print('Time: ', end-start)


# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)
# 
# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.

# Check to make sure the data set is complete
assert len(X_tot) == len(y_tot)

# This is the number of points that will be used in as the training data
dim=12

# Separate the training data from the whole data set
X_train = X_tot[:dim]
y_train = y_tot[:dim]

# Reshape the data for Keras specifications
X_train = X_train.reshape((dim, 1))
y_train = y_train.reshape((dim, 1))


# Create a recurrent neural network in Keras and produce a summary of the 
# machine learning model
# Set the sequence length to 1 for regular data formatting 
model = rnn(length_of_sequences = 1)
model.summary()

# Start the timer.  Want to time training+testing
start = timer()
# Fit the model using the training data genenerated above using 150 training iterations and a 5%
# validation split.  Setting verbose to True prints information about each training iteration.
hist = model.fit(X_train, y_train, batch_size=None, epochs=150, 
                 verbose=True,validation_split=0.05)


# This section plots the training loss and the validation loss as a function of training iteration.
# This is not required for analyzing the couple cluster data but can help determine if the network is
# being overtrained.
for label in ["loss","val_loss"]:
    plt.plot(hist.history[label],label=label)

plt.ylabel("loss")
plt.xlabel("epoch")
plt.title("The final validation loss: {}".format(hist.history["val_loss"][-1]))
plt.legend()
plt.show()

# Use the trained neural network to predict the remaining data points
X_pred = X_tot[dim:]
X_pred = X_pred.reshape((len(X_pred), 1))
y_model = model.predict(X_pred)
y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))

# Plot the known data set and the predicted data set.  The red box represents the region that was used
# for the training data.
fig, ax = plt.subplots()
ax.plot(X_tot, y_tot, label="true", linewidth=3)
ax.plot(X_tot, y_pred, 'g-.',label="predicted", linewidth=4)
ax.legend()
# Created a red region to represent the points used in the training data.
ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')
plt.show()

# Stop the timer and calculate the total time needed.
end = timer()
print('Time: ', end-start)
Model: "model_2"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_3 (InputLayer)         [(None, 2, 1)]            0         
_________________________________________________________________
dnn (Dense)                  (None, 2, 125)            250       
_________________________________________________________________
dnn1 (Dense)                 (None, 2, 125)            15750     
_________________________________________________________________
RNN1 (GRU)                   (None, 2, 250)            282750    
_________________________________________________________________
RNN (GRU)                    (None, 250)               376500    
_________________________________________________________________
dense (Dense)                (None, 1)                 251       
=================================================================
Total params: 675,501
Trainable params: 675,501
Non-trainable params: 0
_________________________________________________________________
Train on 9 samples, validate on 1 samples
Epoch 1/150
9/9 [==============================] - 3s 335ms/sample - loss: 0.2450 - val_loss: 0.6009
Epoch 2/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.1844 - val_loss: 0.4407
Epoch 3/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.1280 - val_loss: 0.2754
Epoch 4/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0726 - val_loss: 0.1180
Epoch 5/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0256 - val_loss: 0.0122
Epoch 6/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0062 - val_loss: 0.0182
Epoch 7/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0340 - val_loss: 0.0463
Epoch 8/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0533 - val_loss: 0.0251
Epoch 9/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0386 - val_loss: 0.0018
Epoch 10/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0170 - val_loss: 0.0069
Epoch 11/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0062 - val_loss: 0.0362
Epoch 12/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0074 - val_loss: 0.0714
Epoch 13/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0145 - val_loss: 0.0968
Epoch 14/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0209 - val_loss: 0.1061
Epoch 15/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0236 - val_loss: 0.0993
Epoch 16/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0219 - val_loss: 0.0804
Epoch 17/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0171 - val_loss: 0.0552
Epoch 18/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0111 - val_loss: 0.0303
Epoch 19/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0061 - val_loss: 0.0114
Epoch 20/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0039 - val_loss: 0.0017
Epoch 21/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0048 - val_loss: 1.7121e-04
Epoch 22/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0077 - val_loss: 0.0021
Epoch 23/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0099 - val_loss: 0.0026
Epoch 24/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0096 - val_loss: 0.0010
Epoch 25/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0069 - val_loss: 7.4865e-06
Epoch 26/150
9/9 [==============================] - 0s 3ms/sample - loss: 0.0037 - val_loss: 0.0019
Epoch 27/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0018 - val_loss: 0.0070
Epoch 28/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0017 - val_loss: 0.0131
Epoch 29/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0028 - val_loss: 0.0172
Epoch 30/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0039 - val_loss: 0.0176
Epoch 31/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0042 - val_loss: 0.0143
Epoch 32/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0035 - val_loss: 0.0088
Epoch 33/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0022 - val_loss: 0.0036
Epoch 34/150
9/9 [==============================] - 0s 2ms/sample - loss: 8.5005e-04 - val_loss: 4.4203e-04
Epoch 35/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.9905e-04 - val_loss: 2.7989e-04
Epoch 36/150
9/9 [==============================] - 0s 2ms/sample - loss: 4.0486e-04 - val_loss: 0.0022
Epoch 37/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0011 - val_loss: 0.0042
Epoch 38/150
9/9 [==============================] - 0s 1ms/sample - loss: 0.0016 - val_loss: 0.0045
Epoch 39/150
9/9 [==============================] - 0s 2ms/sample - loss: 0.0015 - val_loss: 0.0032
Epoch 40/150
9/9 [==============================] - 0s 1ms/sample - loss: 9.0520e-04 - val_loss: 0.0013
Epoch 41/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.7366e-04 - val_loss: 1.8062e-04
Epoch 42/150
9/9 [==============================] - 0s 2ms/sample - loss: 7.9785e-05 - val_loss: 5.6714e-05
Epoch 43/150
9/9 [==============================] - 0s 1ms/sample - loss: 3.6778e-04 - val_loss: 4.3541e-04
Epoch 44/150
9/9 [==============================] - 0s 2ms/sample - loss: 7.7541e-04 - val_loss: 6.0918e-04
Epoch 45/150
9/9 [==============================] - 0s 2ms/sample - loss: 9.4925e-04 - val_loss: 3.9626e-04
Epoch 46/150
9/9 [==============================] - 0s 2ms/sample - loss: 7.9547e-04 - val_loss: 6.2396e-05
Epoch 47/150
9/9 [==============================] - 0s 2ms/sample - loss: 4.6406e-04 - val_loss: 7.4306e-05
Epoch 48/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.9191e-04 - val_loss: 6.7534e-04
Epoch 49/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.3472e-04 - val_loss: 0.0016
Epoch 50/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.6807e-04 - val_loss: 0.0024
Epoch 51/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.2605e-04 - val_loss: 0.0024
Epoch 52/150
9/9 [==============================] - 0s 2ms/sample - loss: 4.5007e-04 - val_loss: 0.0018
Epoch 53/150
9/9 [==============================] - 0s 2ms/sample - loss: 3.1897e-04 - val_loss: 8.9950e-04
Epoch 54/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.4287e-04 - val_loss: 2.3903e-04
Epoch 55/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.7967e-05 - val_loss: 3.1655e-06
Epoch 56/150
9/9 [==============================] - 0s 1ms/sample - loss: 7.3665e-05 - val_loss: 7.2757e-05
Epoch 57/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.6136e-04 - val_loss: 1.9493e-04
Epoch 58/150
9/9 [==============================] - 0s 1ms/sample - loss: 2.2035e-04 - val_loss: 1.9998e-04
Epoch 59/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.0127e-04 - val_loss: 9.4887e-05
Epoch 60/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.2360e-04 - val_loss: 5.1504e-06
Epoch 61/150
9/9 [==============================] - 0s 2ms/sample - loss: 4.9139e-05 - val_loss: 3.8941e-05
Epoch 62/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.8798e-05 - val_loss: 1.8634e-04
Epoch 63/150
9/9 [==============================] - 0s 2ms/sample - loss: 6.4377e-05 - val_loss: 3.3108e-04
Epoch 64/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.1325e-04 - val_loss: 3.5745e-04
Epoch 65/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.2908e-04 - val_loss: 2.5042e-04
Epoch 66/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.0075e-04 - val_loss: 9.8608e-05
Epoch 67/150
9/9 [==============================] - 0s 1ms/sample - loss: 5.6099e-05 - val_loss: 7.8389e-06
Epoch 68/150
9/9 [==============================] - 0s 1ms/sample - loss: 3.1440e-05 - val_loss: 1.4748e-05
Epoch 69/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.0217e-05 - val_loss: 7.2811e-05
Epoch 70/150
9/9 [==============================] - 0s 2ms/sample - loss: 6.5820e-05 - val_loss: 1.0793e-04
Epoch 71/150
9/9 [==============================] - 0s 2ms/sample - loss: 8.0192e-05 - val_loss: 8.5110e-05
Epoch 72/150
9/9 [==============================] - 0s 2ms/sample - loss: 6.9576e-05 - val_loss: 3.0754e-05
Epoch 73/150
9/9 [==============================] - 0s 2ms/sample - loss: 4.3596e-05 - val_loss: 1.5006e-07
Epoch 74/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.3801e-05 - val_loss: 2.4427e-05
Epoch 75/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.2519e-05 - val_loss: 8.4345e-05
Epoch 76/150
9/9 [==============================] - 0s 2ms/sample - loss: 3.4223e-05 - val_loss: 1.3076e-04
Epoch 77/150
9/9 [==============================] - 0s 2ms/sample - loss: 4.3072e-05 - val_loss: 1.2920e-04
Epoch 78/150
9/9 [==============================] - 0s 2ms/sample - loss: 3.8694e-05 - val_loss: 8.6107e-05
Epoch 79/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.4764e-05 - val_loss: 3.5628e-05
Epoch 80/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.3666e-05 - val_loss: 6.0901e-06
Epoch 81/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.3351e-05 - val_loss: 6.5202e-08
Epoch 82/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.0531e-05 - val_loss: 2.3852e-06
Epoch 83/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.5462e-05 - val_loss: 1.4359e-06
Epoch 84/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.2309e-05 - val_loss: 2.7095e-07
Epoch 85/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.3926e-05 - val_loss: 8.9544e-06
Epoch 86/150
9/9 [==============================] - 0s 2ms/sample - loss: 8.1545e-06 - val_loss: 2.9798e-05
Epoch 87/150
9/9 [==============================] - 0s 1ms/sample - loss: 7.9122e-06 - val_loss: 5.1986e-05
Epoch 88/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.1202e-05 - val_loss: 6.0481e-05
Epoch 89/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.3116e-05 - val_loss: 4.9656e-05
Epoch 90/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.1011e-05 - val_loss: 2.7833e-05
Epoch 91/150
9/9 [==============================] - 0s 2ms/sample - loss: 6.6973e-06 - val_loss: 8.9163e-06
Epoch 92/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.0061e-06 - val_loss: 6.4231e-07
Epoch 93/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.6626e-06 - val_loss: 5.3801e-07
Epoch 94/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.8445e-06 - val_loss: 1.6904e-06
Epoch 95/150
9/9 [==============================] - 0s 1ms/sample - loss: 7.5918e-06 - val_loss: 7.6062e-07
Epoch 96/150
9/9 [==============================] - 0s 1ms/sample - loss: 5.9006e-06 - val_loss: 9.0495e-08
Epoch 97/150
9/9 [==============================] - 0s 1ms/sample - loss: 3.3952e-06 - val_loss: 3.1808e-06
Epoch 98/150
9/9 [==============================] - 0s 1ms/sample - loss: 2.2665e-06 - val_loss: 9.5475e-06
Epoch 99/150
9/9 [==============================] - 0s 1ms/sample - loss: 2.9746e-06 - val_loss: 1.4636e-05
Epoch 100/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.0707e-06 - val_loss: 1.4411e-05
Epoch 101/150
9/9 [==============================] - 0s 1ms/sample - loss: 3.9976e-06 - val_loss: 9.2965e-06
Epoch 102/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.7187e-06 - val_loss: 3.3834e-06
Epoch 103/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.4985e-06 - val_loss: 2.8700e-07
Epoch 104/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.3560e-06 - val_loss: 2.5170e-07
Epoch 105/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.0148e-06 - val_loss: 1.0536e-06
Epoch 106/150
9/9 [==============================] - 0s 2ms/sample - loss: 2.4210e-06 - val_loss: 9.4288e-07
Epoch 107/150
9/9 [==============================] - 0s 1ms/sample - loss: 2.0210e-06 - val_loss: 2.0043e-07
Epoch 108/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.2760e-06 - val_loss: 9.3241e-08
Epoch 109/150
9/9 [==============================] - 0s 2ms/sample - loss: 9.1140e-07 - val_loss: 1.0255e-06
Epoch 110/150
9/9 [==============================] - 0s 3ms/sample - loss: 1.1163e-06 - val_loss: 2.0734e-06
Epoch 111/150
9/9 [==============================] - 0s 2ms/sample - loss: 1.5079e-06 - val_loss: 2.1360e-06
Epoch 112/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.5815e-06 - val_loss: 1.1905e-06
Epoch 113/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.2618e-06 - val_loss: 2.1615e-07
Epoch 114/150
9/9 [==============================] - 0s 2ms/sample - loss: 9.0721e-07 - val_loss: 4.4045e-08
Epoch 115/150
9/9 [==============================] - 0s 1ms/sample - loss: 8.5203e-07 - val_loss: 5.2731e-07
Epoch 116/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.0535e-06 - val_loss: 8.8510e-07
Epoch 117/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.2045e-06 - val_loss: 6.6195e-07
Epoch 118/150
9/9 [==============================] - 0s 1ms/sample - loss: 1.1108e-06 - val_loss: 1.7027e-07
Epoch 119/150
9/9 [==============================] - 0s 1ms/sample - loss: 8.8165e-07 - val_loss: 1.3454e-08
Epoch 120/150
9/9 [==============================] - 0s 2ms/sample - loss: 7.5757e-07 - val_loss: 3.5848e-07
Epoch 121/150
9/9 [==============================] - 0s 2ms/sample - loss: 8.2259e-07 - val_loss: 7.9404e-07
Epoch 122/150
9/9 [==============================] - 0s 1ms/sample - loss: 9.3780e-07 - val_loss: 8.4859e-07
Epoch 123/150
9/9 [==============================] - 0s 1ms/sample - loss: 9.3325e-07 - val_loss: 4.9981e-07
Epoch 124/150
9/9 [==============================] - 0s 1ms/sample - loss: 8.0209e-07 - val_loss: 1.1783e-07
Epoch 125/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.8127e-07 - val_loss: 1.2367e-09
Epoch 126/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.7296e-07 - val_loss: 9.0101e-08
Epoch 127/150
9/9 [==============================] - 0s 1ms/sample - loss: 7.3688e-07 - val_loss: 1.3718e-07
Epoch 128/150
9/9 [==============================] - 0s 1ms/sample - loss: 7.6058e-07 - val_loss: 5.4509e-08
Epoch 129/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.9898e-07 - val_loss: 3.0727e-09
Epoch 130/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.1337e-07 - val_loss: 1.5863e-07
Epoch 131/150
9/9 [==============================] - 0s 1ms/sample - loss: 5.8245e-07 - val_loss: 4.7443e-07
Epoch 132/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.0891e-07 - val_loss: 7.1950e-07
Epoch 133/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.3010e-07 - val_loss: 7.2092e-07
Epoch 134/150
9/9 [==============================] - 0s 1ms/sample - loss: 6.0220e-07 - val_loss: 5.1706e-07
Epoch 135/150
9/9 [==============================] - 0s 1ms/sample - loss: 5.4799e-07 - val_loss: 2.7801e-07
Epoch 136/150
9/9 [==============================] - 0s 1ms/sample - loss: 5.1885e-07 - val_loss: 1.2662e-07
Epoch 137/150
9/9 [==============================] - 0s 1ms/sample - loss: 5.2879e-07 - val_loss: 7.3679e-08
Epoch 138/150
9/9 [==============================] - 0s 1ms/sample - loss: 5.4436e-07 - val_loss: 9.2370e-08
Epoch 139/150
9/9 [==============================] - 0s 1ms/sample - loss: 5.3233e-07 - val_loss: 1.9250e-07
Epoch 140/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.9874e-07 - val_loss: 3.9243e-07
Epoch 141/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.7515e-07 - val_loss: 6.4432e-07
Epoch 142/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.7633e-07 - val_loss: 8.3209e-07
Epoch 143/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.8560e-07 - val_loss: 8.5983e-07
Epoch 144/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.8017e-07 - val_loss: 7.3240e-07
Epoch 145/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.5959e-07 - val_loss: 5.4099e-07
Epoch 146/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.4210e-07 - val_loss: 3.8153e-07
Epoch 147/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.3915e-07 - val_loss: 3.0024e-07
Epoch 148/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.4251e-07 - val_loss: 3.0372e-07
Epoch 149/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.3802e-07 - val_loss: 3.8797e-07
Epoch 150/150
9/9 [==============================] - 0s 1ms/sample - loss: 4.2399e-07 - val_loss: 5.3906e-07
MSE:  6.359714873271884e-05
Time:  6.279334420338273
Model: "model_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_4 (InputLayer)         [(None, 1, 1)]            0         
_________________________________________________________________
RNN (SimpleRNN)              (None, 200)               40400     
_________________________________________________________________
dense (Dense)                (None, 1)                 201       
=================================================================
Total params: 40,601
Trainable params: 40,601
Non-trainable params: 0
_________________________________________________________________
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-6c4ebdf72ad9> in <module>
    155 # validation split.  Setting verbose to True prints information about each training iteration.
    156 hist = model.fit(X_train, y_train, batch_size=None, epochs=150, 
--> 157                  verbose=True,validation_split=0.05)
    158 
    159 

~/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    817         max_queue_size=max_queue_size,
    818         workers=workers,
--> 819         use_multiprocessing=use_multiprocessing)
    820 
    821   def evaluate(self,

~/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    233           max_queue_size=max_queue_size,
    234           workers=workers,
--> 235           use_multiprocessing=use_multiprocessing)
    236 
    237       total_samples = _get_total_number_of_samples(training_data_adapter)

~/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py in _process_training_inputs(model, x, y, batch_size, epochs, sample_weights, class_weights, steps_per_epoch, validation_split, validation_data, validation_steps, shuffle, distribution_strategy, max_queue_size, workers, use_multiprocessing)
    550         batch_size=batch_size,
    551         check_steps=False,
--> 552         steps=steps_per_epoch)
    553     (x, y, sample_weights,
    554      val_x, val_y,

~/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset)
   2381         is_dataset=is_dataset,
   2382         class_weight=class_weight,
-> 2383         batch_size=batch_size)
   2384 
   2385   def _standardize_tensors(self, x, y, sample_weight, run_eagerly, dict_inputs,

~/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py in _standardize_tensors(self, x, y, sample_weight, run_eagerly, dict_inputs, is_dataset, class_weight, batch_size)
   2408           feed_input_shapes,
   2409           check_batch_axis=False,  # Don't enforce the batch size.
-> 2410           exception_prefix='input')
   2411 
   2412     # Get typespecs for the input data and sanitize it if necessary.

~/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    571                            ': expected ' + names[i] + ' to have ' +
    572                            str(len(shape)) + ' dimensions, but got array '
--> 573                            'with shape ' + str(data_shape))
    574         if not check_batch_axis:
    575           data_shape = data_shape[1:]

ValueError: Error when checking input: expected input_4 to have 3 dimensions, but got array with shape (12, 1)
In [ ]: