Experimenting With Models

Build. Fit. Evaluate. ReBuild. ReFit. ReEvaluate. ReBuild. ReFit...

  • use more data
  • change number of layers
  • change the number of "units" in each layer
  • train for longer

Imports

In [1]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd

Mock Some Data

In [2]:
X = np.arange(-100, 100, 4)
y = np.arange(-90,110,4)

Split Data Into Training + Testing

In [3]:
# Split data into train and test sets
X_train = X[:40] # first 40 examples (80% of data)
y_train = y[:40]

X_test = X[40:] # last 10 examples (20% of data)
y_test = y[40:]

Visualize

In [4]:
plt.figure(figsize=(10, 7))
# Plot training data in blue
plt.scatter(X_train, y_train, c='b', label='Training data')
# Plot test data in green
plt.scatter(X_test, y_test, c='g', label='Testing data')
# Show the legend
plt.legend();
output png

Begin Experimenting

Model 1

In [5]:
# for repeatability
tf.random.set_seed(42)

m1Epochs = 100
moreEpochs = 500
lessEpochs = 25

fittedXTrained = tf.expand_dims(X_train, axis=-1)

# BUILD
m1 = tf.keras.Sequential()
l1 = tf.keras.layers.Dense(1)
m1.add(l1)

# COMPILE
m1.compile(loss=tf.keras.losses.mae,
          optimizer=tf.keras.optimizers.SGD(),
          metrics=['mae'])

# FIT
m1.fit(fittedXTrained,y_train, epochs=m1Epochs)
Epoch 1/100
2/2 [==============================] - 1s 22ms/step - loss: 63.7147 - mae: 63.7147
Epoch 2/100
2/2 [==============================] - 0s 12ms/step - loss: 28.7626 - mae: 28.7626
Epoch 3/100
2/2 [==============================] - 0s 12ms/step - loss: 10.6471 - mae: 10.6471
Epoch 4/100
2/2 [==============================] - 0s 12ms/step - loss: 13.1998 - mae: 13.1998
Epoch 5/100
2/2 [==============================] - 0s 12ms/step - loss: 12.2716 - mae: 12.2716
Epoch 6/100
2/2 [==============================] - 0s 11ms/step - loss: 9.4961 - mae: 9.4961
Epoch 7/100
2/2 [==============================] - 0s 12ms/step - loss: 8.6277 - mae: 8.6277
Epoch 8/100
2/2 [==============================] - 0s 12ms/step - loss: 9.0650 - mae: 9.0650
Epoch 9/100
2/2 [==============================] - 0s 12ms/step - loss: 18.8638 - mae: 18.8638
Epoch 10/100
2/2 [==============================] - 0s 11ms/step - loss: 10.1885 - mae: 10.1885
Epoch 11/100
2/2 [==============================] - 0s 12ms/step - loss: 8.4371 - mae: 8.4371
Epoch 12/100
2/2 [==============================] - 0s 12ms/step - loss: 10.7266 - mae: 10.7266
Epoch 13/100
2/2 [==============================] - 0s 12ms/step - loss: 9.8331 - mae: 9.8331
Epoch 14/100
2/2 [==============================] - 0s 15ms/step - loss: 16.1273 - mae: 16.1273
Epoch 15/100
2/2 [==============================] - 0s 12ms/step - loss: 11.3361 - mae: 11.3361
Epoch 16/100
2/2 [==============================] - 0s 12ms/step - loss: 8.5803 - mae: 8.5803
Epoch 17/100
2/2 [==============================] - 0s 12ms/step - loss: 13.7109 - mae: 13.7109
Epoch 18/100
2/2 [==============================] - 0s 14ms/step - loss: 11.5536 - mae: 11.5536
Epoch 19/100
2/2 [==============================] - 0s 12ms/step - loss: 17.8386 - mae: 17.8386
Epoch 20/100
2/2 [==============================] - 0s 15ms/step - loss: 14.9738 - mae: 14.9738
Epoch 21/100
2/2 [==============================] - 0s 17ms/step - loss: 10.8579 - mae: 10.8579
Epoch 22/100
2/2 [==============================] - 0s 14ms/step - loss: 8.6092 - mae: 8.6092
Epoch 23/100
2/2 [==============================] - 0s 14ms/step - loss: 9.7280 - mae: 9.7280
Epoch 24/100
2/2 [==============================] - 0s 16ms/step - loss: 10.9689 - mae: 10.9689
Epoch 25/100
2/2 [==============================] - 0s 14ms/step - loss: 9.1760 - mae: 9.1760
Epoch 26/100
2/2 [==============================] - 0s 14ms/step - loss: 13.2062 - mae: 13.2062
Epoch 27/100
2/2 [==============================] - 0s 14ms/step - loss: 10.6796 - mae: 10.6796
Epoch 28/100
2/2 [==============================] - 0s 15ms/step - loss: 12.8993 - mae: 12.8993
Epoch 29/100
2/2 [==============================] - 0s 15ms/step - loss: 9.5252 - mae: 9.5252
Epoch 30/100
2/2 [==============================] - 0s 15ms/step - loss: 16.4202 - mae: 16.4202
Epoch 31/100
2/2 [==============================] - 0s 13ms/step - loss: 23.5828 - mae: 23.5828
Epoch 32/100
2/2 [==============================] - 0s 13ms/step - loss: 7.6255 - mae: 7.6255
Epoch 33/100
2/2 [==============================] - 0s 13ms/step - loss: 9.3222 - mae: 9.3222
Epoch 34/100
2/2 [==============================] - 0s 14ms/step - loss: 13.6949 - mae: 13.6949
Epoch 35/100
2/2 [==============================] - 0s 14ms/step - loss: 11.1691 - mae: 11.1691
Epoch 36/100
2/2 [==============================] - 0s 15ms/step - loss: 13.3876 - mae: 13.3876
Epoch 37/100
2/2 [==============================] - 0s 13ms/step - loss: 9.4687 - mae: 9.4687
Epoch 38/100
2/2 [==============================] - 0s 14ms/step - loss: 10.1219 - mae: 10.1219
Epoch 39/100
2/2 [==============================] - 0s 14ms/step - loss: 10.2212 - mae: 10.2212
Epoch 40/100
2/2 [==============================] - 0s 20ms/step - loss: 10.9641 - mae: 10.9641
Epoch 41/100
2/2 [==============================] - 0s 19ms/step - loss: 7.9414 - mae: 7.9414
Epoch 42/100
2/2 [==============================] - 0s 19ms/step - loss: 10.5998 - mae: 10.5998
Epoch 43/100
2/2 [==============================] - 0s 12ms/step - loss: 7.2267 - mae: 7.2267
Epoch 44/100
2/2 [==============================] - 0s 11ms/step - loss: 8.0120 - mae: 8.0120
Epoch 45/100
2/2 [==============================] - 0s 12ms/step - loss: 9.8062 - mae: 9.8062
Epoch 46/100
2/2 [==============================] - 0s 12ms/step - loss: 8.8818 - mae: 8.8818
Epoch 47/100
2/2 [==============================] - 0s 12ms/step - loss: 7.5891 - mae: 7.5891
Epoch 48/100
2/2 [==============================] - 0s 14ms/step - loss: 8.5885 - mae: 8.5885
Epoch 49/100
2/2 [==============================] - 0s 12ms/step - loss: 10.0117 - mae: 10.0117
Epoch 50/100
2/2 [==============================] - 0s 12ms/step - loss: 9.0400 - mae: 9.0400
Epoch 51/100
2/2 [==============================] - 0s 12ms/step - loss: 10.6813 - mae: 10.6813
Epoch 52/100
2/2 [==============================] - 0s 12ms/step - loss: 15.3109 - mae: 15.3109
Epoch 53/100
2/2 [==============================] - 0s 12ms/step - loss: 14.3301 - mae: 14.3301
Epoch 54/100
2/2 [==============================] - 0s 12ms/step - loss: 21.6240 - mae: 21.6240
Epoch 55/100
2/2 [==============================] - 0s 12ms/step - loss: 15.9957 - mae: 15.9957
Epoch 56/100
2/2 [==============================] - 0s 12ms/step - loss: 10.3023 - mae: 10.3023
Epoch 57/100
2/2 [==============================] - 0s 14ms/step - loss: 9.7810 - mae: 9.7810
Epoch 58/100
2/2 [==============================] - 0s 12ms/step - loss: 9.0675 - mae: 9.0675
Epoch 59/100
2/2 [==============================] - 0s 12ms/step - loss: 8.2701 - mae: 8.2701
Epoch 60/100
2/2 [==============================] - 0s 12ms/step - loss: 9.3692 - mae: 9.3692
Epoch 61/100
2/2 [==============================] - 0s 12ms/step - loss: 11.1774 - mae: 11.1774
Epoch 62/100
2/2 [==============================] - 0s 12ms/step - loss: 12.0914 - mae: 12.0914
Epoch 63/100
2/2 [==============================] - 0s 12ms/step - loss: 7.2832 - mae: 7.2832
Epoch 64/100
2/2 [==============================] - 0s 12ms/step - loss: 12.4387 - mae: 12.4387
Epoch 65/100
2/2 [==============================] - 0s 12ms/step - loss: 10.5133 - mae: 10.5133
Epoch 66/100
2/2 [==============================] - 0s 12ms/step - loss: 15.6232 - mae: 15.6232
Epoch 67/100
2/2 [==============================] - 0s 12ms/step - loss: 10.0265 - mae: 10.0265
Epoch 68/100
2/2 [==============================] - 0s 12ms/step - loss: 8.7370 - mae: 8.7370
Epoch 69/100
2/2 [==============================] - 0s 12ms/step - loss: 13.5013 - mae: 13.5013
Epoch 70/100
2/2 [==============================] - 0s 12ms/step - loss: 7.4844 - mae: 7.4844
Epoch 71/100
2/2 [==============================] - 0s 12ms/step - loss: 12.2401 - mae: 12.2401
Epoch 72/100
2/2 [==============================] - 0s 12ms/step - loss: 8.5479 - mae: 8.5479
Epoch 73/100
2/2 [==============================] - 0s 12ms/step - loss: 7.0543 - mae: 7.0543
Epoch 74/100
2/2 [==============================] - 0s 12ms/step - loss: 9.9451 - mae: 9.9451
Epoch 75/100
2/2 [==============================] - 0s 12ms/step - loss: 9.9505 - mae: 9.9505
Epoch 76/100
2/2 [==============================] - 0s 12ms/step - loss: 10.1173 - mae: 10.1173
Epoch 77/100
2/2 [==============================] - 0s 12ms/step - loss: 12.9622 - mae: 12.9622
Epoch 78/100
2/2 [==============================] - 0s 12ms/step - loss: 11.1621 - mae: 11.1621
Epoch 79/100
2/2 [==============================] - 0s 12ms/step - loss: 14.7133 - mae: 14.7133
Epoch 80/100
2/2 [==============================] - 0s 12ms/step - loss: 8.9385 - mae: 8.9385
Epoch 81/100
2/2 [==============================] - 0s 14ms/step - loss: 10.7818 - mae: 10.7818
Epoch 82/100
2/2 [==============================] - 0s 12ms/step - loss: 8.4039 - mae: 8.4039
Epoch 83/100
2/2 [==============================] - 0s 12ms/step - loss: 9.2376 - mae: 9.2376
Epoch 84/100
2/2 [==============================] - 0s 12ms/step - loss: 8.9566 - mae: 8.9566
Epoch 85/100
2/2 [==============================] - 0s 12ms/step - loss: 13.2035 - mae: 13.2035
Epoch 86/100
2/2 [==============================] - 0s 12ms/step - loss: 13.7151 - mae: 13.7151
Epoch 87/100
2/2 [==============================] - 0s 12ms/step - loss: 13.1997 - mae: 13.1997
Epoch 88/100
2/2 [==============================] - 0s 12ms/step - loss: 11.5270 - mae: 11.5270
Epoch 89/100
2/2 [==============================] - 0s 12ms/step - loss: 7.8183 - mae: 7.8183
Epoch 90/100
2/2 [==============================] - 0s 12ms/step - loss: 10.9432 - mae: 10.9432
Epoch 91/100
2/2 [==============================] - 0s 12ms/step - loss: 6.7646 - mae: 6.7646
Epoch 92/100
2/2 [==============================] - 0s 12ms/step - loss: 10.1358 - mae: 10.1358
Epoch 93/100
2/2 [==============================] - 0s 12ms/step - loss: 7.6208 - mae: 7.6208
Epoch 94/100
2/2 [==============================] - 0s 12ms/step - loss: 9.2539 - mae: 9.2539
Epoch 95/100
2/2 [==============================] - 0s 12ms/step - loss: 10.8433 - mae: 10.8433
Epoch 96/100
2/2 [==============================] - 0s 12ms/step - loss: 10.3068 - mae: 10.3068
Epoch 97/100
2/2 [==============================] - 0s 12ms/step - loss: 7.6925 - mae: 7.6925
Epoch 98/100
2/2 [==============================] - 0s 12ms/step - loss: 8.6284 - mae: 8.6284
Epoch 99/100
2/2 [==============================] - 0s 12ms/step - loss: 9.4073 - mae: 9.4073
Epoch 100/100
2/2 [==============================] - 0s 12ms/step - loss: 8.8527 - mae: 8.8527
Out [5]:
<keras.src.callbacks.History at 0x7f4baf6790>

Predict some outputs

In [6]:
m1Predictions = m1.predict(X_test)
1/1 [==============================] - 0s 201ms/step
In [7]:
def plot_predictions(train_data=X_train, 
                     train_labels=y_train, 
                     test_data=X_test, 
                     test_labels=y_test, 
                     predictions=y_test):
  """
  Plots training data, test data and compares predictions.
  """
  plt.figure(figsize=(10, 7))
  # Plot training data in blue
  plt.scatter(train_data, train_labels, c="b", label="Training data")
  # Plot test data in green
  plt.scatter(test_data, test_labels, c="g", label="Testing data")
  # Plot the predictions in red (predictions were made on the test data)
  plt.scatter(test_data, predictions, c="r", label="Predictions")
  # Show the legend
  plt.legend();

def mae(y_test, y_pred):
  """
  Calculuates mean absolute error between y_test and y_preds.
  """
  return tf.metrics.mean_absolute_error(y_test,
                                        y_pred)
  
def mse(y_test, y_pred):
  """
  Calculates mean squared error between y_test and y_preds.
  """
  return tf.metrics.mean_squared_error(y_test,
                                       y_pred)

Visualize Test, Train, And Predictions

In [8]:
plot_predictions(predictions=m1Predictions)
output png

Calculate some model Stats

In [9]:
# Calculate model_1 metrics
mae_1 = mae(y_test, m1Predictions.squeeze()).numpy()
mse_1 = mse(y_test, m1Predictions.squeeze()).numpy()
mae_1, mse_1
Out [9]:
(8.585786, 80.21259)

Model 2: More Layers

Build

In [10]:
# BUILD
m2 = tf.keras.Sequential()
m2.add(l1)
m2.add(l1)

# COMPILE
m2.compile(loss=tf.keras.losses.mae,
                optimizer=tf.keras.optimizers.SGD(),
                metrics=['mae'])

# FIT
m2.fit(fittedXTrained, y_train, epochs=m1Epochs, verbose=0) # set verbose to 0 for less output
Out [10]:
<keras.src.callbacks.History at 0x7f49666b50>

Predict

In [11]:
predictionsM2 = m2.predict(X_test)
plot_predictions(predictions=predictionsM2)
1/1 [==============================] - 0s 120ms/step
output png

Get Model Stats

In [12]:
mae_2 = mae(y_test, predictionsM2.squeeze()).numpy()
mse_2 = mse(y_test, predictionsM2.squeeze()).numpy()
mae_2, mse_2
Out [12]:
(1.5568199, 3.6158714)

Model 3: More Epochs

Build

In [13]:
# BUILD
m3 = tf.keras.Sequential()
m3.add(l1)
m3.add(l1)

# COMPILE
m3.compile(loss=tf.keras.losses.mae,
                optimizer=tf.keras.optimizers.SGD(),
                metrics=['mae'])

# FIT
m3.fit(fittedXTrained, y_train, epochs=moreEpochs, verbose=0) # set verbose to 0 for less output
Out [13]:
<keras.src.callbacks.History at 0x7f49546d90>

Predict

In [14]:
predictionsM3 = m3.predict(X_test)
plot_predictions(predictions=predictionsM3)
1/1 [==============================] - 0s 119ms/step
output png

Get Model Stats

In [15]:
mae_3 = mae(y_test, predictionsM3.squeeze()).numpy()
mse_3 = mse(y_test, predictionsM3.squeeze()).numpy()
mae_3, mse_3
Out [15]:
(28.125193, 812.3425)

Model 4: less epochs

In [18]:
# BUILD
m4 = tf.keras.Sequential()
m4.add(l1)
m4.add(l1)

# COMPILE
m4.compile(loss=tf.keras.losses.mae,
                optimizer=tf.keras.optimizers.SGD(),
                metrics=['mae'])

# FIT
m4.fit(fittedXTrained, y_train, epochs=lessEpochs, verbose=0) # set verbose to 0 for less output



predictionsM4 = m4.predict(X_test)
plot_predictions(predictions=predictionsM4)
mae_4 = mae(y_test, predictionsM4.squeeze()).numpy()
mse_4 = mse(y_test, predictionsM4.squeeze()).numpy()
mae_4, mse_4
WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7f4ba6b1a0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
1/1 [==============================] - 0s 172ms/step
Out [18]:
(29.59107, 891.5161)
output png
In [19]:
resultsArray = [["model_1", mae_1, mse_1],
                 ["model_2", mae_2, mse_2],
                 ["model_3", mae_3, mae_3],
                ["model_4", mae_4, mae_4]
               ]

all_results = pd.DataFrame(resultsArray, columns=["model", "mae", "mse"])
all_results
Out [19]:
model mae mse
0 model_1 8.585786 80.212593
1 model_2 1.556820 3.615871
2 model_3 28.125193 28.125193
3 model_4 29.591070 29.591070