handson-ml/15_processing_sequences_usi...

2345 lines
80 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Chapter 15 Processing Sequences Using RNNs and CNNs**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"_This notebook contains all the sample code and solutions to the exercises in chapter 15._"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<table align=\"left\">\n",
" <td>\n",
" <a href=\"https://colab.research.google.com/github/ageron/handson-ml3/blob/main/15_processing_sequences_using_rnns_and_cnns.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
" </td>\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://kaggle.com/kernels/welcome?src=https://github.com/ageron/handson-ml3/blob/main/15_processing_sequences_using_rnns_and_cnns.ipynb\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" /></a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8IPbJEmZpKzu"
},
"source": [
"This project requires Python 3.8 or above:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"id": "TFSU3FCOpKzu"
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"assert sys.version_info >= (3, 8)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TAlKky09pKzv"
},
"source": [
"It also requires Scikit-Learn ≥ 1.0.1:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"id": "YqCwW7cMpKzw"
},
"outputs": [],
"source": [
"import sklearn\n",
"\n",
"assert sklearn.__version__ >= \"1.0.1\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GJtVEqxfpKzw"
},
"source": [
"And TensorFlow ≥ 2.6:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "0Piq5se2pKzx"
},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"\n",
"assert tf.__version__ >= \"2.6.0\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DDaDoLQTpKzx"
},
"source": [
"As we did in earlier chapters, let's define the default font sizes to make the figures prettier:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"id": "8d4TH3NbpKzx"
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"plt.rc('font', size=14)\n",
"plt.rc('axes', labelsize=14, titlesize=14)\n",
"plt.rc('legend', fontsize=14)\n",
"plt.rc('xtick', labelsize=10)\n",
"plt.rc('ytick', labelsize=10)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RcoUIRsvpKzy"
},
"source": [
"And let's create the `images/rnn` folder (if it doesn't already exist), and define the `save_fig()` function which is used through this notebook to save the figures in high-res for the book:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"id": "PQFH5Y9PpKzy"
},
"outputs": [],
"source": [
"from pathlib import Path\n",
"\n",
"IMAGES_PATH = Path() / \"images\" / \"rnn\"\n",
"IMAGES_PATH.mkdir(parents=True, exist_ok=True)\n",
"\n",
"def save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n",
" path = IMAGES_PATH / f\"{fig_id}.{fig_extension}\"\n",
" if tight_layout:\n",
" plt.tight_layout()\n",
" plt.savefig(path, format=fig_extension, dpi=resolution)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YTsawKlapKzy"
},
"source": [
"This chapter can be very slow without a GPU, so let's make sure there's one, or else issue a warning:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"id": "Ekxzo6pOpKzy"
},
"outputs": [],
"source": [
"if not tf.config.list_physical_devices('GPU'):\n",
" print(\"No GPU was detected. Neural nets can be very slow without a GPU.\")\n",
" if \"google.colab\" in sys.modules:\n",
" print(\"Go to Runtime > Change runtime and select a GPU hardware \"\n",
" \"accelerator.\")\n",
" if \"kaggle_secrets\" in sys.modules:\n",
" print(\"Go to Settings > Accelerator and select GPU.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Basic RNNs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's load ridership data from Chicago's Transit Authority (available on [Chicago's Data Portal](https://homl.info/ridership)."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"from pathlib import Path\n",
"\n",
"path = Path(\"datasets/ridership/CTA_-_Ridership_-_Daily_Boarding_Totals.csv\")\n",
"df = pd.read_csv(path, parse_dates=[\"service_date\"])\n",
"df.columns = [\"date\", \"day_type\", \"bus\", \"rail\", \"total\"] # shorter names\n",
"df = df.sort_values(\"date\").set_index(\"date\")\n",
"df = df.drop(\"total\", axis=1) # no need for total, it's just bus + rail\n",
"df = df.drop_duplicates() # remove duplicated months (2011-10 and 2014-07)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's look at the first few months of 2019 (note that Pandas treats the range boundaries as inclusive):"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"\n",
"df[\"2019-03\":\"2019-05\"].plot(grid=True, marker=\".\", figsize=(8, 3.5))\n",
"save_fig(\"daily_ridership_plot\") # extra code saves the figure for the book\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"diff_7 = df[[\"bus\", \"rail\"]].diff(7)[\"2019-03\":\"2019-05\"]\n",
"\n",
"fig, axs = plt.subplots(2, 1, sharex=True, figsize=(8, 5))\n",
"df.plot(ax=axs[0], legend=False, marker=\".\") # original time series\n",
"df.shift(7).plot(ax=axs[0], grid=True, legend=False, linestyle=\":\") # lagged\n",
"diff_7.plot(ax=axs[1], grid=True, marker=\".\") # 7-day difference time series\n",
"axs[0].set_ylim([170_000, 900_000]) # extra code beautifies the plot\n",
"save_fig(\"differencing_plot\") # extra code saves the figure for the book\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"list(df.loc[\"2019-05-25\":\"2019-05-27\"][\"day_type\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Mean absolute error (MAE), also called mean absolute deviation (MAD):"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"diff_7.abs().mean()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Mean absolute percentage error (MAPE):"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"targets = df[[\"bus\", \"rail\"]][\"2019-03\":\"2019-05\"]\n",
"(diff_7 / targets).abs().mean()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's look at the yearly seasonality and the long-term trends:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"period = slice(\"2001\", \"2019\")\n",
"df_monthly = df.resample('M').mean() # compute the mean for each month\n",
"rolling_average_12_months = df_monthly[period].rolling(window=12).mean()\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 4))\n",
"df_monthly[period].plot(ax=ax, marker=\".\")\n",
"rolling_average_12_months.plot(ax=ax, grid=True, legend=False)\n",
"save_fig(\"long_term_ridership_plot\") # extra code saves the figure for the book\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"df_monthly.diff(12)[period].plot(grid=True, marker=\".\", figsize=(8, 3))\n",
"save_fig(\"yearly_diff_plot\") # extra code saves the figure for the book\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"from statsmodels.tsa.arima.model import ARIMA\n",
"\n",
"origin, today = \"2019-01-01\", \"2019-05-31\"\n",
"rail_series = df.loc[origin:today][\"rail\"].asfreq(\"D\")\n",
"model = ARIMA(rail_series,\n",
" order=(1, 0, 0),\n",
" seasonal_order=(0, 1, 1, 7))\n",
"model = model.fit()\n",
"y_pred = model.forecast() # returns 427,758.6"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"y_pred[0] # ARIMA forecast"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"df[\"rail\"].loc[\"2019-06-01\"] # target value"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"df[\"rail\"].loc[\"2019-05-25\"] # naive forecast (value from one week earlier)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"origin, start_date, end_date = \"2019-01-01\", \"2019-03-01\", \"2019-05-31\"\n",
"time_period = pd.date_range(start_date, end_date)\n",
"rail_series = df.loc[origin:end_date][\"rail\"].asfreq(\"D\")\n",
"y_preds = []\n",
"for today in time_period.shift(-1):\n",
" model = ARIMA(rail_series[origin:today], # train on data up to \"today\"\n",
" order=(1, 0, 0),\n",
" seasonal_order=(0, 1, 1, 7))\n",
" model = model.fit() # note that we retrain the model every day!\n",
" y_pred = model.forecast()[0]\n",
" y_preds.append(y_pred)\n",
"\n",
"y_preds = pd.Series(y_preds, index=time_period)\n",
"mae = (y_preds - rail_series[time_period]).abs().mean() # returns 32,040.7"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"mae"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"# extra code displays the SARIMA forecasts\n",
"fig, ax = plt.subplots(figsize=(8, 3))\n",
"rail_series.loc[time_period].plot(label=\"True\", ax=ax, marker=\".\", grid=True)\n",
"ax.plot(y_preds, color=\"r\", marker=\".\", label=\"SARIMA Forecasts\")\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"# extra code shows how to plot the Autocorrelation Function (ACF) and the\n",
"# Partial Autocorrelation Function (PACF)\n",
"\n",
"from statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n",
"\n",
"fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(15, 5))\n",
"plot_acf(df[period][\"rail\"], ax=axs[0], lags=35)\n",
"axs[0].grid()\n",
"plot_pacf(df[period][\"rail\"], ax=axs[1], lags=35, method=\"ywm\")\n",
"axs[1].grid()\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"\n",
"my_series = [0, 1, 2, 3, 4, 5]\n",
"my_dataset = tf.keras.utils.timeseries_dataset_from_array(\n",
" my_series,\n",
" targets=my_series[3:], # the targets are 3 steps into the future\n",
" sequence_length=3,\n",
" batch_size=2\n",
")\n",
"list(my_dataset)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"for window_dataset in tf.data.Dataset.range(6).window(4, shift=1):\n",
" for element in window_dataset:\n",
" print(f\"{element}\", end=\" \")\n",
" print()"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"dataset = tf.data.Dataset.range(6).window(4, shift=1, drop_remainder=True)\n",
"dataset = dataset.flat_map(lambda window_dataset: window_dataset.batch(4))\n",
"for window_tensor in dataset:\n",
" print(f\"{window_tensor}\")"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"def to_windows(dataset, length):\n",
" dataset = dataset.window(length, shift=1, drop_remainder=True)\n",
" return dataset.flat_map(lambda window_ds: window_ds.batch(length))"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"dataset = to_windows(tf.data.Dataset.range(6), 4)\n",
"dataset = dataset.map(lambda window: (window[:-1], window[-1]))\n",
"list(dataset.batch(2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before we continue looking at the data, let's split the time series into three periods, for training, validation and testing. We won't look at the test data for now:"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"rail_train = df[\"rail\"][\"2016-01\":\"2018-12\"] / 1e6\n",
"rail_valid = df[\"rail\"][\"2019-01\":\"2019-05\"] / 1e6\n",
"rail_test = df[\"rail\"][\"2019-06\":] / 1e6"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"seq_length = 56\n",
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"train_ds = tf.keras.utils.timeseries_dataset_from_array(\n",
" rail_train.to_numpy(),\n",
" targets=rail_train[seq_length:],\n",
" sequence_length=seq_length,\n",
" batch_size=32,\n",
" shuffle=True,\n",
" seed=42\n",
")\n",
"valid_ds = tf.keras.utils.timeseries_dataset_from_array(\n",
" rail_valid.to_numpy(),\n",
" targets=rail_valid[seq_length:],\n",
" sequence_length=seq_length,\n",
" batch_size=32\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42)\n",
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Dense(1, input_shape=[seq_length])\n",
"])\n",
"early_stopping_cb = tf.keras.callbacks.EarlyStopping(\n",
" monitor=\"val_mae\", patience=50, restore_best_weights=True)\n",
"opt = tf.keras.optimizers.SGD(learning_rate=0.02, momentum=0.9)\n",
"model.compile(loss=tf.keras.losses.Huber(), optimizer=opt, metrics=[\"mae\"])\n",
"history = model.fit(train_ds, validation_data=valid_ds, epochs=500,\n",
" callbacks=[early_stopping_cb])"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"# extra code evaluates the model\n",
"valid_loss, valid_mae = model.evaluate(valid_ds)\n",
"valid_mae * 1e6"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using a Simple RNN"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"model = tf.keras.Sequential([\n",
" tf.keras.layers.SimpleRNN(1, input_shape=[None, 1])\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [],
"source": [
"# extra code defines a utility function we'll reuse several time\n",
"\n",
"def fit_and_evaluate(model, train_set, valid_set, learning_rate, epochs=500):\n",
" early_stopping_cb = tf.keras.callbacks.EarlyStopping(\n",
" monitor=\"val_mae\", patience=50, restore_best_weights=True)\n",
" opt = tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)\n",
" model.compile(loss=tf.keras.losses.Huber(), optimizer=opt, metrics=[\"mae\"])\n",
" history = model.fit(train_set, validation_data=valid_set, epochs=epochs,\n",
" callbacks=[early_stopping_cb])\n",
" valid_loss, valid_mae = model.evaluate(valid_set)\n",
" return valid_mae * 1e6"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(model, train_ds, valid_ds, learning_rate=0.02)"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"univar_model = tf.keras.Sequential([\n",
" tf.keras.layers.SimpleRNN(32, input_shape=[None, 1]),\n",
" tf.keras.layers.Dense(1) # no activation function by default\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"# extra code compiles, fits, and evaluates the model, like earlier\n",
"fit_and_evaluate(univar_model, train_ds, valid_ds, learning_rate=0.05)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Deep RNNs"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"deep_model = tf.keras.Sequential([\n",
" tf.keras.layers.SimpleRNN(32, return_sequences=True, input_shape=[None, 1]),\n",
" tf.keras.layers.SimpleRNN(32, return_sequences=True),\n",
" tf.keras.layers.SimpleRNN(32),\n",
" tf.keras.layers.Dense(1)\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [],
"source": [
"# extra code compiles, fits, and evaluates the model, like earlier\n",
"fit_and_evaluate(deep_model, train_ds, valid_ds, learning_rate=0.01)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Multivariate time series"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [],
"source": [
"df_mulvar = df[[\"bus\", \"rail\"]] / 1e6 # use both bus & rail series as input\n",
"df_mulvar[\"next_day_type\"] = df[\"day_type\"].shift(-1) # we know tomorrow's type\n",
"df_mulvar = pd.get_dummies(df_mulvar) # one-hot encode the day type"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
"mulvar_train = df_mulvar[\"2016-01\":\"2018-12\"]\n",
"mulvar_valid = df_mulvar[\"2019-01\":\"2019-05\"]\n",
"mulvar_test = df_mulvar[\"2019-06\":]"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"\n",
"train_mulvar_ds = tf.keras.utils.timeseries_dataset_from_array(\n",
" mulvar_train.to_numpy(), # use all 5 columns as input\n",
" targets=mulvar_train[\"rail\"][seq_length:], # forecast only the rail series\n",
" sequence_length=seq_length,\n",
" batch_size=32,\n",
" shuffle=True,\n",
" seed=42\n",
")\n",
"valid_mulvar_ds = tf.keras.utils.timeseries_dataset_from_array(\n",
" mulvar_valid.to_numpy(),\n",
" targets=mulvar_valid[\"rail\"][seq_length:],\n",
" sequence_length=seq_length,\n",
" batch_size=32\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"mulvar_model = tf.keras.Sequential([\n",
" tf.keras.layers.SimpleRNN(32, input_shape=[None, 5]),\n",
" tf.keras.layers.Dense(1)\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"# extra code compiles, fits, and evaluates the model, like earlier\n",
"fit_and_evaluate(mulvar_model, train_mulvar_ds, valid_mulvar_ds,\n",
" learning_rate=0.05)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"# extra code build and train a multitask RNN that forecasts both bus and rail\n",
"\n",
"tf.random.set_seed(42)\n",
"\n",
"seq_length = 56\n",
"train_multask_ds = tf.keras.utils.timeseries_dataset_from_array(\n",
" mulvar_train.to_numpy(),\n",
" targets=mulvar_train[[\"bus\", \"rail\"]][seq_length:], # 2 targets per day\n",
" sequence_length=seq_length,\n",
" batch_size=32,\n",
" shuffle=True,\n",
" seed=42\n",
")\n",
"valid_multask_ds = tf.keras.utils.timeseries_dataset_from_array(\n",
" mulvar_valid.to_numpy(),\n",
" targets=mulvar_valid[[\"bus\", \"rail\"]][seq_length:],\n",
" sequence_length=seq_length,\n",
" batch_size=32\n",
")\n",
"\n",
"tf.random.set_seed(42)\n",
"multask_model = tf.keras.Sequential([\n",
" tf.keras.layers.SimpleRNN(32, input_shape=[None, 5]),\n",
" tf.keras.layers.Dense(2)\n",
"])\n",
"\n",
"fit_and_evaluate(multask_model, train_multask_ds, valid_multask_ds,\n",
" learning_rate=0.02)"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [],
"source": [
"# extra code evaluates the naive forecasts for bus\n",
"bus_naive = mulvar_valid[\"bus\"].shift(7)[seq_length:]\n",
"bus_target = mulvar_valid[\"bus\"][seq_length:]\n",
"(bus_target - bus_naive).abs().mean() * 1e6"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [],
"source": [
"# extra code evaluates the multitask RNN's forecasts both bus and rail\n",
"Y_preds_valid = multask_model.predict(valid_multask_ds)\n",
"for idx, name in enumerate([\"bus\", \"rail\"]):\n",
" mae = 1e6 * tf.keras.metrics.mean_absolute_error(\n",
" mulvar_valid[name][seq_length:], Y_preds_valid[:, idx])\n",
" print(name, int(mae))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Forecasting Several Steps Ahead"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"X = rail_valid.to_numpy()[np.newaxis, :seq_length, np.newaxis]\n",
"for step_ahead in range(14):\n",
" y_pred_one = univar_model.predict(X)\n",
" X = np.concatenate([X, y_pred_one.reshape(1, 1, 1)], axis=1)"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [],
"source": [
"# extra code generates and saves Figure 1511\n",
"\n",
"# The forecasts start on 2019-02-26, as it is the 57th day of 2019, and they end\n",
"# on 2019-03-11. That's 14 days in total.\n",
"Y_pred = pd.Series(X[0, -14:, 0],\n",
" index=pd.date_range(\"2019-02-26\", \"2019-03-11\"))\n",
"\n",
"fig, ax = plt.subplots(figsize=(8, 3.5))\n",
"(rail_valid * 1e6)[\"2019-02-01\":\"2019-03-11\"].plot(\n",
" label=\"True\", marker=\".\", ax=ax)\n",
"(Y_pred * 1e6).plot(\n",
" label=\"Predictions\", grid=True, marker=\"x\", color=\"r\", ax=ax)\n",
"ax.vlines(\"2019-02-25\", 0, 1e6, color=\"k\", linestyle=\"--\", label=\"Today\")\n",
"ax.set_ylim([200_000, 800_000])\n",
"plt.legend(loc=\"center left\")\n",
"save_fig(\"forecast_ahead_plot\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's create an RNN that predicts all 14 next values at once:"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"\n",
"def split_inputs_and_targets(mulvar_series, ahead=14, target_col=1):\n",
" return mulvar_series[:, :-ahead], mulvar_series[:, -ahead:, target_col]\n",
"\n",
"ahead_train_ds = tf.keras.utils.timeseries_dataset_from_array(\n",
" mulvar_train.to_numpy(),\n",
" targets=None,\n",
" sequence_length=seq_length + 14,\n",
" batch_size=32,\n",
" shuffle=True,\n",
" seed=42\n",
").map(split_inputs_and_targets)\n",
"ahead_valid_ds = tf.keras.utils.timeseries_dataset_from_array(\n",
" mulvar_valid.to_numpy(),\n",
" targets=None,\n",
" sequence_length=seq_length + 14,\n",
" batch_size=32\n",
").map(split_inputs_and_targets)"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42)\n",
"\n",
"ahead_model = tf.keras.Sequential([\n",
" tf.keras.layers.SimpleRNN(32, input_shape=[None, 5]),\n",
" tf.keras.layers.Dense(14)\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [],
"source": [
"# extra code compiles, fits, and evaluates the model, like earlier\n",
"fit_and_evaluate(ahead_model, ahead_train_ds, ahead_valid_ds,\n",
" learning_rate=0.02)"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [],
"source": [
"X = mulvar_valid.to_numpy()[np.newaxis, :seq_length] # shape [1, 56, 5]\n",
"Y_pred = ahead_model.predict(X) # shape [1, 14]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's create an RNN that predicts the next 14 steps at each time step. That is, instead of just forecasting time steps 56 to 69 based on time steps 0 to 55, it will forecast time steps 1 to 14 at time step 0, then time steps 2 to 15 at time step 1, and so on, and finally it will forecast time steps 56 to 69 at the last time step. Notice that the model is causal: when it makes predictions at any time step, it can only see past time steps."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To prepare the datasets, we can use `to_windows()` twice, to get sequences of consecutive windows, like this:"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [],
"source": [
"my_series = tf.data.Dataset.range(7)\n",
"dataset = to_windows(to_windows(my_series, 3), 4)\n",
"list(dataset)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then we can split these elements into the desired inputs and targets:"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [],
"source": [
"dataset = dataset.map(lambda S: (S[:, 0], S[:, 1:]))\n",
"list(dataset)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's wrap this idea into a utility function. It will also take care of shuffling (optional) and batching:"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [],
"source": [
"def to_seq2seq_dataset(series, seq_length=56, ahead=14, target_col=1,\n",
" batch_size=32, shuffle=False, seed=None):\n",
" ds = to_windows(tf.data.Dataset.from_tensor_slices(series), ahead + 1)\n",
" ds = to_windows(ds, seq_length).map(lambda S: (S[:, 0], S[:, 1:, 1]))\n",
" if shuffle:\n",
" ds = ds.shuffle(8 * batch_size, seed=seed)\n",
" return ds.batch(batch_size)"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [],
"source": [
"seq2seq_train = to_seq2seq_dataset(mulvar_train, shuffle=True, seed=42)\n",
"seq2seq_valid = to_seq2seq_dataset(mulvar_valid)"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"seq2seq_model = tf.keras.Sequential([\n",
" tf.keras.layers.SimpleRNN(32, return_sequences=True, input_shape=[None, 5]),\n",
" tf.keras.layers.Dense(14)\n",
" # equivalent: tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(14))\n",
" # also equivalent: tf.keras.layers.Conv1D(14, kernel_size=1)\n",
"])"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(seq2seq_model, seq2seq_train, seq2seq_valid,\n",
" learning_rate=0.1)"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [],
"source": [
"X = mulvar_valid.to_numpy()[np.newaxis, :seq_length]\n",
"y_pred_14 = seq2seq_model.predict(X)[0, -1] # only the last time step's output"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [],
"source": [
"Y_pred_valid = seq2seq_model.predict(seq2seq_valid)\n",
"for ahead in range(14):\n",
" preds = pd.Series(Y_pred_valid[:-1, -1, ahead],\n",
" index=mulvar_valid.index[56 + ahead : -14 + ahead])\n",
" mae = (preds - mulvar_valid[\"rail\"]).abs().mean() * 1e6\n",
" print(f\"MAE for +{ahead + 1}: {mae:,.0f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Deep RNNs with Layer Norm"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [],
"source": [
"class LNSimpleRNNCell(tf.keras.layers.Layer):\n",
" def __init__(self, units, activation=\"tanh\", **kwargs):\n",
" super().__init__(**kwargs)\n",
" self.state_size = units\n",
" self.output_size = units\n",
" self.simple_rnn_cell = tf.keras.layers.SimpleRNNCell(units,\n",
" activation=None)\n",
" self.layer_norm = tf.keras.layers.LayerNormalization()\n",
" self.activation = tf.keras.activations.get(activation)\n",
"\n",
" def call(self, inputs, states):\n",
" outputs, new_states = self.simple_rnn_cell(inputs, states)\n",
" norm_outputs = self.activation(self.layer_norm(outputs))\n",
" return norm_outputs, [norm_outputs]"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"custom_ln_model = tf.keras.Sequential([\n",
" tf.keras.layers.RNN(LNSimpleRNNCell(32), return_sequences=True,\n",
" input_shape=[None, 5]),\n",
" tf.keras.layers.Dense(14)\n",
"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just training for 5 epochs to show that it works (you can increase this if you want):"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(custom_ln_model, seq2seq_train, seq2seq_valid,\n",
" learning_rate=0.1, epochs=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Extra Material Creating a Custom RNN Class"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The RNN class is not magical. In fact, it's not too hard to implement your own RNN class:"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"class MyRNN(tf.keras.layers.Layer):\n",
" def __init__(self, cell, return_sequences=False, **kwargs):\n",
" super().__init__(**kwargs)\n",
" self.cell = cell\n",
" self.return_sequences = return_sequences\n",
"\n",
" def get_initial_state(self, inputs):\n",
" try:\n",
" return self.cell.get_initial_state(inputs)\n",
" except AttributeError:\n",
" # fallback to zeros if self.cell has no get_initial_state() method\n",
" batch_size = tf.shape(inputs)[0]\n",
" return [tf.zeros([batch_size, self.cell.state_size],\n",
" dtype=inputs.dtype)]\n",
"\n",
" @tf.function\n",
" def call(self, inputs):\n",
" states = self.get_initial_state(inputs)\n",
" shape = tf.shape(inputs)\n",
" batch_size = shape[0]\n",
" n_steps = shape[1]\n",
" sequences = tf.TensorArray(\n",
" inputs.dtype, size=(n_steps if self.return_sequences else 0))\n",
" outputs = tf.zeros(shape=[batch_size, self.cell.output_size],\n",
" dtype=inputs.dtype)\n",
" for step in tf.range(n_steps):\n",
" outputs, states = self.cell(inputs[:, step], states)\n",
" if self.return_sequences:\n",
" sequences = sequences.write(step, outputs)\n",
"\n",
" if self.return_sequences:\n",
" # stack the outputs into an array of shape\n",
" # [time steps, batch size, dims], then transpose it to shape\n",
" # [batch size, time steps, dims]\n",
" return tf.transpose(sequences.stack(), [1, 0, 2])\n",
" else:\n",
" return outputs"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that `@tf.function` requires the `outputs` variable to be created before the `for` loop, which is why we initialize its value to a zero tensor, even though we don't use that value at all. Once the function is converted to a graph, this unused value will be pruned from the graph, so it doesn't impact performance. Similarly, `@tf.function` requires the `sequences` variable to be created before the `if` statement where it is used, even if `self.return_sequences` is `False`, so we create a `TensorArray` of size 0 in this case."
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42)\n",
"\n",
"custom_model = tf.keras.Sequential([\n",
" MyRNN(LNSimpleRNNCell(32), return_sequences=True, input_shape=[None, 5]),\n",
" tf.keras.layers.Dense(14)\n",
"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just training for 5 epochs to show that it works (you can increase this if you want):"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(custom_model, seq2seq_train, seq2seq_valid,\n",
" learning_rate=0.1, epochs=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# LSTMs"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"lstm_model = tf.keras.models.Sequential([\n",
" tf.keras.layers.LSTM(32, return_sequences=True, input_shape=[None, 5]),\n",
" tf.keras.layers.Dense(14)\n",
"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just training for 5 epochs to show that it works (you can increase this if you want):"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(lstm_model, seq2seq_train, seq2seq_valid,\n",
" learning_rate=0.1, epochs=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# GRUs"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"gru_model = tf.keras.Sequential([\n",
" tf.keras.layers.GRU(32, return_sequences=True, input_shape=[None, 5]),\n",
" tf.keras.layers.Dense(14)\n",
"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just training for 5 epochs to show that it works (you can increase this if you want):"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(gru_model, seq2seq_train, seq2seq_valid,\n",
" learning_rate=0.1, epochs=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using One-Dimensional Convolutional Layers to Process Sequences"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
" |-----0-----| |-----3----| |--... |-------52------|\n",
" |-----1----| |-----4----| ... | |-------53------|\n",
" |-----2----| |------5--...-51------| |-------54------|\n",
"X: 0 1 2 3 4 5 6 7 8 9 10 11 12 ... 104 105 106 107 108 109 110 111\n",
"Y: from 4 6 8 10 12 ... 106 108 110 112\n",
" to 17 19 21 23 25 ... 119 121 123 125\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"conv_rnn_model = tf.keras.Sequential([\n",
" tf.keras.layers.Conv1D(filters=32, kernel_size=4, strides=2,\n",
" activation=\"relu\", input_shape=[None, 5]),\n",
" tf.keras.layers.GRU(32, return_sequences=True),\n",
" tf.keras.layers.Dense(14)\n",
"])\n",
"\n",
"longer_train = to_seq2seq_dataset(mulvar_train, seq_length=112,\n",
" shuffle=True, seed=42)\n",
"longer_valid = to_seq2seq_dataset(mulvar_valid, seq_length=112)\n",
"downsampled_train = longer_train.map(lambda X, Y: (X, Y[:, 3::2]))\n",
"downsampled_valid = longer_valid.map(lambda X, Y: (X, Y[:, 3::2]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just training for 5 epochs to show that it works (you can increase this if you want):"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(conv_rnn_model, downsampled_train, downsampled_valid,\n",
" learning_rate=0.1, epochs=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## WaveNet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```\n",
" ⋮\n",
"C2 /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\...\n",
" \\ / \\ / \\ / \\ / \\ / \\ / \\ \n",
" / \\ / \\ / \\ \n",
"C1 /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /\\ /...\\\n",
"X: 0 1 2 3 4 5 6 7 8 9 10 11 12 ... 111\n",
"Y: 1 2 3 4 5 6 7 8 9 10 11 12 13 ... 112\n",
" /14 15 16 17 18 19 20 21 22 23 24 25 26 ... 125\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42) # extra code ensures reproducibility\n",
"wavenet_model = tf.keras.Sequential()\n",
"wavenet_model.add(tf.keras.layers.InputLayer(input_shape=[None, 5]))\n",
"for rate in (1, 2, 4, 8) * 2:\n",
" wavenet_model.add(tf.keras.layers.Conv1D(\n",
" filters=32, kernel_size=2, padding=\"causal\", activation=\"relu\",\n",
" dilation_rate=rate))\n",
"wavenet_model.add(tf.keras.layers.Conv1D(filters=14, kernel_size=1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just training for 5 epochs to show that it works (you can increase this if you want):"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(wavenet_model, longer_train, longer_valid,\n",
" learning_rate=0.1, epochs=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Extra Material Wavenet Implementation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is the original WaveNet defined in the paper: it uses Gated Activation Units instead of ReLU and parametrized skip connections, plus it pads with zeros on the left to avoid getting shorter and shorter sequences:"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [],
"source": [
"class GatedActivationUnit(tf.keras.layers.Layer):\n",
" def __init__(self, activation=\"tanh\", **kwargs):\n",
" super().__init__(**kwargs)\n",
" self.activation = tf.keras.activations.get(activation)\n",
"\n",
" def call(self, inputs):\n",
" n_filters = inputs.shape[-1] // 2\n",
" linear_output = self.activation(inputs[..., :n_filters])\n",
" gate = tf.keras.activations.sigmoid(inputs[..., n_filters:])\n",
" return self.activation(linear_output) * gate"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [],
"source": [
"def wavenet_residual_block(inputs, n_filters, dilation_rate):\n",
" z = tf.keras.layers.Conv1D(2 * n_filters, kernel_size=2, padding=\"causal\",\n",
" dilation_rate=dilation_rate)(inputs)\n",
" z = GatedActivationUnit()(z)\n",
" z = tf.keras.layers.Conv1D(n_filters, kernel_size=1)(z)\n",
" return tf.keras.layers.Add()([z, inputs]), z"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [],
"source": [
"tf.random.set_seed(42)\n",
"\n",
"n_layers_per_block = 3 # 10 in the paper\n",
"n_blocks = 1 # 3 in the paper\n",
"n_filters = 32 # 128 in the paper\n",
"n_outputs = 14 # 256 in the paper\n",
"\n",
"inputs = tf.keras.layers.Input(shape=[None, 5])\n",
"z = tf.keras.layers.Conv1D(n_filters, kernel_size=2, padding=\"causal\")(inputs)\n",
"skip_to_last = []\n",
"for dilation_rate in [2**i for i in range(n_layers_per_block)] * n_blocks:\n",
" z, skip = wavenet_residual_block(z, n_filters, dilation_rate)\n",
" skip_to_last.append(skip)\n",
"\n",
"z = tf.keras.activations.relu(tf.keras.layers.Add()(skip_to_last))\n",
"z = tf.keras.layers.Conv1D(n_filters, kernel_size=1, activation=\"relu\")(z)\n",
"Y_preds = tf.keras.layers.Conv1D(n_outputs, kernel_size=1)(z)\n",
"\n",
"full_wavenet_model = tf.keras.Model(inputs=[inputs], outputs=[Y_preds])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just training for 5 epochs to show that it works (you can increase this if you want):"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [],
"source": [
"fit_and_evaluate(full_wavenet_model, longer_train, longer_valid,\n",
" learning_rate=0.1, epochs=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this chapter we explored the fundamentals of RNNs and used them to process sequences (namely, time series). In the process we also looked at other ways to process sequences, including CNNs. In the next chapter we will use RNNs for Natural Language Processing, and we will learn more about RNNs (bidirectional RNNs, stateful vs stateless RNNs, EncoderDecoders, and Attention-augmented Encoder-Decoders). We will also look at the Transformer, an Attention-only architecture."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercise solutions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. to 8."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. Here are a few RNN applications:\n",
" * For a sequence-to-sequence RNN: predicting the weather (or any other time series), machine translation (using an EncoderDecoder architecture), video captioning, speech to text, music generation (or other sequence generation), identifying the chords of a song\n",
" * For a sequence-to-vector RNN: classifying music samples by music genre, analyzing the sentiment of a book review, predicting what word an aphasic patient is thinking of based on readings from brain implants, predicting the probability that a user will want to watch a movie based on their watch history (this is one of many possible implementations of _collaborative filtering_ for a recommender system)\n",
" * For a vector-to-sequence RNN: image captioning, creating a music playlist based on an embedding of the current artist, generating a melody based on a set of parameters, locating pedestrians in a picture (e.g., a video frame from a self-driving car's camera)\n",
"2. An RNN layer must have three-dimensional inputs: the first dimension is the batch dimension (its size is the batch size), the second dimension represents the time (its size is the number of time steps), and the third dimension holds the inputs at each time step (its size is the number of input features per time step). For example, if you want to process a batch containing 5 time series of 10 time steps each, with 2 values per time step (e.g., the temperature and the wind speed), the shape will be [5, 10, 2]. The outputs are also three-dimensional, with the same first two dimensions, but the last dimension is equal to the number of neurons. For example, if an RNN layer with 32 neurons processes the batch we just discussed, the output will have a shape of [5, 10, 32].\n",
"3. To build a deep sequence-to-sequence RNN using Keras, you must set `return_sequences=True` for all RNN layers. To build a sequence-to-vector RNN, you must set `return_sequences=True` for all RNN layers except for the top RNN layer, which must have `return_sequences=False` (or do not set this argument at all, since `False` is the default).\n",
"4. If you have a daily univariate time series, and you want to forecast the next seven days, the simplest RNN architecture you can use is a stack of RNN layers (all with `return_sequences=True` except for the top RNN layer), using seven neurons in the output RNN layer. You can then train this model using random windows from the time series (e.g., sequences of 30 consecutive days as the inputs, and a vector containing the values of the next 7 days as the target). This is a sequence-to-vector RNN. Alternatively, you could set `return_sequences=True` for all RNN layers to create a sequence-to-sequence RNN. You can train this model using random windows from the time series, with sequences of the same length as the inputs as the targets. Each target sequence should have seven values per time step (e.g., for time step _t_, the target should be a vector containing the values at time steps _t_ + 1 to _t_ + 7).\n",
"5. The two main difficulties when training RNNs are unstable gradients (exploding or vanishing) and a very limited short-term memory. These problems both get worse when dealing with long sequences. To alleviate the unstable gradients problem, you can use a smaller learning rate, use a saturating activation function such as the hyperbolic tangent (which is the default), and possibly use gradient clipping, Layer Normalization, or dropout at each time step. To tackle the limited short-term memory problem, you can use `LSTM` or `GRU` layers (this also helps with the unstable gradients problem).\n",
"6. An LSTM cell's architecture looks complicated, but it's actually not too hard if you understand the underlying logic. The cell has a short-term state vector and a long-term state vector. At each time step, the inputs and the previous short-term state are fed to a simple RNN cell and three gates: the forget gate decides what to remove from the long-term state, the input gate decides which part of the output of the simple RNN cell should be added to the long-term state, and the output gate decides which part of the long-term state should be output at this time step (after going through the tanh activation function). The new short-term state is equal to the output of the cell. See Figure 1512.\n",
"7. An RNN layer is fundamentally sequential: in order to compute the outputs at time step _t_, it has to first compute the outputs at all earlier time steps. This makes it impossible to parallelize. On the other hand, a 1D convolutional layer lends itself well to parallelization since it does not hold a state between time steps. In other words, it has no memory: the output at any time step can be computed based only on a small window of values from the inputs without having to know all the past values. Moreover, since a 1D convolutional layer is not recurrent, it suffers less from unstable gradients. One or more 1D convolutional layers can be useful in an RNN to efficiently preprocess the inputs, for example to reduce their temporal resolution (downsampling) and thereby help the RNN layers detect long-term patterns. In fact, it is possible to use only convolutional layers, for example by building a WaveNet architecture.\n",
"8. To classify videos based on their visual content, one possible architecture could be to take (say) one frame per second, then run every frame through the same convolutional neural network (e.g., a pretrained Xception model, possibly frozen if your dataset is not large), feed the sequence of outputs from the CNN to a sequence-to-vector RNN, and finally run its output through a softmax layer, giving you all the class probabilities. For training you would use cross entropy as the cost function. If you wanted to use the audio for classification as well, you could use a stack of strided 1D convolutional layers to reduce the temporal resolution from thousands of audio frames per second to just one per second (to match the number of images per second), and concatenate the output sequence to the inputs of the sequence-to-vector RNN (along the last dimension)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 9. Tackling the SketchRNN Dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"_Exercise: Train a classification model for the SketchRNN dataset, available in TensorFlow Datasets._"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The dataset is not available in TFDS yet, the [pull request](https://github.com/tensorflow/datasets/pull/361) is still work in progress. Luckily, the data is conveniently available as TFRecords, so let's download it (it might take a while, as it's about 1 GB large, with 3,450,000 training sketches and 345,000 test sketches):"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [],
"source": [
"DOWNLOAD_ROOT = \"http://download.tensorflow.org/data/\"\n",
"FILENAME = \"quickdraw_tutorial_dataset_v1.tar.gz\"\n",
"filepath = tf.keras.utils.get_file(FILENAME,\n",
" DOWNLOAD_ROOT + FILENAME,\n",
" cache_subdir=\"datasets/quickdraw\",\n",
" extract=True)"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [],
"source": [
"quickdraw_dir = Path(filepath).parent\n",
"train_files = sorted(\n",
" [str(path) for path in quickdraw_dir.glob(\"training.tfrecord-*\")]\n",
")\n",
"eval_files = sorted(\n",
" [str(path) for path in quickdraw_dir.glob(\"eval.tfrecord-*\")]\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {},
"outputs": [],
"source": [
"train_files"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {},
"outputs": [],
"source": [
"eval_files"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {},
"outputs": [],
"source": [
"with open(quickdraw_dir / \"eval.tfrecord.classes\") as test_classes_file:\n",
" test_classes = test_classes_file.readlines()\n",
" \n",
"with open(quickdraw_dir / \"training.tfrecord.classes\") as train_classes_file:\n",
" train_classes = train_classes_file.readlines()"
]
},
{
"cell_type": "code",
"execution_count": 85,
"metadata": {},
"outputs": [],
"source": [
"assert train_classes == test_classes\n",
"class_names = [name.strip().lower() for name in train_classes]"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {},
"outputs": [],
"source": [
"sorted(class_names)"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {},
"outputs": [],
"source": [
"def parse(data_batch):\n",
" feature_descriptions = {\n",
" \"ink\": tf.io.VarLenFeature(dtype=tf.float32),\n",
" \"shape\": tf.io.FixedLenFeature([2], dtype=tf.int64),\n",
" \"class_index\": tf.io.FixedLenFeature([1], dtype=tf.int64)\n",
" }\n",
" examples = tf.io.parse_example(data_batch, feature_descriptions)\n",
" flat_sketches = tf.sparse.to_dense(examples[\"ink\"])\n",
" sketches = tf.reshape(flat_sketches, shape=[tf.size(data_batch), -1, 3])\n",
" lengths = examples[\"shape\"][:, 0]\n",
" labels = examples[\"class_index\"][:, 0]\n",
" return sketches, lengths, labels"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [],
"source": [
"def quickdraw_dataset(filepaths, batch_size=32, shuffle_buffer_size=None,\n",
" n_parse_threads=5, n_read_threads=5, cache=False):\n",
" dataset = tf.data.TFRecordDataset(filepaths,\n",
" num_parallel_reads=n_read_threads)\n",
" if cache:\n",
" dataset = dataset.cache()\n",
" if shuffle_buffer_size:\n",
" dataset = dataset.shuffle(shuffle_buffer_size)\n",
" dataset = dataset.batch(batch_size)\n",
" dataset = dataset.map(parse, num_parallel_calls=n_parse_threads)\n",
" return dataset.prefetch(1)"
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {},
"outputs": [],
"source": [
"train_set = quickdraw_dataset(train_files, shuffle_buffer_size=10000)\n",
"valid_set = quickdraw_dataset(eval_files[:5])\n",
"test_set = quickdraw_dataset(eval_files[5:])"
]
},
{
"cell_type": "code",
"execution_count": 90,
"metadata": {},
"outputs": [],
"source": [
"for sketches, lengths, labels in train_set.take(1):\n",
" print(\"sketches =\", sketches)\n",
" print(\"lengths =\", lengths)\n",
" print(\"labels =\", labels)"
]
},
{
"cell_type": "code",
"execution_count": 91,
"metadata": {},
"outputs": [],
"source": [
"def draw_sketch(sketch, label=None):\n",
" origin = np.array([[0., 0., 0.]])\n",
" sketch = np.r_[origin, sketch]\n",
" stroke_end_indices = np.argwhere(sketch[:, -1]==1.)[:, 0]\n",
" coordinates = sketch[:, :2].cumsum(axis=0)\n",
" strokes = np.split(coordinates, stroke_end_indices + 1)\n",
" title = class_names[label.numpy()] if label is not None else \"Try to guess\"\n",
" plt.title(title)\n",
" plt.plot(coordinates[:, 0], -coordinates[:, 1], \"y:\")\n",
" for stroke in strokes:\n",
" plt.plot(stroke[:, 0], -stroke[:, 1], \".-\")\n",
" plt.axis(\"off\")\n",
"\n",
"def draw_sketches(sketches, lengths, labels):\n",
" n_sketches = len(sketches)\n",
" n_cols = 4\n",
" n_rows = (n_sketches - 1) // n_cols + 1\n",
" plt.figure(figsize=(n_cols * 3, n_rows * 3.5))\n",
" for index, sketch, length, label in zip(range(n_sketches), sketches, lengths, labels):\n",
" plt.subplot(n_rows, n_cols, index + 1)\n",
" draw_sketch(sketch[:length], label)\n",
" plt.show()\n",
"\n",
"for sketches, lengths, labels in train_set.take(1):\n",
" draw_sketches(sketches, lengths, labels)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Most sketches are composed of less than 100 points:"
]
},
{
"cell_type": "code",
"execution_count": 92,
"metadata": {},
"outputs": [],
"source": [
"lengths = np.concatenate([lengths for _, lengths, _ in train_set.take(1000)])\n",
"plt.hist(lengths, bins=150, density=True)\n",
"plt.axis([0, 200, 0, 0.03])\n",
"plt.xlabel(\"length\")\n",
"plt.ylabel(\"density\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {},
"outputs": [],
"source": [
"def crop_long_sketches(dataset, max_length=100):\n",
" return dataset.map(lambda inks, lengths, labels: (inks[:, :max_length], labels))\n",
"\n",
"cropped_train_set = crop_long_sketches(train_set)\n",
"cropped_valid_set = crop_long_sketches(valid_set)\n",
"cropped_test_set = crop_long_sketches(test_set)"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {},
"outputs": [],
"source": [
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Conv1D(32, kernel_size=5, strides=2, activation=\"relu\"),\n",
" tf.keras.layers.BatchNormalization(),\n",
" tf.keras.layers.Conv1D(64, kernel_size=5, strides=2, activation=\"relu\"),\n",
" tf.keras.layers.BatchNormalization(),\n",
" tf.keras.layers.Conv1D(128, kernel_size=3, strides=2, activation=\"relu\"),\n",
" tf.keras.layers.BatchNormalization(),\n",
" tf.keras.layers.LSTM(128, return_sequences=True),\n",
" tf.keras.layers.LSTM(128),\n",
" tf.keras.layers.Dense(len(class_names), activation=\"softmax\")\n",
"])\n",
"optimizer = tf.keras.optimizers.SGD(learning_rate=1e-2, clipnorm=1.)\n",
"model.compile(loss=\"sparse_categorical_crossentropy\",\n",
" optimizer=optimizer,\n",
" metrics=[\"accuracy\", \"sparse_top_k_categorical_accuracy\"])\n",
"history = model.fit(cropped_train_set, epochs=2,\n",
" validation_data=cropped_valid_set)"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {},
"outputs": [],
"source": [
"y_test = np.concatenate([labels for _, _, labels in test_set])\n",
"y_probas = model.predict(test_set)"
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata": {},
"outputs": [],
"source": [
"np.mean(tf.keras.metrics.sparse_top_k_categorical_accuracy(y_test, y_probas))"
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {},
"outputs": [],
"source": [
"n_new = 10\n",
"Y_probas = model.predict(sketches)\n",
"top_k = tf.nn.top_k(Y_probas, k=5)\n",
"for index in range(n_new):\n",
" plt.figure(figsize=(3, 3.5))\n",
" draw_sketch(sketches[index])\n",
" plt.show()\n",
" print(\"Top-5 predictions:\".format(index + 1))\n",
" for k in range(5):\n",
" class_name = class_names[top_k.indices[index, k]]\n",
" proba = 100 * top_k.values[index, k]\n",
" print(\" {}. {} {:.3f}%\".format(k + 1, class_name, proba))\n",
" print(\"Answer: {}\".format(class_names[labels[index].numpy()]))"
]
},
{
"cell_type": "code",
"execution_count": 98,
"metadata": {},
"outputs": [],
"source": [
"model.save(\"my_sketchrnn\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 10. Bach Chorales\n",
"_Exercise: Download the [Bach chorales](https://homl.info/bach) dataset and unzip it. It is composed of 382 chorales composed by Johann Sebastian Bach. Each chorale is 100 to 640 time steps long, and each time step contains 4 integers, where each integer corresponds to a note's index on a piano (except for the value 0, which means that no note is played). Train a model—recurrent, convolutional, or both—that can predict the next time step (four notes), given a sequence of time steps from a chorale. Then use this model to generate Bach-like music, one note at a time: you can do this by giving the model the start of a chorale and asking it to predict the next time step, then appending these time steps to the input sequence and asking the model for the next note, and so on. Also make sure to check out [Google's Coconet model](https://homl.info/coconet), which was used for a nice [Google doodle about Bach](https://www.google.com/doodles/celebrating-johann-sebastian-bach)._\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 99,
"metadata": {},
"outputs": [],
"source": [
"DOWNLOAD_ROOT = (\"https://raw.githubusercontent.com/ageron/handson-ml3/main/\"\n",
" \"datasets/jsb_chorales/\")\n",
"FILENAME = \"jsb_chorales.tgz\"\n",
"filepath = tf.keras.utils.get_file(FILENAME,\n",
" DOWNLOAD_ROOT + FILENAME,\n",
" cache_subdir=\"datasets/jsb_chorales\",\n",
" extract=True)"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {},
"outputs": [],
"source": [
"jsb_chorales_dir = Path(filepath).parent\n",
"train_files = sorted(jsb_chorales_dir.glob(\"train/chorale_*.csv\"))\n",
"valid_files = sorted(jsb_chorales_dir.glob(\"valid/chorale_*.csv\"))\n",
"test_files = sorted(jsb_chorales_dir.glob(\"test/chorale_*.csv\"))"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"def load_chorales(filepaths):\n",
" return [pd.read_csv(filepath).values.tolist() for filepath in filepaths]\n",
"\n",
"train_chorales = load_chorales(train_files)\n",
"valid_chorales = load_chorales(valid_files)\n",
"test_chorales = load_chorales(test_files)"
]
},
{
"cell_type": "code",
"execution_count": 102,
"metadata": {},
"outputs": [],
"source": [
"train_chorales[0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notes range from 36 (C1 = C on octave 1) to 81 (A5 = A on octave 5), plus 0 for silence:"
]
},
{
"cell_type": "code",
"execution_count": 103,
"metadata": {},
"outputs": [],
"source": [
"notes = set()\n",
"for chorales in (train_chorales, valid_chorales, test_chorales):\n",
" for chorale in chorales:\n",
" for chord in chorale:\n",
" notes |= set(chord)\n",
"\n",
"n_notes = len(notes)\n",
"min_note = min(notes - {0})\n",
"max_note = max(notes)\n",
"\n",
"assert min_note == 36\n",
"assert max_note == 81"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's write a few functions to listen to these chorales (you don't need to understand the details here, and in fact there are certainly simpler ways to do this, for example using MIDI players, but I just wanted to have a bit of fun writing a synthesizer):"
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {},
"outputs": [],
"source": [
"from IPython.display import Audio\n",
"\n",
"def notes_to_frequencies(notes):\n",
" # Frequency doubles when you go up one octave; there are 12 semi-tones\n",
" # per octave; Note A on octave 4 is 440 Hz, and it is note number 69.\n",
" return 2 ** ((np.array(notes) - 69) / 12) * 440\n",
"\n",
"def frequencies_to_samples(frequencies, tempo, sample_rate):\n",
" note_duration = 60 / tempo # the tempo is measured in beats per minutes\n",
" # To reduce click sound at every beat, we round the frequencies to try to\n",
" # get the samples close to zero at the end of each note.\n",
" frequencies = (note_duration * frequencies).round() / note_duration\n",
" n_samples = int(note_duration * sample_rate)\n",
" time = np.linspace(0, note_duration, n_samples)\n",
" sine_waves = np.sin(2 * np.pi * frequencies.reshape(-1, 1) * time)\n",
" # Removing all notes with frequencies ≤ 9 Hz (includes note 0 = silence)\n",
" sine_waves *= (frequencies > 9.).reshape(-1, 1)\n",
" return sine_waves.reshape(-1)\n",
"\n",
"def chords_to_samples(chords, tempo, sample_rate):\n",
" freqs = notes_to_frequencies(chords)\n",
" freqs = np.r_[freqs, freqs[-1:]] # make last note a bit longer\n",
" merged = np.mean([frequencies_to_samples(melody, tempo, sample_rate)\n",
" for melody in freqs.T], axis=0)\n",
" n_fade_out_samples = sample_rate * 60 // tempo # fade out last note\n",
" fade_out = np.linspace(1., 0., n_fade_out_samples)**2\n",
" merged[-n_fade_out_samples:] *= fade_out\n",
" return merged\n",
"\n",
"def play_chords(chords, tempo=160, amplitude=0.1, sample_rate=44100, filepath=None):\n",
" samples = amplitude * chords_to_samples(chords, tempo, sample_rate)\n",
" if filepath:\n",
" from scipy.io import wavfile\n",
" samples = (2**15 * samples).astype(np.int16)\n",
" wavfile.write(filepath, sample_rate, samples)\n",
" return display(Audio(filepath))\n",
" else:\n",
" return display(Audio(samples, rate=sample_rate))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's listen to a few chorales:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for index in range(3):\n",
" play_chords(train_chorales[index])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Divine! :)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In order to be able to generate new chorales, we want to train a model that can predict the next chord given all the previous chords. If we naively try to predict the next chord in one shot, predicting all 4 notes at once, we run the risk of getting notes that don't go very well together (believe me, I tried). It's much better and simpler to predict one note at a time. So we will need to preprocess every chorale, turning each chord into an arpegio (i.e., a sequence of notes rather than notes played simultaneuously). So each chorale will be a long sequence of notes (rather than chords), and we can just train a model that can predict the next note given all the previous notes. We will use a sequence-to-sequence approach, where we feed a window to the neural net, and it tries to predict that same window shifted one time step into the future.\n",
"\n",
"We will also shift the values so that they range from 0 to 46, where 0 represents silence, and values 1 to 46 represent notes 36 (C1) to 81 (A5).\n",
"\n",
"And we will train the model on windows of 128 notes (i.e., 32 chords).\n",
"\n",
"Since the dataset fits in memory, we could preprocess the chorales in RAM using any Python code we like, but I will demonstrate here how to do all the preprocessing using tf.data (there will be more details about creating windows using tf.data in the next chapter)."
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {},
"outputs": [],
"source": [
"def create_target(batch):\n",
" X = batch[:, :-1]\n",
" Y = batch[:, 1:] # predict next note in each arpegio, at each step\n",
" return X, Y\n",
"\n",
"def preprocess(window):\n",
" window = tf.where(window == 0, window, window - min_note + 1) # shift values\n",
" return tf.reshape(window, [-1]) # convert to arpegio\n",
"\n",
"def bach_dataset(chorales, batch_size=32, shuffle_buffer_size=None,\n",
" window_size=32, window_shift=16, cache=True):\n",
" def batch_window(window):\n",
" return window.batch(window_size + 1)\n",
"\n",
" def to_windows(chorale):\n",
" dataset = tf.data.Dataset.from_tensor_slices(chorale)\n",
" dataset = dataset.window(window_size + 1, window_shift, drop_remainder=True)\n",
" return dataset.flat_map(batch_window)\n",
"\n",
" chorales = tf.ragged.constant(chorales, ragged_rank=1)\n",
" dataset = tf.data.Dataset.from_tensor_slices(chorales)\n",
" dataset = dataset.flat_map(to_windows).map(preprocess)\n",
" if cache:\n",
" dataset = dataset.cache()\n",
" if shuffle_buffer_size:\n",
" dataset = dataset.shuffle(shuffle_buffer_size)\n",
" dataset = dataset.batch(batch_size)\n",
" dataset = dataset.map(create_target)\n",
" return dataset.prefetch(1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's create the training set, the validation set and the test set:"
]
},
{
"cell_type": "code",
"execution_count": 107,
"metadata": {},
"outputs": [],
"source": [
"train_set = bach_dataset(train_chorales, shuffle_buffer_size=1000)\n",
"valid_set = bach_dataset(valid_chorales)\n",
"test_set = bach_dataset(test_chorales)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's create the model:\n",
"\n",
"* We could feed the note values directly to the model, as floats, but this would probably not give good results. Indeed, the relationships between notes are not that simple: for example, if you replace a C3 with a C4, the melody will still sound fine, even though these notes are 12 semi-tones apart (i.e., one octave). Conversely, if you replace a C3 with a C\\#3, it's very likely that the chord will sound horrible, despite these notes being just next to each other. So we will use an `Embedding` layer to convert each note to a small vector representation (see Chapter 16 for more details on embeddings). We will use 5-dimensional embeddings, so the output of this first layer will have a shape of `[batch_size, window_size, 5]`.\n",
"* We will then feed this data to a small WaveNet-like neural network, composed of a stack of 4 `Conv1D` layers with doubling dilation rates. We will intersperse these layers with `BatchNormalization` layers for faster better convergence.\n",
"* Then one `LSTM` layer to try to capture long-term patterns.\n",
"* And finally a `Dense` layer to produce the final note probabilities. It will predict one probability for each chorale in the batch, for each time step, and for each possible note (including silence). So the output shape will be `[batch_size, window_size, 47]`."
]
},
{
"cell_type": "code",
"execution_count": 108,
"metadata": {},
"outputs": [],
"source": [
"n_embedding_dims = 5\n",
"\n",
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Embedding(input_dim=n_notes, output_dim=n_embedding_dims,\n",
" input_shape=[None]),\n",
" tf.keras.layers.Conv1D(32, kernel_size=2, padding=\"causal\", activation=\"relu\"),\n",
" tf.keras.layers.BatchNormalization(),\n",
" tf.keras.layers.Conv1D(48, kernel_size=2, padding=\"causal\", activation=\"relu\", dilation_rate=2),\n",
" tf.keras.layers.BatchNormalization(),\n",
" tf.keras.layers.Conv1D(64, kernel_size=2, padding=\"causal\", activation=\"relu\", dilation_rate=4),\n",
" tf.keras.layers.BatchNormalization(),\n",
" tf.keras.layers.Conv1D(96, kernel_size=2, padding=\"causal\", activation=\"relu\", dilation_rate=8),\n",
" tf.keras.layers.BatchNormalization(),\n",
" tf.keras.layers.LSTM(256, return_sequences=True),\n",
" tf.keras.layers.Dense(n_notes, activation=\"softmax\")\n",
"])\n",
"\n",
"model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we're ready to compile and train the model!"
]
},
{
"cell_type": "code",
"execution_count": 109,
"metadata": {},
"outputs": [],
"source": [
"optimizer = tf.keras.optimizers.Nadam(learning_rate=1e-3)\n",
"model.compile(loss=\"sparse_categorical_crossentropy\", optimizer=optimizer,\n",
" metrics=[\"accuracy\"])\n",
"model.fit(train_set, epochs=20, validation_data=valid_set)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I have not done much hyperparameter search, so feel free to iterate on this model now and try to optimize it. For example, you could try removing the `LSTM` layer and replacing it with `Conv1D` layers. You could also play with the number of layers, the learning rate, the optimizer, and so on."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once you're satisfied with the performance of the model on the validation set, you can save it and evaluate it one last time on the test set:"
]
},
{
"cell_type": "code",
"execution_count": 110,
"metadata": {},
"outputs": [],
"source": [
"model.save(\"my_bach_model.h5\")\n",
"model.evaluate(test_set)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** There's no real need for a test set in this exercise, since we will perform the final evaluation by just listening to the music produced by the model. So if you want, you can add the test set to the train set, and train the model again, hopefully getting a slightly better model."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's write a function that will generate a new chorale. We will give it a few seed chords, it will convert them to arpegios (the format expected by the model), and use the model to predict the next note, then the next, and so on. In the end, it will group the notes 4 by 4 to create chords again, and return the resulting chorale."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Warning**: `model.predict_classes(X)` is deprecated. It is replaced with `model.predict(X).argmax(axis=-1)`."
]
},
{
"cell_type": "code",
"execution_count": 111,
"metadata": {},
"outputs": [],
"source": [
"def generate_chorale(model, seed_chords, length):\n",
" arpegio = preprocess(tf.constant(seed_chords, dtype=tf.int64))\n",
" arpegio = tf.reshape(arpegio, [1, -1])\n",
" for chord in range(length):\n",
" for note in range(4):\n",
" #next_note = model.predict_classes(arpegio)[:1, -1:]\n",
" next_note = model.predict(arpegio).argmax(axis=-1)[:1, -1:]\n",
" arpegio = tf.concat([arpegio, next_note], axis=1)\n",
" arpegio = tf.where(arpegio == 0, arpegio, arpegio + min_note - 1)\n",
" return tf.reshape(arpegio, shape=[-1, 4])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To test this function, we need some seed chords. Let's use the first 8 chords of one of the test chorales (it's actually just 2 different chords, each played 4 times):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"seed_chords = test_chorales[2][:8]\n",
"play_chords(seed_chords, amplitude=0.2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are ready to generate our first chorale! Let's ask the function to generate 56 more chords, for a total of 64 chords, i.e., 16 bars (assuming 4 chords per bar, i.e., a 4/4 signature):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"new_chorale = generate_chorale(model, seed_chords, 56)\n",
"play_chords(new_chorale)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This approach has one major flaw: it is often too conservative. Indeed, the model will not take any risk, it will always choose the note with the highest score, and since repeating the previous note generally sounds good enough, it's the least risky option, so the algorithm will tend to make notes last longer and longer. Pretty boring. Plus, if you run the model multiple times, it will always generate the same melody.\n",
"\n",
"So let's spice things up a bit! Instead of always picking the note with the highest score, we will pick the next note randomly, according to the predicted probabilities. For example, if the model predicts a C3 with 75% probability, and a G3 with a 25% probability, then we will pick one of these two notes randomly, with these probabilities. We will also add a `temperature` parameter that will control how \"hot\" (i.e., daring) we want the system to feel. A high temperature will bring the predicted probabilities closer together, reducing the probability of the likely notes and increasing the probability of the unlikely ones."
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {},
"outputs": [],
"source": [
"def generate_chorale_v2(model, seed_chords, length, temperature=1):\n",
" arpegio = preprocess(tf.constant(seed_chords, dtype=tf.int64))\n",
" arpegio = tf.reshape(arpegio, [1, -1])\n",
" for chord in range(length):\n",
" for note in range(4):\n",
" next_note_probas = model.predict(arpegio)[0, -1:]\n",
" rescaled_logits = tf.math.log(next_note_probas) / temperature\n",
" next_note = tf.random.categorical(rescaled_logits, num_samples=1)\n",
" arpegio = tf.concat([arpegio, next_note], axis=1)\n",
" arpegio = tf.where(arpegio == 0, arpegio, arpegio + min_note - 1)\n",
" return tf.reshape(arpegio, shape=[-1, 4])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's generate 3 chorales using this new function: one cold, one medium, and one hot (feel free to experiment with other seeds, lengths and temperatures). The code saves each chorale to a separate file. You can run these cells over an over again until you generate a masterpiece!\n",
"\n",
"**Please share your most beautiful generated chorale with me on Twitter @aureliengeron, I would really appreciate it! :))**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"new_chorale_v2_cold = generate_chorale_v2(model, seed_chords, 56, temperature=0.8)\n",
"play_chords(new_chorale_v2_cold, filepath=\"bach_cold.wav\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"new_chorale_v2_medium = generate_chorale_v2(model, seed_chords, 56, temperature=1.0)\n",
"play_chords(new_chorale_v2_medium, filepath=\"bach_medium.wav\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"new_chorale_v2_hot = generate_chorale_v2(model, seed_chords, 56, temperature=1.5)\n",
"play_chords(new_chorale_v2_hot, filepath=\"bach_hot.wav\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lastly, you can try a fun social experiment: send your friends a few of your favorite generated chorales, plus the real chorale, and ask them to guess which one is the real one!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"play_chords(test_chorales[2][:64], filepath=\"bach_test_4.wav\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.12"
},
"nav_menu": {},
"toc": {
"navigate_menu": true,
"number_sections": true,
"sideBar": true,
"threshold": 6,
"toc_cell": false,
"toc_section_display": "block",
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 4
}