Get Data¶

In [ ]:
# Download Bitcoin historical data from GitHub
!wget https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/main/extras/BTC_USD_2013-10-01_2021-05-18-CoinDesk.csv
--2023-03-14 15:53:02--  https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/main/extras/BTC_USD_2013-10-01_2021-05-18-CoinDesk.csv
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 178509 (174K) [text/plain]
Saving to: ‘BTC_USD_2013-10-01_2021-05-18-CoinDesk.csv’

BTC_USD_2013-10-01_ 100%[===================>] 174.33K  --.-KB/s    in 0.01s   

2023-03-14 15:53:03 (11.6 MB/s) - ‘BTC_USD_2013-10-01_2021-05-18-CoinDesk.csv’ saved [178509/178509]

In [ ]:
import pandas as pd

df = pd.read_csv("/content/BTC_USD_2013-10-01_2021-05-18-CoinDesk.csv",
                 parse_dates=["Date"],
                 index_col=["Date"]) 
df.head()
Out[ ]:
Currency Closing Price (USD) 24h Open (USD) 24h High (USD) 24h Low (USD)
Date
2013-10-01 BTC 123.65499 124.30466 124.75166 122.56349
2013-10-02 BTC 125.45500 123.65499 125.75850 123.63383
2013-10-03 BTC 108.58483 125.45500 125.66566 83.32833
2013-10-04 BTC 118.67466 108.58483 118.67500 107.05816
2013-10-05 BTC 121.33866 118.67466 121.93633 118.00566
In [ ]:
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2787 entries, 2013-10-01 to 2021-05-18
Data columns (total 5 columns):
 #   Column               Non-Null Count  Dtype  
---  ------               --------------  -----  
 0   Currency             2787 non-null   object 
 1   Closing Price (USD)  2787 non-null   float64
 2   24h Open (USD)       2787 non-null   float64
 3   24h High (USD)       2787 non-null   float64
 4   24h Low (USD)        2787 non-null   float64
dtypes: float64(4), object(1)
memory usage: 130.6+ KB
In [ ]:
len(df)
Out[ ]:
2787
In [ ]:
bitcoin_prices = pd.DataFrame(df["Closing Price (USD)"]).rename(columns={"Closing Price (USD)": "Price"})
bitcoin_prices.head()
Out[ ]:
Price
Date
2013-10-01 123.65499
2013-10-02 125.45500
2013-10-03 108.58483
2013-10-04 118.67466
2013-10-05 121.33866
In [ ]:
import matplotlib.pyplot as plt
bitcoin_prices.plot(figsize=(10, 7))
plt.ylabel("BTC Price")
plt.title("Price of Bitcoin from 1 Oct 2013 to 18 May 2021", fontsize=16)
plt.legend(fontsize=14);
No description has been provided for this image
In [ ]:
import csv
from datetime import datetime

timesteps = []
btc_price = []
with open("/content/BTC_USD_2013-10-01_2021-05-18-CoinDesk.csv", "r") as f:
  csv_reader = csv.reader(f, delimiter=",") 
  next(csv_reader) 
  for line in csv_reader:
    timesteps.append(datetime.strptime(line[1], "%Y-%m-%d")) 
    btc_price.append(float(line[2])) 

timesteps[:10], btc_price[:10]
Out[ ]:
([datetime.datetime(2013, 10, 1, 0, 0),
  datetime.datetime(2013, 10, 2, 0, 0),
  datetime.datetime(2013, 10, 3, 0, 0),
  datetime.datetime(2013, 10, 4, 0, 0),
  datetime.datetime(2013, 10, 5, 0, 0),
  datetime.datetime(2013, 10, 6, 0, 0),
  datetime.datetime(2013, 10, 7, 0, 0),
  datetime.datetime(2013, 10, 8, 0, 0),
  datetime.datetime(2013, 10, 9, 0, 0),
  datetime.datetime(2013, 10, 10, 0, 0)],
 [123.65499,
  125.455,
  108.58483,
  118.67466,
  121.33866,
  120.65533,
  121.795,
  123.033,
  124.049,
  125.96116])
In [ ]:
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(10, 7))
plt.plot(timesteps, btc_price)
plt.title("Price of Bitcoin from 1 Oct 2013 to 18 May 2021", fontsize=16)
plt.xlabel("Date")
plt.ylabel("BTC Price");
No description has been provided for this image

Train Test Split¶

In [ ]:
timesteps = bitcoin_prices.index.to_numpy()
prices = bitcoin_prices["Price"].to_numpy()

timesteps[:10], prices[:10]
Out[ ]:
(array(['2013-10-01T00:00:00.000000000', '2013-10-02T00:00:00.000000000',
        '2013-10-03T00:00:00.000000000', '2013-10-04T00:00:00.000000000',
        '2013-10-05T00:00:00.000000000', '2013-10-06T00:00:00.000000000',
        '2013-10-07T00:00:00.000000000', '2013-10-08T00:00:00.000000000',
        '2013-10-09T00:00:00.000000000', '2013-10-10T00:00:00.000000000'],
       dtype='datetime64[ns]'),
 array([123.65499, 125.455  , 108.58483, 118.67466, 121.33866, 120.65533,
        121.795  , 123.033  , 124.049  , 125.96116]))
In [ ]:
split_size = int(0.8 * len(prices)) 
X_train, y_train = timesteps[:split_size], prices[:split_size]

X_test, y_test = timesteps[split_size:], prices[split_size:]

len(X_train), len(X_test), len(y_train), len(y_test)
Out[ ]:
(2229, 558, 2229, 558)
In [ ]:
# Plot correctly made splits
plt.figure(figsize=(10, 7))
plt.scatter(X_train, y_train, s=5, label="Train data")
plt.scatter(X_test, y_test, s=5, label="Test data")
plt.xlabel("Date")
plt.ylabel("BTC Price")
plt.legend(fontsize=14)
plt.show();
No description has been provided for this image
In [ ]:
def plot_time_series(timesteps, values, format='.', start=0, end=None, label=None):
  """
  Plots a timesteps (a series of points in time) against values (a series of values across timesteps).

  Parameters
  ---------
  timesteps : array of timesteps
  values : array of values across time
  format : style of plot, default "."
  start : where to start the plot (setting a value will index from start of timesteps & values)
  end : where to end the plot (setting a value will index from end of timesteps & values)
  label : label to show on plot of values
  """
  plt.plot(timesteps[start:end], values[start:end], format, label=label)
  plt.xlabel("Time")
  plt.ylabel("BTC Price")
  if label:
    plt.legend(fontsize=14) 
  plt.grid(True)
In [ ]:
plt.figure(figsize=(10, 7))
plot_time_series(timesteps=X_train, values=y_train, label="Train data")
plot_time_series(timesteps=X_test, values=y_test, label="Test data")
No description has been provided for this image

Model 0: Naive forcast¶

$$\hat{y}_t = y_{t-1}$$

In [ ]:
naive_forecast = y_test[:-1]
naive_forecast[:10], naive_forecast[-10:] 
Out[ ]:
(array([9226.48582088, 8794.35864452, 8798.04205463, 9081.18687849,
        8711.53433917, 8760.89271814, 8749.52059102, 8656.97092235,
        8500.64355816, 8469.2608989 ]),
 array([57107.12067189, 58788.20967893, 58102.19142623, 55715.54665129,
        56573.5554719 , 52147.82118698, 49764.1320816 , 50032.69313676,
        47885.62525472, 45604.61575361]))
In [ ]:
plt.figure(figsize=(10, 7))
plot_time_series(timesteps=X_train, values=y_train, label="Train data")
plot_time_series(timesteps=X_test, values=y_test, label="Test data")
plot_time_series(timesteps=X_test[1:], values=naive_forecast, format="-", label="Naive forecast");
No description has been provided for this image
In [ ]:
plt.figure(figsize=(10, 7))
offset = 300 
plot_time_series(timesteps=X_test, values=y_test, start=offset, label="Test data")
plot_time_series(timesteps=X_test[1:], values=naive_forecast, format="-", start=offset, label="Naive forecast");
No description has been provided for this image
In [ ]:
import tensorflow as tf
In [ ]:
def mean_absolute_scaled_error(y_true, y_pred):
  """
  Implement MASE (assuming no seasonality of data).
  """
  mae = tf.reduce_mean(tf.abs(y_true - y_pred))

  mae_naive_no_season = tf.reduce_mean(tf.abs(y_true[1:] - y_true[:-1]))

  return mae / mae_naive_no_season
In [ ]:
def evaluate_preds(y_true, y_pred):
  y_true = tf.cast(y_true, dtype=tf.float32)
  y_pred = tf.cast(y_pred, dtype=tf.float32)

  mae = tf.keras.metrics.mean_absolute_error(y_true, y_pred)
  mse = tf.keras.metrics.mean_squared_error(y_true, y_pred) 
  rmse = tf.sqrt(mse)
  mape = tf.keras.metrics.mean_absolute_percentage_error(y_true, y_pred)
  mase = mean_absolute_scaled_error(y_true, y_pred)

  return {"mae": mae.numpy(),
          "mse": mse.numpy(),
          "rmse": rmse.numpy(),
          "mape": mape.numpy(),
          "mase": mase.numpy()}
In [ ]:
naive_results = evaluate_preds(y_true=y_test[1:],
                               y_pred=naive_forecast)
naive_results
Out[ ]:
{'mae': 567.9802,
 'mse': 1147547.0,
 'rmse': 1071.2362,
 'mape': 2.5165248,
 'mase': 0.99957}
In [ ]:
tf.reduce_mean(y_test).numpy()
Out[ ]:
20056.632963737226
In [ ]:
HORIZON = 1 
WINDOW_SIZE = 7
In [ ]:
def get_labelled_windows(x, horizon=1):
  """
  Creates labels for windowed dataset.

  E.g. if horizon=1 (default)
  Input: [1, 2, 3, 4, 5, 6] -> Output: ([1, 2, 3, 4, 5], [6])
  """
  return x[:, :-horizon], x[:, -horizon:]
In [ ]:
test_window, test_label = get_labelled_windows(tf.expand_dims(tf.range(8)+1, axis=0), horizon=HORIZON)
print(f"Window: {tf.squeeze(test_window).numpy()} -> Label: {tf.squeeze(test_label).numpy()}")
Window: [1 2 3 4 5 6 7] -> Label: 8
In [ ]:
def make_windows(x, window_size=7, horizon=1):
  """
  Turns a 1D array into a 2D array of sequential windows of window_size.
  """
  window_step = np.expand_dims(np.arange(window_size+horizon), axis=0)

  window_indexes = window_step + np.expand_dims(np.arange(len(x)-(window_size+horizon-1)), axis=0).T # create 2D array of windows of size window_size

  windowed_array = x[window_indexes]

  windows, labels = get_labelled_windows(windowed_array, horizon=horizon)

  return windows, labels
In [ ]:
full_windows, full_labels = make_windows(prices, window_size=WINDOW_SIZE, horizon=HORIZON)
len(full_windows), len(full_labels)
Out[ ]:
(2780, 2780)
In [ ]:
for i in range(3):
  print(f"Window: {full_windows[i]} -> Label: {full_labels[i]}")
Window: [123.65499 125.455   108.58483 118.67466 121.33866 120.65533 121.795  ] -> Label: [123.033]
Window: [125.455   108.58483 118.67466 121.33866 120.65533 121.795   123.033  ] -> Label: [124.049]
Window: [108.58483 118.67466 121.33866 120.65533 121.795   123.033   124.049  ] -> Label: [125.96116]
In [ ]:
for i in range(3):
  print(f"Window: {full_windows[i-3]} -> Label: {full_labels[i-3]}")
Window: [58788.20967893 58102.19142623 55715.54665129 56573.5554719
 52147.82118698 49764.1320816  50032.69313676] -> Label: [47885.62525472]
Window: [58102.19142623 55715.54665129 56573.5554719  52147.82118698
 49764.1320816  50032.69313676 47885.62525472] -> Label: [45604.61575361]
Window: [55715.54665129 56573.5554719  52147.82118698 49764.1320816
 50032.69313676 47885.62525472 45604.61575361] -> Label: [43144.47129086]
In [ ]:
def make_train_test_splits(windows, labels, test_split=0.2):
  """
  Splits matching pairs of windows and labels into train and test splits.
  """
  split_size = int(len(windows) * (1-test_split)) 
  train_windows = windows[:split_size]
  train_labels = labels[:split_size]
  test_windows = windows[split_size:]
  test_labels = labels[split_size:]
  return train_windows, test_windows, train_labels, test_labels
In [ ]:
train_windows, test_windows, train_labels, test_labels = make_train_test_splits(full_windows, full_labels)
len(train_windows), len(test_windows), len(train_labels), len(test_labels)
Out[ ]:
(2224, 556, 2224, 556)
In [ ]:
np.array_equal(np.squeeze(train_labels[:-HORIZON-1]), y_train[WINDOW_SIZE:])
Out[ ]:
True

Model Checkpoint¶

In [ ]:
import os

def create_model_checkpoint(model_name, save_path="model_experiments"):
  return tf.keras.callbacks.ModelCheckpoint(filepath=os.path.join(save_path, model_name), 
                                            verbose=0, 
                                            save_best_only=True) 

Model 1: Dense model (window = 7, horizon = 1)¶

In [ ]:
import tensorflow as tf
from tensorflow.keras import layers

tf.random.set_seed(42)

model_1 = tf.keras.Sequential([
  layers.Dense(128, activation="relu"),
  layers.Dense(HORIZON, activation="linear") 
], name="model_1_dense") 

model_1.compile(loss="mae",
                optimizer=tf.keras.optimizers.Adam(),
                metrics=["mae"]) 

model_1.fit(x=train_windows, 
            y=train_labels,
            epochs=100,
            verbose=1,
            batch_size=128,
            validation_data=(test_windows, test_labels),
            callbacks=[create_model_checkpoint(model_name=model_1.name)]) 
In [ ]:
model_1.evaluate(test_windows, test_labels)
18/18 [==============================] - 0s 2ms/step - loss: 723.0089 - mae: 723.0089
Out[ ]:
[723.0088500976562, 723.0088500976562]
In [ ]:
model_1 = tf.keras.models.load_model("model_experiments/model_1_dense")
model_1.evaluate(test_windows, test_labels)
18/18 [==============================] - 0s 2ms/step - loss: 572.4927 - mae: 572.4927
Out[ ]:
[572.4927368164062, 572.4927368164062]
In [ ]:
def make_preds(model, input_data):
  """
  Uses model to make predictions on input_data.

  Parameters
  ----------
  model: trained model
  input_data: windowed input data (same kind of data model was trained on)

  Returns model predictions on input_data.
  """
  forecast = model.predict(input_data)
  return tf.squeeze(forecast)
In [ ]:
model_1_preds = make_preds(model_1, test_windows)
len(model_1_preds), model_1_preds[:10]
18/18 [==============================] - 0s 1ms/step
Out[ ]:
(556, <tf.Tensor: shape=(10,), dtype=float32, numpy=
 array([8882.29  , 8771.357 , 8997.532 , 8846.857 , 8749.909 , 8691.108 ,
        8708.644 , 8549.288 , 8442.5625, 8523.987 ], dtype=float32)>)
In [ ]:
model_1_results = evaluate_preds(y_true=tf.squeeze(test_labels),
                                 y_pred=model_1_preds)
model_1_results
Out[ ]:
{'mae': 572.49274,
 'mse': 1181174.9,
 'rmse': 1086.8187,
 'mape': 2.5654848,
 'mase': 1.0057112}
In [ ]:
naive_results
Out[ ]:
{'mae': 567.9802,
 'mse': 1147547.0,
 'rmse': 1071.2362,
 'mape': 2.5165248,
 'mase': 0.99957}
In [ ]:
offset = 300
plt.figure(figsize=(10, 7))
plot_time_series(timesteps=X_test[-len(test_windows):], values=test_labels[:, 0], start=offset, label="Test_data")
plot_time_series(timesteps=X_test[-len(test_windows):], values=model_1_preds, start=offset, format="-", label="model_1_preds")
No description has been provided for this image

Model 2: Dense (window = 30, horizon=1)¶

In [ ]:
HORIZON = 1 # predict one step at a time
WINDOW_SIZE = 30 # use 30 timesteps in the past
In [ ]:
full_windows, full_labels = make_windows(prices, window_size=WINDOW_SIZE, horizon=HORIZON)
len(full_windows), len(full_labels)
Out[ ]:
(2757, 2757)
In [ ]:
train_windows, test_windows, train_labels, test_labels = make_train_test_splits(windows=full_windows, labels=full_labels)
len(train_windows), len(test_windows), len(train_labels), len(test_labels)
Out[ ]:
(2205, 552, 2205, 552)
In [ ]:
tf.random.set_seed(42)

model_2 = tf.keras.Sequential([
  layers.Dense(128, activation="relu"),
  layers.Dense(HORIZON) 
], name="model_2_dense")

model_2.compile(loss="mae",
                optimizer=tf.keras.optimizers.Adam())

model_2.fit(train_windows,
            train_labels,
            epochs=100,
            batch_size=128,
            verbose=0,
            validation_data=(test_windows, test_labels),
            callbacks=[create_model_checkpoint(model_name=model_2.name)])
In [ ]:
model_2.evaluate(test_windows, test_labels)
18/18 [==============================] - 0s 2ms/step - loss: 618.8589
Out[ ]:
618.8589477539062
In [ ]:
model_2 = tf.keras.models.load_model("model_experiments/model_2_dense/")
model_2.evaluate(test_windows, test_labels)
18/18 [==============================] - 0s 2ms/step - loss: 618.8589
Out[ ]:
618.8589477539062
In [ ]:
model_2_preds = make_preds(model_2,
                           input_data=test_windows)
18/18 [==============================] - 0s 2ms/step
In [ ]:
model_2_results = evaluate_preds(y_true=tf.squeeze(test_labels),
                                 y_pred=model_2_preds)
model_2_results
Out[ ]:
{'mae': 618.85895,
 'mse': 1311890.0,
 'rmse': 1145.3777,
 'mape': 2.7747989,
 'mase': 1.0817714}
In [ ]:
offset = 300
plt.figure(figsize=(10, 7))
plot_time_series(timesteps=X_test[-len(test_windows):], values=test_labels[:, 0], start=offset, label="test_data")
plot_time_series(timesteps=X_test[-len(test_windows):], values=model_2_preds, start=offset, format="-", label="model_2_preds")
No description has been provided for this image

Model 3: Dense (window =30, horizon = 7)¶

In [ ]:
HORIZON = 7
WINDOW_SIZE = 30

full_windows, full_labels = make_windows(prices, window_size=WINDOW_SIZE, horizon=HORIZON)
len(full_windows), len(full_labels)
Out[ ]:
(2751, 2751)
In [ ]:
train_windows, test_windows, train_labels, test_labels = make_train_test_splits(windows=full_windows, labels=full_labels, test_split=0.2)
len(train_windows), len(test_windows), len(train_labels), len(test_labels)
Out[ ]:
(2200, 551, 2200, 551)
In [ ]:
tf.random.set_seed(42)

model_3 = tf.keras.Sequential([
  layers.Dense(128, activation="relu"),
  layers.Dense(HORIZON)
], name="model_3_dense")

model_3.compile(loss="mae",
                optimizer=tf.keras.optimizers.Adam())

model_3.fit(train_windows,
            train_labels,
            batch_size=128,
            epochs=100,
            verbose=0,
            validation_data=(test_windows, test_labels),
            callbacks=[create_model_checkpoint(model_name=model_3.name)])
In [ ]:
model_3.evaluate(test_windows, test_labels)
18/18 [==============================] - 0s 2ms/step - loss: 1309.9860
Out[ ]:
1309.9859619140625
In [ ]:
model_3 = tf.keras.models.load_model("model_experiments/model_3_dense/")
model_3.evaluate(test_windows, test_labels)
18/18 [==============================] - 0s 2ms/step - loss: 1235.4514
Out[ ]:
1235.451416015625
In [ ]:
model_3_preds = make_preds(model_3,
                           input_data=test_windows)
model_3_preds[:5]
18/18 [==============================] - 0s 2ms/step
Out[ ]:
<tf.Tensor: shape=(5, 7), dtype=float32, numpy=
array([[9391.67  , 9435.451 , 9392.129 , 9185.196 , 9731.022 , 9793.0205,
        9493.9375],
       [8997.21  , 9044.488 , 9100.856 , 8830.969 , 9436.48  , 9474.913 ,
        9390.65  ],
       [8888.112 , 8963.833 , 8782.561 , 8861.71  , 9254.064 , 9201.261 ,
        9280.101 ],
       [8913.8545, 9093.12  , 8864.063 , 9226.914 , 9416.29  , 9122.967 ,
        9196.648 ],
       [8837.005 , 8996.516 , 8742.849 , 9115.141 , 9283.897 , 8920.553 ,
        8975.973 ]], dtype=float32)>
In [ ]:
def evaluate_preds(y_true, y_pred):
  y_true = tf.cast(y_true, dtype=tf.float32)
  y_pred = tf.cast(y_pred, dtype=tf.float32)

  mae = tf.keras.metrics.mean_absolute_error(y_true, y_pred)
  mse = tf.keras.metrics.mean_squared_error(y_true, y_pred)
  rmse = tf.sqrt(mse)
  mape = tf.keras.metrics.mean_absolute_percentage_error(y_true, y_pred)
  mase = mean_absolute_scaled_error(y_true, y_pred)

  if mae.ndim > 0: 
    mae = tf.reduce_mean(mae)
    mse = tf.reduce_mean(mse)
    rmse = tf.reduce_mean(rmse)
    mape = tf.reduce_mean(mape)
    mase = tf.reduce_mean(mase)

  return {"mae": mae.numpy(),
          "mse": mse.numpy(),
          "rmse": rmse.numpy(),
          "mape": mape.numpy(),
          "mase": mase.numpy()}
In [ ]:
model_3_results = evaluate_preds(y_true=tf.squeeze(test_labels),
                                 y_pred=model_3_preds)
model_3_results
Out[ ]:
{'mae': 1235.4514,
 'mse': 5316866.0,
 'rmse': 1427.3538,
 'mape': 5.640647,
 'mase': 2.1984165}
In [ ]:
offset = 300
plt.figure(figsize=(10, 7))
plot_time_series(timesteps=X_test[-len(test_windows):], values=test_labels[:, 0], start=offset, label="Test_data")
plot_time_series(timesteps=X_test[-len(test_windows):], values=model_3_preds, start=offset, label="model_3_preds")
No description has been provided for this image
In [ ]:
offset = 300
plt.figure(figsize=(10, 7))
plot_time_series(timesteps=X_test[-len(test_windows):],
                 values=test_labels[:, 0],
                 start=offset,
                 label="Test_data")
plot_time_series(timesteps=X_test[-len(test_windows):],
                 values=tf.reduce_mean(model_3_preds, axis=1),
                 format="-",
                 start=offset,
                 label="model_3_preds")
No description has been provided for this image
In [ ]:
pd.DataFrame({"naive": naive_results["mae"],
              "horizon_1_window_7": model_1_results["mae"],
              "horizon_1_window_30": model_2_results["mae"],
              "horizon_7_window_30": model_3_results["mae"]}, index=["mae"]).plot(figsize=(10, 7), kind="bar");
No description has been provided for this image

Model 4: Conv1D¶

In [ ]:
HORIZON = 1
WINDOW_SIZE = 7 
In [ ]:
full_windows, full_labels = make_windows(prices, window_size=WINDOW_SIZE, horizon=HORIZON)
len(full_windows), len(full_labels)
Out[ ]:
(2780, 2780)
In [ ]:
train_windows, test_windows, train_labels, test_labels = make_train_test_splits(full_windows, full_labels)
len(train_windows), len(test_windows), len(train_labels), len(test_labels)
Out[ ]:
(2224, 556, 2224, 556)
In [ ]:
train_windows[0].shape 
Out[ ]:
(7,)
In [ ]:
x = tf.constant(train_windows[0])
expand_dims_layer = layers.Lambda(lambda x: tf.expand_dims(x, axis=1))
print(f"Original shape: {x.shape}") 
print(f"Expanded shape: {expand_dims_layer(x).shape}") 
print(f"Original values with expanded shape:\n {expand_dims_layer(x)}")
Original shape: (7,)
Expanded shape: (7, 1)
Original values with expanded shape:
 [[123.65499]
 [125.455  ]
 [108.58483]
 [118.67466]
 [121.33866]
 [120.65533]
 [121.795  ]]
In [ ]:
tf.random.set_seed(42)

# Create model
model_4 = tf.keras.Sequential([
  layers.Lambda(lambda x: tf.expand_dims(x, axis=1)),
  layers.Conv1D(filters=128, kernel_size=5, padding="causal", activation="relu"),
  layers.Dense(HORIZON)
], name="model_4_conv1D")

# Compile model
model_4.compile(loss="mae",
                optimizer=tf.keras.optimizers.Adam())

# Fit model
model_4.fit(train_windows,
            train_labels,
            batch_size=128,
            epochs=100,
            verbose=0,
            validation_data=(test_windows, test_labels),
            callbacks=[create_model_checkpoint(model_name=model_4.name)])
In [ ]:
model_4.summary()
Model: "model_4_conv1D"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 lambda_1 (Lambda)           (None, 1, 7)              0         
                                                                 
 conv1d (Conv1D)             (None, 1, 128)            4608      
                                                                 
 dense_6 (Dense)             (None, 1, 1)              129       
                                                                 
=================================================================
Total params: 4,737
Trainable params: 4,737
Non-trainable params: 0
_________________________________________________________________
In [ ]:
model_4 = tf.keras.models.load_model("model_experiments/model_4_conv1D")
model_4.evaluate(test_windows, test_labels)
18/18 [==============================] - 0s 2ms/step - loss: 567.2568
Out[ ]:
567.2568359375
In [ ]:
model_4_preds = make_preds(model_4, test_windows)
model_4_preds[:10]
18/18 [==============================] - 0s 2ms/step
Out[ ]:
<tf.Tensor: shape=(10,), dtype=float32, numpy=
array([8904.228, 8807.786, 9025.899, 8813.664, 8776.681, 8757.376,
       8699.406, 8558.045, 8485.218, 8539.196], dtype=float32)>
In [ ]:
model_4_results = evaluate_preds(y_true=tf.squeeze(test_labels),
                                 y_pred=model_4_preds)
model_4_results
Out[ ]:
{'mae': 567.25684,
 'mse': 1174792.1,
 'rmse': 1083.8783,
 'mape': 2.54246,
 'mase': 0.9965131}

Model 5: LSTM¶

In [ ]:
tf.random.set_seed(42)

inputs = layers.Input(shape=(WINDOW_SIZE))
x = layers.Lambda(lambda x: tf.expand_dims(x, axis=1))(inputs)

x = layers.LSTM(128, activation="relu")(x) 

output = layers.Dense(HORIZON)(x)
model_5 = tf.keras.Model(inputs=inputs, outputs=output, name="model_5_lstm")

model_5.compile(loss="mae",
                optimizer=tf.keras.optimizers.Adam())

model_5.fit(train_windows,
            train_labels,
            epochs=100,
            verbose=0,
            batch_size=128,
            validation_data=(test_windows, test_labels),
            callbacks=[create_model_checkpoint(model_name=model_5.name)])
In [ ]:
model_5 = tf.keras.models.load_model("model_experiments/model_5_lstm/")
model_5.evaluate(test_windows, test_labels)
18/18 [==============================] - 0s 2ms/step - loss: 614.1224
Out[ ]:
614.1223754882812
In [ ]:
model_5_preds = make_preds(model_5, test_windows)
model_5_preds[:10]
18/18 [==============================] - 0s 2ms/step
Out[ ]:
<tf.Tensor: shape=(10,), dtype=float32, numpy=
array([9000.2295, 8839.915 , 8934.461 , 8807.579 , 8774.97  , 8750.144 ,
       8698.224 , 8581.72  , 8487.692 , 8508.767 ], dtype=float32)>
In [ ]:
model_5_results = evaluate_preds(y_true=tf.squeeze(test_labels),
                                 y_pred=model_5_preds)
model_5_results
Out[ ]:
{'mae': 614.12244,
 'mse': 1324128.0,
 'rmse': 1150.7076,
 'mape': 2.768758,
 'mase': 1.078843}

Model 6: Multivariant Data¶

In [ ]:
bitcoin_prices.head()
Out[ ]:
Price
Date
2013-10-01 123.65499
2013-10-02 125.45500
2013-10-03 108.58483
2013-10-04 118.67466
2013-10-05 121.33866
In [ ]:
block_reward_1 = 50 
block_reward_2 = 25
block_reward_3 = 12.5
block_reward_4 = 6.25

block_reward_2_datetime = np.datetime64("2012-11-28")
block_reward_3_datetime = np.datetime64("2016-07-09")
block_reward_4_datetime = np.datetime64("2020-05-11")
In [ ]:
block_reward_2_days = (block_reward_3_datetime - bitcoin_prices.index[0]).days
block_reward_3_days = (block_reward_4_datetime - bitcoin_prices.index[0]).days
block_reward_2_days, block_reward_3_days
Out[ ]:
(1012, 2414)
In [ ]:
bitcoin_prices_block = bitcoin_prices.copy()
bitcoin_prices_block["block_reward"] = None

bitcoin_prices_block.iloc[:block_reward_2_days, -1] = block_reward_2
bitcoin_prices_block.iloc[block_reward_2_days:block_reward_3_days, -1] = block_reward_3
bitcoin_prices_block.iloc[block_reward_3_days:, -1] = block_reward_4
bitcoin_prices_block.head()
Out[ ]:
Price block_reward
Date
2013-10-01 123.65499 25
2013-10-02 125.45500 25
2013-10-03 108.58483 25
2013-10-04 118.67466 25
2013-10-05 121.33866 25
In [ ]:
from sklearn.preprocessing import minmax_scale
scaled_price_block_df = pd.DataFrame(minmax_scale(bitcoin_prices_block[["Price", "block_reward"]]),
                                     columns=bitcoin_prices_block.columns,
                                     index=bitcoin_prices_block.index)
scaled_price_block_df.plot(figsize=(10, 7));
No description has been provided for this image
In [ ]:
HORIZON = 1
WINDOW_SIZE = 7
In [ ]:
bitcoin_prices_windowed = bitcoin_prices_block.copy()

for i in range(WINDOW_SIZE):
  bitcoin_prices_windowed[f"Price+{i+1}"] = bitcoin_prices_windowed["Price"].shift(periods=i+1)
bitcoin_prices_windowed.head(10)
Out[ ]:
Price block_reward Price+1 Price+2 Price+3 Price+4 Price+5 Price+6 Price+7
Date
2013-10-01 123.65499 25 NaN NaN NaN NaN NaN NaN NaN
2013-10-02 125.45500 25 123.65499 NaN NaN NaN NaN NaN NaN
2013-10-03 108.58483 25 125.45500 123.65499 NaN NaN NaN NaN NaN
2013-10-04 118.67466 25 108.58483 125.45500 123.65499 NaN NaN NaN NaN
2013-10-05 121.33866 25 118.67466 108.58483 125.45500 123.65499 NaN NaN NaN
2013-10-06 120.65533 25 121.33866 118.67466 108.58483 125.45500 123.65499 NaN NaN
2013-10-07 121.79500 25 120.65533 121.33866 118.67466 108.58483 125.45500 123.65499 NaN
2013-10-08 123.03300 25 121.79500 120.65533 121.33866 118.67466 108.58483 125.45500 123.65499
2013-10-09 124.04900 25 123.03300 121.79500 120.65533 121.33866 118.67466 108.58483 125.45500
2013-10-10 125.96116 25 124.04900 123.03300 121.79500 120.65533 121.33866 118.67466 108.58483
In [ ]:
X = bitcoin_prices_windowed.dropna().drop("Price", axis=1).astype(np.float32)
y = bitcoin_prices_windowed.dropna()["Price"].astype(np.float32)
X.head()
Out[ ]:
block_reward Price+1 Price+2 Price+3 Price+4 Price+5 Price+6 Price+7
Date
2013-10-08 25.0 121.794998 120.655327 121.338661 118.674660 108.584831 125.455002 123.654991
2013-10-09 25.0 123.032997 121.794998 120.655327 121.338661 118.674660 108.584831 125.455002
2013-10-10 25.0 124.049004 123.032997 121.794998 120.655327 121.338661 118.674660 108.584831
2013-10-11 25.0 125.961159 124.049004 123.032997 121.794998 120.655327 121.338661 118.674660
2013-10-12 25.0 125.279663 125.961159 124.049004 123.032997 121.794998 120.655327 121.338661
In [ ]:
y.head()
Out[ ]:
Date
2013-10-08    123.032997
2013-10-09    124.049004
2013-10-10    125.961159
2013-10-11    125.279663
2013-10-12    125.927498
Name: Price, dtype: float32
In [ ]:
split_size = int(len(X) * 0.8)
X_train, y_train = X[:split_size], y[:split_size]
X_test, y_test = X[split_size:], y[split_size:]
len(X_train), len(y_train), len(X_test), len(y_test)
Out[ ]:
(2224, 2224, 556, 556)
In [ ]:
tf.random.set_seed(42)

model_6 = tf.keras.Sequential([
  layers.Dense(128, activation="relu"),
  layers.Dense(HORIZON)
], name="model_6_dense_multivariate")

model_6.compile(loss="mae",
                optimizer=tf.keras.optimizers.Adam())

model_6.fit(X_train, y_train,
            epochs=100,
            batch_size=128,
            verbose=0,
            validation_data=(X_test, y_test),
            callbacks=[create_model_checkpoint(model_name=model_6.name)])
In [ ]:
model_6 = tf.keras.models.load_model("model_experiments/model_6_dense_multivariate")
model_6.evaluate(X_test, y_test)
18/18 [==============================] - 0s 2ms/step - loss: 567.2610
Out[ ]:
567.260986328125
In [ ]:
model_6_preds = tf.squeeze(model_6.predict(X_test))
model_6_preds[:10]
18/18 [==============================] - 0s 2ms/step
Out[ ]:
<tf.Tensor: shape=(10,), dtype=float32, numpy=
array([8861.014, 8757.47 , 8996.217, 8807.636, 8732.141, 8703.957,
       8683.494, 8525.386, 8439.305, 8512.089], dtype=float32)>
In [ ]:
model_6_results = evaluate_preds(y_true=y_test,
                                 y_pred=model_6_preds)
model_6_results
Out[ ]:
{'mae': 567.26105,
 'mse': 1167443.8,
 'rmse': 1080.4832,
 'mape': 2.5425735,
 'mase': 0.9965205}

Model 7: N-BEATS¶

In [ ]:
class NBeatsBlock(tf.keras.layers.Layer):
  def __init__(self,
               input_size: int,
               theta_size: int,
               horizon: int,
               n_neurons: int,
               n_layers: int,
               **kwargs): 
    super().__init__(**kwargs)
    self.input_size = input_size
    self.theta_size = theta_size
    self.horizon = horizon
    self.n_neurons = n_neurons
    self.n_layers = n_layers

    self.hidden = [tf.keras.layers.Dense(n_neurons, activation="relu") for _ in range(n_layers)]
    self.theta_layer = tf.keras.layers.Dense(theta_size, activation="linear", name="theta")

  def call(self, inputs): 
    x = inputs
    for layer in self.hidden: 
      x = layer(x)
    theta = self.theta_layer(x)
    backcast, forecast = theta[:, :self.input_size], theta[:, -self.horizon:]
    return backcast, forecast
In [ ]:
dummy_nbeats_block_layer = NBeatsBlock(input_size=WINDOW_SIZE,
                                       theta_size=WINDOW_SIZE+HORIZON,
                                       horizon=HORIZON,
                                       n_neurons=128,
                                       n_layers=4)
In [ ]:
dummy_inputs = tf.expand_dims(tf.range(WINDOW_SIZE) + 1, axis=0) 
dummy_inputs
Out[ ]:
<tf.Tensor: shape=(1, 7), dtype=int32, numpy=array([[1, 2, 3, 4, 5, 6, 7]], dtype=int32)>
In [ ]:
backcast, forecast = dummy_nbeats_block_layer(dummy_inputs)
print(f"Backcast: {tf.squeeze(backcast.numpy())}")
print(f"Forecast: {tf.squeeze(forecast.numpy())}")
Backcast: [-0.12375063  0.04774781 -0.32459643 -0.32171392 -0.02503065  0.48192424
 -0.07146749]
Forecast: 0.09792520105838776

Preparing data using tf.data¶

In [ ]:
HORIZON = 1 
WINDOW_SIZE = 7 
In [ ]:
bitcoin_prices.head()
Out[ ]:
Price
Date
2013-10-01 123.65499
2013-10-02 125.45500
2013-10-03 108.58483
2013-10-04 118.67466
2013-10-05 121.33866
In [ ]:
bitcoin_prices_nbeats = bitcoin_prices.copy()
for i in range(WINDOW_SIZE):
  bitcoin_prices_nbeats[f"Price+{i+1}"] = bitcoin_prices_nbeats["Price"].shift(periods=i+1)
bitcoin_prices_nbeats.dropna().head()
Out[ ]:
Price Price+1 Price+2 Price+3 Price+4 Price+5 Price+6 Price+7
Date
2013-10-08 123.03300 121.79500 120.65533 121.33866 118.67466 108.58483 125.45500 123.65499
2013-10-09 124.04900 123.03300 121.79500 120.65533 121.33866 118.67466 108.58483 125.45500
2013-10-10 125.96116 124.04900 123.03300 121.79500 120.65533 121.33866 118.67466 108.58483
2013-10-11 125.27966 125.96116 124.04900 123.03300 121.79500 120.65533 121.33866 118.67466
2013-10-12 125.92750 125.27966 125.96116 124.04900 123.03300 121.79500 120.65533 121.33866
In [ ]:
X = bitcoin_prices_nbeats.dropna().drop("Price", axis=1)
y = bitcoin_prices_nbeats.dropna()["Price"]

split_size = int(len(X) * 0.8)
X_train, y_train = X[:split_size], y[:split_size]
X_test, y_test = X[split_size:], y[split_size:]
len(X_train), len(y_train), len(X_test), len(y_test)
Out[ ]:
(2224, 2224, 556, 556)
In [ ]:
train_features_dataset = tf.data.Dataset.from_tensor_slices(X_train)
train_labels_dataset = tf.data.Dataset.from_tensor_slices(y_train)

test_features_dataset = tf.data.Dataset.from_tensor_slices(X_test)
test_labels_dataset = tf.data.Dataset.from_tensor_slices(y_test)

train_dataset = tf.data.Dataset.zip((train_features_dataset, train_labels_dataset))
test_dataset = tf.data.Dataset.zip((test_features_dataset, test_labels_dataset))

BATCH_SIZE = 1024
train_dataset = train_dataset.batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)
test_dataset = test_dataset.batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)

train_dataset, test_dataset
Out[ ]:
(<PrefetchDataset element_spec=(TensorSpec(shape=(None, 7), dtype=tf.float64, name=None), TensorSpec(shape=(None,), dtype=tf.float64, name=None))>,
 <PrefetchDataset element_spec=(TensorSpec(shape=(None, 7), dtype=tf.float64, name=None), TensorSpec(shape=(None,), dtype=tf.float64, name=None))>)
In [ ]:
N_EPOCHS = 5000 
N_NEURONS = 512 
N_LAYERS = 4
N_STACKS = 30

INPUT_SIZE = WINDOW_SIZE * HORIZON 
THETA_SIZE = INPUT_SIZE + HORIZON

INPUT_SIZE, THETA_SIZE
Out[ ]:
(7, 8)
In [ ]:
tensor_1 = tf.range(10) + 10
tensor_2 = tf.range(10)

subtracted = layers.subtract([tensor_1, tensor_2])

added = layers.add([tensor_1, tensor_2])

print(f"Input tensors: {tensor_1.numpy()} & {tensor_2.numpy()}")
print(f"Subtracted: {subtracted.numpy()}")
print(f"Added: {added.numpy()}")
Input tensors: [10 11 12 13 14 15 16 17 18 19] & [0 1 2 3 4 5 6 7 8 9]
Subtracted: [10 10 10 10 10 10 10 10 10 10]
Added: [10 12 14 16 18 20 22 24 26 28]
In [ ]:
tf.random.set_seed(42)

nbeats_block_layer = NBeatsBlock(input_size=INPUT_SIZE,
                                 theta_size=THETA_SIZE,
                                 horizon=HORIZON,
                                 n_neurons=N_NEURONS,
                                 n_layers=N_LAYERS,
                                 name="InitialBlock")

stack_input = layers.Input(shape=(INPUT_SIZE), name="stack_input")

backcast, forecast = nbeats_block_layer(stack_input)
residuals = layers.subtract([stack_input, backcast], name=f"subtract_00")

for i, _ in enumerate(range(N_STACKS-1)): 

  backcast, block_forecast = NBeatsBlock(
      input_size=INPUT_SIZE,
      theta_size=THETA_SIZE,
      horizon=HORIZON,
      n_neurons=N_NEURONS,
      n_layers=N_LAYERS,
      name=f"NBeatsBlock_{i}"
  )(residuals) 
  residuals = layers.subtract([residuals, backcast], name=f"subtract_{i}")
  forecast = layers.add([forecast, block_forecast], name=f"add_{i}")

model_7 = tf.keras.Model(inputs=stack_input,
                         outputs=forecast,
                         name="model_7_N-BEATS")

model_7.compile(loss="mae",
                optimizer=tf.keras.optimizers.Adam(0.001),
                metrics=["mae", "mse"])

model_7.fit(train_dataset,
            epochs=N_EPOCHS,
            validation_data=test_dataset,
            verbose=0, 
            callbacks=[tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=200, restore_best_weights=True),
                      tf.keras.callbacks.ReduceLROnPlateau(monitor="val_loss", patience=100, verbose=1)])
In [ ]:
model_7.evaluate(test_dataset)
1/1 [==============================] - 1s 532ms/step - loss: 645.2433 - mae: 645.2433 - mse: 1403377.1250
Out[ ]:
[645.2433471679688, 645.2433471679688, 1403377.125]
In [ ]:
model_7_preds = make_preds(model_7, test_dataset)
model_7_preds[:10]
1/1 [==============================] - 5s 5s/step
Out[ ]:
<tf.Tensor: shape=(10,), dtype=float32, numpy=
array([8848.904, 8797.149, 8978.421, 8727.149, 8692.965, 8678.041,
       8613.595, 8501.041, 8425.463, 8468.33 ], dtype=float32)>
In [ ]:
model_7_results = evaluate_preds(y_true=y_test,
                                 y_pred=model_7_preds)
model_7_results
Out[ ]:
{'mae': 645.24335,
 'mse': 1403377.1,
 'rmse': 1184.6422,
 'mape': 2.9733312,
 'mase': 1.1335138}
In [ ]:
from tensorflow.keras.utils import plot_model
plot_model(model_7)
Out[ ]:
No description has been provided for this image
In [ ]:
model_7.save(model_7.name)

Model 8: Creating ensemble (stacking multiple Models)¶

In [ ]:
def get_ensemble_models(horizon=HORIZON,
                        train_data=train_dataset,
                        test_data=test_dataset,
                        num_iter=10,
                        num_epochs=100,
                        loss_fns=["mae", "mse", "mape"]):
  """
  Returns a list of num_iter models each trained on MAE, MSE and MAPE loss.

  For example, if num_iter=10, a list of 30 trained models will be returned:
  10 * len(["mae", "mse", "mape"]).
  """
  ensemble_models = []

  for i in range(num_iter):
    for loss_function in loss_fns:
      print(f"Optimizing model by reducing: {loss_function} for {num_epochs} epochs, model number: {i}")

      model = tf.keras.Sequential([
        layers.Dense(128, kernel_initializer="he_normal", activation="relu"),
        layers.Dense(128, kernel_initializer="he_normal", activation="relu"),
        layers.Dense(HORIZON)
      ])

      model.compile(loss=loss_function,
                    optimizer=tf.keras.optimizers.Adam(),
                    metrics=["mae", "mse"])

      model.fit(train_data,
                epochs=num_epochs,
                verbose=0,
                validation_data=test_data,
                callbacks=[tf.keras.callbacks.EarlyStopping(monitor="val_loss",
                                                            patience=200,
                                                            restore_best_weights=True),
                           tf.keras.callbacks.ReduceLROnPlateau(monitor="val_loss",
                                                                patience=100,
                                                                verbose=1)])

      ensemble_models.append(model)

  return ensemble_models
In [ ]:
ensemble_models = get_ensemble_models(num_iter=5,
                                      num_epochs=1000)
Optimizing model by reducing: mae for 1000 epochs, model number: 0
Optimizing model by reducing: mse for 1000 epochs, model number: 0

Epoch 272: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 372: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.
Optimizing model by reducing: mape for 1000 epochs, model number: 0

Epoch 223: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 328: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.

Epoch 881: ReduceLROnPlateau reducing learning rate to 1.0000000656873453e-06.

Epoch 981: ReduceLROnPlateau reducing learning rate to 1.0000001111620805e-07.
Optimizing model by reducing: mae for 1000 epochs, model number: 1

Epoch 361: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.
Optimizing model by reducing: mse for 1000 epochs, model number: 1

Epoch 460: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 560: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.
Optimizing model by reducing: mape for 1000 epochs, model number: 1

Epoch 173: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 505: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.
Optimizing model by reducing: mae for 1000 epochs, model number: 2

Epoch 493: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 593: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.
Optimizing model by reducing: mse for 1000 epochs, model number: 2

Epoch 916: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.
Optimizing model by reducing: mape for 1000 epochs, model number: 2

Epoch 219: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 319: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.
Optimizing model by reducing: mae for 1000 epochs, model number: 3

Epoch 421: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.
Optimizing model by reducing: mse for 1000 epochs, model number: 3

Epoch 288: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 388: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.
Optimizing model by reducing: mape for 1000 epochs, model number: 3

Epoch 247: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 347: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.
Optimizing model by reducing: mae for 1000 epochs, model number: 4

Epoch 367: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.
Optimizing model by reducing: mse for 1000 epochs, model number: 4

Epoch 248: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 348: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.
Optimizing model by reducing: mape for 1000 epochs, model number: 4

Epoch 226: ReduceLROnPlateau reducing learning rate to 0.00010000000474974513.

Epoch 883: ReduceLROnPlateau reducing learning rate to 1.0000000474974514e-05.

Epoch 983: ReduceLROnPlateau reducing learning rate to 1.0000000656873453e-06.
CPU times: user 8min 30s, sys: 18.8 s, total: 8min 49s
Wall time: 10min 42s
In [ ]:
def make_ensemble_preds(ensemble_models, data):
  ensemble_preds = []
  for model in ensemble_models:
    preds = model.predict(data) 
    ensemble_preds.append(preds)
  return tf.constant(tf.squeeze(ensemble_preds))
In [ ]:
ensemble_preds = make_ensemble_preds(ensemble_models=ensemble_models,
                                     data=test_dataset)
ensemble_preds
1/1 [==============================] - 0s 105ms/step
1/1 [==============================] - 0s 64ms/step
WARNING:tensorflow:5 out of the last 22 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7f544c7f51f0> 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 53ms/step
WARNING:tensorflow:6 out of the last 23 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7f544c7f5700> 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 55ms/step
1/1 [==============================] - 0s 49ms/step
1/1 [==============================] - 0s 47ms/step
1/1 [==============================] - 0s 51ms/step
1/1 [==============================] - 0s 49ms/step
1/1 [==============================] - 0s 47ms/step
1/1 [==============================] - 0s 47ms/step
1/1 [==============================] - 0s 46ms/step
1/1 [==============================] - 0s 46ms/step
1/1 [==============================] - 0s 46ms/step
1/1 [==============================] - 0s 59ms/step
1/1 [==============================] - 0s 57ms/step
Out[ ]:
<tf.Tensor: shape=(15, 556), dtype=float32, numpy=
array([[ 8871.281 ,  8784.015 ,  9030.399 , ..., 50435.996 , 49406.496 ,
        45706.48  ],
       [ 8726.012 ,  8768.488 ,  9013.082 , ..., 49912.887 , 48393.945 ,
        46313.523 ],
       [ 8808.467 ,  8782.644 ,  9080.286 , ..., 49736.09  , 48596.727 ,
        45983.273 ],
       ...,
       [ 8814.5   ,  8765.516 ,  9048.904 , ..., 50083.23  , 48809.223 ,
        45704.77  ],
       [ 8830.308 ,  8790.611 ,  9044.155 , ..., 49832.906 , 48108.312 ,
        46238.188 ],
       [ 8783.409 ,  8792.559 ,  9085.6875, ..., 50007.855 , 49030.766 ,
        46546.355 ]], dtype=float32)>
In [ ]:
ensemble_results = evaluate_preds(y_true=y_test,
                                  y_pred=np.median(ensemble_preds, axis=0)) 
ensemble_results
Out[ ]:
{'mae': 566.8151,
 'mse': 1146559.4,
 'rmse': 1070.7751,
 'mape': 2.5635748,
 'mase': 0.9957372}
In [ ]:
def get_upper_lower(preds):

  std = tf.math.reduce_std(preds, axis=0)

  interval = 1.96 * std 
  preds_mean = tf.reduce_mean(preds, axis=0)
  lower, upper = preds_mean - interval, preds_mean + interval
  return lower, upper

lower, upper = get_upper_lower(preds=ensemble_preds)
In [ ]:
ensemble_median = np.median(ensemble_preds, axis=0)

offset=500
plt.figure(figsize=(10, 7))
plt.plot(X_test.index[offset:], y_test[offset:], "g", label="Test Data")
plt.plot(X_test.index[offset:], ensemble_median[offset:], "k-", label="Ensemble Median")
plt.xlabel("Date")
plt.ylabel("BTC Price")
plt.fill_between(X_test.index[offset:],
                 (lower)[offset:],
                 (upper)[offset:], label="Prediction Intervals")
plt.legend(loc="upper left", fontsize=14);
No description has been provided for this image

Model 9: Train a model on the full historical data to make predictions into future¶

In [ ]:
bitcoin_prices_windowed.head()
Out[ ]:
Price block_reward Price+1 Price+2 Price+3 Price+4 Price+5 Price+6 Price+7
Date
2013-10-01 123.65499 25 NaN NaN NaN NaN NaN NaN NaN
2013-10-02 125.45500 25 123.65499 NaN NaN NaN NaN NaN NaN
2013-10-03 108.58483 25 125.45500 123.65499 NaN NaN NaN NaN NaN
2013-10-04 118.67466 25 108.58483 125.45500 123.65499 NaN NaN NaN NaN
2013-10-05 121.33866 25 118.67466 108.58483 125.45500 123.65499 NaN NaN NaN
In [ ]:
X_all = bitcoin_prices_windowed.drop(["Price", "block_reward"], axis=1).dropna().to_numpy()
y_all = bitcoin_prices_windowed.dropna()["Price"].to_numpy()
In [ ]:
features_dataset_all = tf.data.Dataset.from_tensor_slices(X_all)
labels_dataset_all = tf.data.Dataset.from_tensor_slices(y_all)

dataset_all = tf.data.Dataset.zip((features_dataset_all, labels_dataset_all))

BATCH_SIZE = 1024
dataset_all = dataset_all.batch(BATCH_SIZE).prefetch(tf.data.AUTOTUNE)

dataset_all
Out[ ]:
<PrefetchDataset element_spec=(TensorSpec(shape=(None, 7), dtype=tf.float64, name=None), TensorSpec(shape=(None,), dtype=tf.float64, name=None))>
In [ ]:
tf.random.set_seed(42)

model_9 = tf.keras.Sequential([
  layers.Dense(128, activation="relu"),
  layers.Dense(128, activation="relu"),
  layers.Dense(HORIZON)
])

model_9.compile(loss=tf.keras.losses.mae,
                optimizer=tf.keras.optimizers.Adam())

model_9.fit(dataset_all,
            epochs=100,
            verbose=0)
Out[ ]:
<keras.callbacks.History at 0x7f544e955c70>
In [ ]:
INTO_FUTURE = 14
In [ ]:
def make_future_forecast(values, model, into_future, window_size=WINDOW_SIZE) -> list:
  """
  Makes future forecasts into_future steps after values ends.

  Returns future forecasts as list of floats.
  """
  future_forecast = []
  last_window = values[-WINDOW_SIZE:]

  for _ in range(into_future):

    future_pred = model.predict(tf.expand_dims(last_window, axis=0))
    print(f"Predicting on: \n {last_window} -> Prediction: {tf.squeeze(future_pred).numpy()}\n")

    future_forecast.append(tf.squeeze(future_pred).numpy())

    last_window = np.append(last_window, future_pred)[-WINDOW_SIZE:]

  return future_forecast
In [ ]:
future_forecast = make_future_forecast(values=y_all,
                                       model=model_9,
                                       into_future=INTO_FUTURE,
                                       window_size=WINDOW_SIZE)
1/1 [==============================] - 0s 80ms/step
Predicting on: 
 [56573.5554719  52147.82118698 49764.1320816  50032.69313676
 47885.62525472 45604.61575361 43144.47129086] -> Prediction: 56197.69921875

1/1 [==============================] - 0s 28ms/step
Predicting on: 
 [52147.82118698 49764.1320816  50032.69313676 47885.62525472
 45604.61575361 43144.47129086 56197.69921875] -> Prediction: 50857.90625

1/1 [==============================] - 0s 25ms/step
Predicting on: 
 [49764.1320816  50032.69313676 47885.62525472 45604.61575361
 43144.47129086 56197.69921875 50857.90625   ] -> Prediction: 50806.4140625

1/1 [==============================] - 0s 26ms/step
Predicting on: 
 [50032.69313676 47885.62525472 45604.61575361 43144.47129086
 56197.69921875 50857.90625    50806.4140625 ] -> Prediction: 48320.3125

1/1 [==============================] - 0s 24ms/step
Predicting on: 
 [47885.62525472 45604.61575361 43144.47129086 56197.69921875
 50857.90625    50806.4140625  48320.3125    ] -> Prediction: 48515.421875

1/1 [==============================] - 0s 27ms/step
Predicting on: 
 [45604.61575361 43144.47129086 56197.69921875 50857.90625
 50806.4140625  48320.3125     48515.421875  ] -> Prediction: 44613.91015625

1/1 [==============================] - 0s 26ms/step
Predicting on: 
 [43144.47129086 56197.69921875 50857.90625    50806.4140625
 48320.3125     48515.421875   44613.91015625] -> Prediction: 48087.86328125

1/1 [==============================] - 0s 26ms/step
Predicting on: 
 [56197.69921875 50857.90625    50806.4140625  48320.3125
 48515.421875   44613.91015625 48087.86328125] -> Prediction: 54764.28125

1/1 [==============================] - 0s 29ms/step
Predicting on: 
 [50857.90625    50806.4140625  48320.3125     48515.421875
 44613.91015625 48087.86328125 54764.28125   ] -> Prediction: 51082.3828125

1/1 [==============================] - 0s 24ms/step
Predicting on: 
 [50806.4140625  48320.3125     48515.421875   44613.91015625
 48087.86328125 54764.28125    51082.3828125 ] -> Prediction: 50153.84375

1/1 [==============================] - 0s 26ms/step
Predicting on: 
 [48320.3125     48515.421875   44613.91015625 48087.86328125
 54764.28125    51082.3828125  50153.84375   ] -> Prediction: 48228.11328125

1/1 [==============================] - 0s 25ms/step
Predicting on: 
 [48515.421875   44613.91015625 48087.86328125 54764.28125
 51082.3828125  50153.84375    48228.11328125] -> Prediction: 48151.65625

1/1 [==============================] - 0s 25ms/step
Predicting on: 
 [44613.91015625 48087.86328125 54764.28125    51082.3828125
 50153.84375    48228.11328125 48151.65625   ] -> Prediction: 45754.9765625

1/1 [==============================] - 0s 27ms/step
Predicting on: 
 [48087.86328125 54764.28125    51082.3828125  50153.84375
 48228.11328125 48151.65625    45754.9765625 ] -> Prediction: 50949.98828125

In [ ]:
def get_future_dates(start_date, into_future, offset=1):
  """
  Returns array of datetime values from ranging from start_date to start_date+horizon.

  start_date: date to start range (np.datetime64)
  into_future: number of days to add onto start date for range (int)
  offset: number of days to offset start_date by (default 1)
  """
  start_date = start_date + np.timedelta64(offset, "D") 
  end_date = start_date + np.timedelta64(into_future, "D") 
  return np.arange(start_date, end_date, dtype="datetime64[D]") 
In [ ]:
last_timestep = bitcoin_prices.index[-1]
last_timestep
Out[ ]:
Timestamp('2021-05-18 00:00:00')
In [ ]:
next_time_steps = get_future_dates(start_date=last_timestep,
                                   into_future=INTO_FUTURE)
next_time_steps
Out[ ]:
array(['2021-05-19', '2021-05-20', '2021-05-21', '2021-05-22',
       '2021-05-23', '2021-05-24', '2021-05-25', '2021-05-26',
       '2021-05-27', '2021-05-28', '2021-05-29', '2021-05-30',
       '2021-05-31', '2021-06-01'], dtype='datetime64[D]')
In [ ]:
next_time_steps = np.insert(next_time_steps, 0, last_timestep)
future_forecast = np.insert(future_forecast, 0, btc_price[-1])
next_time_steps, future_forecast
Out[ ]:
(array(['2021-05-18', '2021-05-19', '2021-05-20', '2021-05-21',
        '2021-05-22', '2021-05-23', '2021-05-24', '2021-05-25',
        '2021-05-26', '2021-05-27', '2021-05-28', '2021-05-29',
        '2021-05-30', '2021-05-31', '2021-06-01'], dtype='datetime64[D]'),
 array([43144.473, 56197.7  , 50857.906, 50806.414, 48320.312, 48515.42 ,
        44613.91 , 48087.863, 54764.28 , 51082.383, 50153.844, 48228.113,
        48151.656, 45754.977, 50949.99 ], dtype=float32))
In [ ]:
plt.figure(figsize=(10, 7))
plot_time_series(bitcoin_prices.index, btc_price, start=2500, format="-", label="Actual BTC Price")
plot_time_series(next_time_steps, future_forecast, format="-", label="Predicted BTC Price")
No description has been provided for this image
In [ ]:
model_results = pd.DataFrame({"naive_model": naive_results,
                              "model_1_dense_w7_h1": model_1_results,
                              "model_2_dense_w30_h1": model_2_results,
                              "model_3_dense_w30_h7": model_3_results,
                              "model_4_CONV1D": model_4_results,
                              "model_5_LSTM": model_5_results,
                              "model_6_multivariate": model_6_results,
                              "model_8_NBEATs": model_7_results,
                              "model_9_ensemble": ensemble_results}).T
model_results.head(10)
Out[ ]:
mae mse rmse mape mase
naive_model 567.980225 1147547.000 1071.236206 2.516525 0.999570
model_1_dense_w7_h1 572.492737 1181174.875 1086.818726 2.565485 1.005711
model_2_dense_w30_h1 618.858948 1311890.000 1145.377686 2.774799 1.081771
model_3_dense_w30_h7 1235.451416 5316866.000 1427.353760 5.640647 2.198416
model_4_CONV1D 567.256836 1174792.125 1083.878296 2.542460 0.996513
model_5_LSTM 614.122437 1324128.000 1150.707642 2.768758 1.078843
model_6_multivariate 567.261047 1167443.750 1080.483154 2.542573 0.996521
model_8_NBEATs 645.243347 1403377.125 1184.642212 2.973331 1.133514
model_9_ensemble 566.815125 1146559.375 1070.775146 2.563575 0.995737
In [ ]:
model_results[["mae"]].sort_values(by="mae").plot(figsize=(10, 7), kind="bar");
No description has been provided for this image