Table Of Contents

A One-To-One Model

In [24]:
import tensorflow as tf
import matplotlib.pyplot as plt
print(f'TF VERSION: {tf.__version__}')
TF VERSION: 2.14.0

Mock some data

In [2]:
indVarTensor = tf.range(-100,100,4)
indVarTensor
Out [2]:
<tf.Tensor: shape=(50,), dtype=int32, numpy=
array([-100,  -96,  -92,  -88,  -84,  -80,  -76,  -72,  -68,  -64,  -60,
        -56,  -52,  -48,  -44,  -40,  -36,  -32,  -28,  -24,  -20,  -16,
        -12,   -8,   -4,    0,    4,    8,   12,   16,   20,   24,   28,
         32,   36,   40,   44,   48,   52,   56,   60,   64,   68,   72,
         76,   80,   84,   88,   92,   96], dtype=int32)>
In [3]:
depVarTensor = indVarTensor * 10
depVarTensor
Out [3]:
<tf.Tensor: shape=(50,), dtype=int32, numpy=
array([-1000,  -960,  -920,  -880,  -840,  -800,  -760,  -720,  -680,
        -640,  -600,  -560,  -520,  -480,  -440,  -400,  -360,  -320,
        -280,  -240,  -200,  -160,  -120,   -80,   -40,     0,    40,
          80,   120,   160,   200,   240,   280,   320,   360,   400,
         440,   480,   520,   560,   600,   640,   680,   720,   760,
         800,   840,   880,   920,   960], dtype=int32)>
In [4]:
plt.scatter(indVarTensor, depVarTensor)
Out [4]:
<matplotlib.collections.PathCollection at 0x7f11975410>
output png

Split Data Into 3

  • Training: model learns from this data, typically 7080% of the data
  • Validation: model gets "tuned" on this, typically 10-15% of data
  • Test: the model's learning gets evaluated on this, typically 10-15% of data

Here, we'll split the data into training & validation. the Test data will be manual at the end.

In [5]:
len(depVarTensor)
Out [5]:
50
In [6]:
x_train = indVarTensor[:40] #first 40
y_train = depVarTensor[:40]  #last 10

x_test = indVarTensor[40:]
y_test = depVarTensor[40:]
In [7]:
plt.figure(figsize=(10, 7))
# TRAINING
plt.scatter(x_train, y_train, c='b', label='Training data')
# TESTING
plt.scatter(x_test, y_test, c='g', label='Testing data')
plt.legend();
output png

Create & Visualize a model

In [8]:
# increase repeatability
tf.random.set_seed(42)

m = tf.keras.Sequential()
# layers
mL1 = tf.keras.layers.Dense(1, input_shape=[1])
# mL2 = tf.keras.layers.Dense(1)
m.add(mL1)
# m.add(mL2)
m.compile(loss=tf.keras.losses.mae,
          # optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
          optimizer=tf.keras.optimizers.SGD(),
          metrics=["mae"])

Sumarizing the model

In [9]:
# https://www.tensorflow.org/api_docs/python/tf/keras/Model#summary
m.summary()
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense (Dense)               (None, 1)                 2         
                                                                 
=================================================================
Total params: 2 (8.00 Byte)
Trainable params: 2 (8.00 Byte)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________

Fit The Model To The Data

In [10]:
m.fit(tf.expand_dims(x_train, axis=-1), y_train, epochs=100, verbose=1)
Epoch 1/100
2/2 [==============================] - 1s 26ms/step - loss: 384.8997 - mae: 384.8997
Epoch 2/100
2/2 [==============================] - 0s 14ms/step - loss: 348.9157 - mae: 348.9157
Epoch 3/100
2/2 [==============================] - 0s 14ms/step - loss: 310.7949 - mae: 310.7949
Epoch 4/100
2/2 [==============================] - 0s 14ms/step - loss: 273.9105 - mae: 273.9105
Epoch 5/100
2/2 [==============================] - 0s 14ms/step - loss: 237.2411 - mae: 237.2411
Epoch 6/100
2/2 [==============================] - 0s 15ms/step - loss: 202.5008 - mae: 202.5008
Epoch 7/100
2/2 [==============================] - 0s 13ms/step - loss: 167.9083 - mae: 167.9083
Epoch 8/100
2/2 [==============================] - 0s 14ms/step - loss: 130.7788 - mae: 130.7788
Epoch 9/100
2/2 [==============================] - 0s 15ms/step - loss: 88.3749 - mae: 88.3749
Epoch 10/100
2/2 [==============================] - 0s 16ms/step - loss: 50.5085 - mae: 50.5085
Epoch 11/100
2/2 [==============================] - 0s 14ms/step - loss: 14.9921 - mae: 14.9921
Epoch 12/100
2/2 [==============================] - 0s 15ms/step - loss: 16.7825 - mae: 16.7825
Epoch 13/100
2/2 [==============================] - 0s 15ms/step - loss: 13.1797 - mae: 13.1797
Epoch 14/100
2/2 [==============================] - 0s 25ms/step - loss: 20.3170 - mae: 20.3170
Epoch 15/100
2/2 [==============================] - 0s 20ms/step - loss: 13.0323 - mae: 13.0323
Epoch 16/100
2/2 [==============================] - 0s 12ms/step - loss: 11.2802 - mae: 11.2802
Epoch 17/100
2/2 [==============================] - 0s 12ms/step - loss: 12.0403 - mae: 12.0403
Epoch 18/100
2/2 [==============================] - 0s 13ms/step - loss: 13.6978 - mae: 13.6978
Epoch 19/100
2/2 [==============================] - 0s 12ms/step - loss: 15.7764 - mae: 15.7764
Epoch 20/100
2/2 [==============================] - 0s 12ms/step - loss: 6.1935 - mae: 6.1935
Epoch 21/100
2/2 [==============================] - 0s 12ms/step - loss: 6.8500 - mae: 6.8500
Epoch 22/100
2/2 [==============================] - 0s 12ms/step - loss: 8.2456 - mae: 8.2456
Epoch 23/100
2/2 [==============================] - 0s 12ms/step - loss: 4.4098 - mae: 4.4098
Epoch 24/100
2/2 [==============================] - 0s 12ms/step - loss: 5.4226 - mae: 5.4226
Epoch 25/100
2/2 [==============================] - 0s 12ms/step - loss: 6.5746 - mae: 6.5746
Epoch 26/100
2/2 [==============================] - 0s 12ms/step - loss: 9.1301 - mae: 9.1301
Epoch 27/100
2/2 [==============================] - 0s 12ms/step - loss: 9.2812 - mae: 9.2812
Epoch 28/100
2/2 [==============================] - 0s 12ms/step - loss: 13.3580 - mae: 13.3580
Epoch 29/100
2/2 [==============================] - 0s 12ms/step - loss: 10.8502 - mae: 10.8502
Epoch 30/100
2/2 [==============================] - 0s 12ms/step - loss: 20.6037 - mae: 20.6037
Epoch 31/100
2/2 [==============================] - 0s 12ms/step - loss: 17.1603 - mae: 17.1603
Epoch 32/100
2/2 [==============================] - 0s 12ms/step - loss: 13.1076 - mae: 13.1076
Epoch 33/100
2/2 [==============================] - 0s 12ms/step - loss: 12.8645 - mae: 12.8645
Epoch 34/100
2/2 [==============================] - 0s 12ms/step - loss: 13.7155 - mae: 13.7155
Epoch 35/100
2/2 [==============================] - 0s 14ms/step - loss: 10.1649 - mae: 10.1649
Epoch 36/100
2/2 [==============================] - 0s 11ms/step - loss: 12.2415 - mae: 12.2415
Epoch 37/100
2/2 [==============================] - 0s 14ms/step - loss: 7.7422 - mae: 7.7422
Epoch 38/100
2/2 [==============================] - 0s 12ms/step - loss: 7.4192 - mae: 7.4192
Epoch 39/100
2/2 [==============================] - 0s 12ms/step - loss: 7.2619 - mae: 7.2619
Epoch 40/100
2/2 [==============================] - 0s 12ms/step - loss: 7.2299 - mae: 7.2299
Epoch 41/100
2/2 [==============================] - 0s 13ms/step - loss: 6.2314 - mae: 6.2314
Epoch 42/100
2/2 [==============================] - 0s 12ms/step - loss: 4.9985 - mae: 4.9985
Epoch 43/100
2/2 [==============================] - 0s 12ms/step - loss: 6.0061 - mae: 6.0061
Epoch 44/100
2/2 [==============================] - 0s 12ms/step - loss: 10.1504 - mae: 10.1504
Epoch 45/100
2/2 [==============================] - 0s 12ms/step - loss: 9.9889 - mae: 9.9889
Epoch 46/100
2/2 [==============================] - 0s 12ms/step - loss: 10.2216 - mae: 10.2216
Epoch 47/100
2/2 [==============================] - 0s 12ms/step - loss: 3.8698 - mae: 3.8698
Epoch 48/100
2/2 [==============================] - 0s 12ms/step - loss: 4.5304 - mae: 4.5304
Epoch 49/100
2/2 [==============================] - 0s 12ms/step - loss: 5.0956 - mae: 5.0956
Epoch 50/100
2/2 [==============================] - 0s 13ms/step - loss: 3.3482 - mae: 3.3482
Epoch 51/100
2/2 [==============================] - 0s 12ms/step - loss: 6.3185 - mae: 6.3185
Epoch 52/100
2/2 [==============================] - 0s 12ms/step - loss: 11.0143 - mae: 11.0143
Epoch 53/100
2/2 [==============================] - 0s 13ms/step - loss: 11.3351 - mae: 11.3351
Epoch 54/100
2/2 [==============================] - 0s 13ms/step - loss: 20.4708 - mae: 20.4708
Epoch 55/100
2/2 [==============================] - 0s 12ms/step - loss: 14.0911 - mae: 14.0911
Epoch 56/100
2/2 [==============================] - 0s 12ms/step - loss: 12.6470 - mae: 12.6470
Epoch 57/100
2/2 [==============================] - 0s 12ms/step - loss: 13.2412 - mae: 13.2412
Epoch 58/100
2/2 [==============================] - 0s 12ms/step - loss: 10.0523 - mae: 10.0523
Epoch 59/100
2/2 [==============================] - 0s 12ms/step - loss: 8.3151 - mae: 8.3151
Epoch 60/100
2/2 [==============================] - 0s 12ms/step - loss: 6.4987 - mae: 6.4987
Epoch 61/100
2/2 [==============================] - 0s 12ms/step - loss: 6.2225 - mae: 6.2225
Epoch 62/100
2/2 [==============================] - 0s 12ms/step - loss: 6.4411 - mae: 6.4411
Epoch 63/100
2/2 [==============================] - 0s 12ms/step - loss: 5.3723 - mae: 5.3723
Epoch 64/100
2/2 [==============================] - 0s 13ms/step - loss: 5.3104 - mae: 5.3104
Epoch 65/100
2/2 [==============================] - 0s 12ms/step - loss: 5.9633 - mae: 5.9633
Epoch 66/100
2/2 [==============================] - 0s 12ms/step - loss: 6.8727 - mae: 6.8727
Epoch 67/100
2/2 [==============================] - 0s 12ms/step - loss: 7.4745 - mae: 7.4745
Epoch 68/100
2/2 [==============================] - 0s 12ms/step - loss: 6.8352 - mae: 6.8352
Epoch 69/100
2/2 [==============================] - 0s 12ms/step - loss: 6.4509 - mae: 6.4509
Epoch 70/100
2/2 [==============================] - 0s 12ms/step - loss: 3.9991 - mae: 3.9991
Epoch 71/100
2/2 [==============================] - 0s 12ms/step - loss: 4.2888 - mae: 4.2888
Epoch 72/100
2/2 [==============================] - 0s 12ms/step - loss: 4.3132 - mae: 4.3132
Epoch 73/100
2/2 [==============================] - 0s 12ms/step - loss: 4.6834 - mae: 4.6834
Epoch 74/100
2/2 [==============================] - 0s 12ms/step - loss: 9.1816 - mae: 9.1816
Epoch 75/100
2/2 [==============================] - 0s 12ms/step - loss: 7.4994 - mae: 7.4994
Epoch 76/100
2/2 [==============================] - 0s 12ms/step - loss: 8.5743 - mae: 8.5743
Epoch 77/100
2/2 [==============================] - 0s 12ms/step - loss: 9.5558 - mae: 9.5558
Epoch 78/100
2/2 [==============================] - 0s 12ms/step - loss: 9.4755 - mae: 9.4755
Epoch 79/100
2/2 [==============================] - 0s 13ms/step - loss: 11.9530 - mae: 11.9530
Epoch 80/100
2/2 [==============================] - 0s 12ms/step - loss: 21.8714 - mae: 21.8714
Epoch 81/100
2/2 [==============================] - 0s 12ms/step - loss: 11.6170 - mae: 11.6170
Epoch 82/100
2/2 [==============================] - 0s 12ms/step - loss: 4.6694 - mae: 4.6694
Epoch 83/100
2/2 [==============================] - 0s 13ms/step - loss: 3.7263 - mae: 3.7263
Epoch 84/100
2/2 [==============================] - 0s 12ms/step - loss: 7.8121 - mae: 7.8121
Epoch 85/100
2/2 [==============================] - 0s 12ms/step - loss: 11.7576 - mae: 11.7576
Epoch 86/100
2/2 [==============================] - 0s 12ms/step - loss: 13.4348 - mae: 13.4348
Epoch 87/100
2/2 [==============================] - 0s 12ms/step - loss: 14.0089 - mae: 14.0089
Epoch 88/100
2/2 [==============================] - 0s 12ms/step - loss: 18.4718 - mae: 18.4718
Epoch 89/100
2/2 [==============================] - 0s 12ms/step - loss: 11.5349 - mae: 11.5349
Epoch 90/100
2/2 [==============================] - 0s 12ms/step - loss: 14.1623 - mae: 14.1623
Epoch 91/100
2/2 [==============================] - 0s 12ms/step - loss: 12.8820 - mae: 12.8820
Epoch 92/100
2/2 [==============================] - 0s 12ms/step - loss: 18.1476 - mae: 18.1476
Epoch 93/100
2/2 [==============================] - 0s 12ms/step - loss: 12.2636 - mae: 12.2636
Epoch 94/100
2/2 [==============================] - 0s 12ms/step - loss: 11.3409 - mae: 11.3409
Epoch 95/100
2/2 [==============================] - 0s 12ms/step - loss: 13.7530 - mae: 13.7530
Epoch 96/100
2/2 [==============================] - 0s 12ms/step - loss: 11.8180 - mae: 11.8180
Epoch 97/100
2/2 [==============================] - 0s 12ms/step - loss: 15.1417 - mae: 15.1417
Epoch 98/100
2/2 [==============================] - 0s 12ms/step - loss: 12.8859 - mae: 12.8859
Epoch 99/100
2/2 [==============================] - 0s 12ms/step - loss: 11.7187 - mae: 11.7187
Epoch 100/100
2/2 [==============================] - 0s 12ms/step - loss: 16.0436 - mae: 16.0436
Out [10]:
<keras.src.callbacks.History at 0x7f08598d90>
In [11]:
## Build some prediction data
predictions = m.predict(x_test)
predictions
1/1 [==============================] - 0s 196ms/step
Out [11]:
array([[574.31793],
       [612.6054 ],
       [650.8929 ],
       [689.1804 ],
       [727.46796],
       [765.75543],
       [804.0429 ],
       [842.33044],
       [880.618  ],
       [918.90546]], dtype=float32)

Evaluating A Model's Predictions

Plot It

Plot 3 datasets: train data, test data, and prediction data.

In [12]:
def plot_predictions(train_data=x_train, 
                     train_labels=y_train, 
                     test_data=x_test, 
                     test_labels=y_test, 
                     predictions=predictions):
  """
  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();

plot_predictions()
output png

Regression Evaluation Metrics

Different evaluation metrics exist. Regressions commonly use MAE and

  • MAE (mean avg error): on average how "wrong" each prediction is. a great "starter metric" for any regression
  • MSE (mean squared error): square the errors, then find the avg. Useful when larger errors are more significant than smaller errors
In [13]:
m.evaluate(x_test, y_test)
1/1 [==============================] - 0s 381ms/step - loss: 33.3883 - mae: 33.3883
Out [13]:
[33.3883171081543, 33.3883171081543]
In [21]:
# get err of EACH test input
# NOTE: the tensors have to be the same "shape", and the predictions are NOT the same shape
#   as the test data
squeezedPredictions = tf.squeeze(predictions)
# y_test.shape, predictions.shape, squeezedPredictions.shape

myMas = tf.metrics.mean_absolute_error(y_true=y_test,
                             y_pred=squeezedPredictions)
myMas
Out [21]:
<tf.Tensor: shape=(), dtype=float32, numpy=33.388317>
In [23]:
myMse = tf.metrics.mean_squared_error(y_true=y_test,
                             y_pred=squeezedPredictions)
myMse
Out [23]:
<tf.Tensor: shape=(), dtype=float32, numpy=1138.974>