Format: application/octet-stream
1 {
2 "nbformat": 4,
3 "nbformat_minor": 0,
4 "metadata": {
5 "colab": {
6 "name": "S+P Week 3 Lesson 2 - RNN.ipynb",
7 "provenance": [],
8 "collapsed_sections": [],
9 "toc_visible": true
10 },
11 "kernelspec": {
12 "display_name": "Python 3",
13 "name": "python3"
14 }
15 },
16 "cells": [
17 {
18 "cell_type": "code",
19 "metadata": {
20 "id": "zX4Kg8DUTKWO"
21 },
22 "source": [
23 "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
24 "# you may not use this file except in compliance with the License.\n",
25 "# You may obtain a copy of the License at\n",
26 "#\n",
27 "# https://www.apache.org/licenses/LICENSE-2.0\n",
28 "#\n",
29 "# Unless required by applicable law or agreed to in writing, software\n",
30 "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
31 "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
32 "# See the License for the specific language governing permissions and\n",
33 "# limitations under the License."
34 ],
35 "execution_count": null,
36 "outputs": []
37 },
38 {
39 "cell_type": "markdown",
40 "metadata": {
41 "id": "view-in-github"
42 },
43 "source": [
44 "<a href=\"https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20In%20Practice/Course%204%20-%20S%2BP/S%2BP%20Week%203%20Lesson%202%20-%20RNN.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
45 ]
46 },
47 {
48 "cell_type": "code",
49 "metadata": {
50 "cellView": "both",
51 "id": "D1J15Vh_1Jih"
52 },
53 "source": [
54 "try:\n",
55 " # %tensorflow_version only exists in Colab.\n",
56 " %tensorflow_version 2.x\n",
57 "except Exception:\n",
58 " pass\n"
59 ],
60 "execution_count": null,
61 "outputs": []
62 },
63 {
64 "cell_type": "code",
65 "metadata": {
66 "id": "BOjujz601HcS"
67 },
68 "source": [
69 "import tensorflow as tf\n",
70 "import numpy as np\n",
71 "import matplotlib.pyplot as plt\n",
72 "print(tf.__version__)"
73 ],
74 "execution_count": null,
75 "outputs": []
76 },
77 {
78 "cell_type": "code",
79 "metadata": {
80 "id": "Zswl7jRtGzkk"
81 },
82 "source": [
83 "def plot_series(time, series, format=\"-\", start=0, end=None):\n",
84 " plt.plot(time[start:end], series[start:end], format)\n",
85 " plt.xlabel(\"Time\")\n",
86 " plt.ylabel(\"Value\")\n",
87 " plt.grid(True)\n",
88 "\n",
89 "def trend(time, slope=0):\n",
90 " return slope * time\n",
91 "\n",
92 "def seasonal_pattern(season_time):\n",
93 " \"\"\"Just an arbitrary pattern, you can change it if you wish\"\"\"\n",
94 " return np.where(season_time < 0.4,\n",
95 " np.cos(season_time * 2 * np.pi),\n",
96 " 1 / np.exp(3 * season_time))\n",
97 "\n",
98 "def seasonality(time, period, amplitude=1, phase=0):\n",
99 " \"\"\"Repeats the same pattern at each period\"\"\"\n",
100 " season_time = ((time + phase) % period) / period\n",
101 " return amplitude * seasonal_pattern(season_time)\n",
102 "\n",
103 "def noise(time, noise_level=1, seed=None):\n",
104 " rnd = np.random.RandomState(seed)\n",
105 " return rnd.randn(len(time)) * noise_level\n",
106 "\n",
107 "time = np.arange(4 * 365 + 1, dtype=\"float32\")\n",
108 "baseline = 10\n",
109 "series = trend(time, 0.1) \n",
110 "baseline = 10\n",
111 "amplitude = 40\n",
112 "slope = 0.05\n",
113 "noise_level = 5\n",
114 "\n",
115 "# Create the series\n",
116 "series = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)\n",
117 "# Update with noise\n",
118 "series += noise(time, noise_level, seed=42)\n",
119 "\n",
120 "split_time = 1000\n",
121 "time_train = time[:split_time]\n",
122 "x_train = series[:split_time]\n",
123 "time_valid = time[split_time:]\n",
124 "x_valid = series[split_time:]\n",
125 "\n",
126 "window_size = 20\n",
127 "batch_size = 32\n",
128 "shuffle_buffer_size = 1000"
129 ],
130 "execution_count": null,
131 "outputs": []
132 },
133 {
134 "cell_type": "code",
135 "metadata": {
136 "id": "4sTTIOCbyShY"
137 },
138 "source": [
139 "def windowed_dataset(series, window_size, batch_size, shuffle_buffer):\n",
140 " dataset = tf.data.Dataset.from_tensor_slices(series)\n",
141 " dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)\n",
142 " dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))\n",
143 " dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1]))\n",
144 " dataset = dataset.batch(batch_size).prefetch(1)\n",
145 " return dataset"
146 ],
147 "execution_count": null,
148 "outputs": []
149 },
150 {
151 "cell_type": "code",
152 "metadata": {
153 "id": "L4nblWkqg1NL"
154 },
155 "source": [
156 "tf.keras.backend.clear_session()\n",
157 "tf.random.set_seed(51)\n",
158 "np.random.seed(51)\n",
159 "\n",
160 "train_set = windowed_dataset(x_train, window_size, batch_size=128, shuffle_buffer=shuffle_buffer_size)\n",
161 "\n",
162 "model = tf.keras.models.Sequential([\n",
163 " tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),\n",
164 " input_shape=[None]),\n",
165 " tf.keras.layers.SimpleRNN(40, return_sequences=True),\n",
166 " tf.keras.layers.SimpleRNN(40),\n",
167 " tf.keras.layers.Dense(1),\n",
168 " tf.keras.layers.Lambda(lambda x: x * 100.0)\n",
169 "])\n",
170 "\n",
171 "lr_schedule = tf.keras.callbacks.LearningRateScheduler(\n",
172 " lambda epoch: 1e-8 * 10**(epoch / 20))\n",
173 "optimizer = tf.keras.optimizers.SGD(lr=1e-8, momentum=0.9)\n",
174 "model.compile(loss=tf.keras.losses.Huber(),\n",
175 " optimizer=optimizer,\n",
176 " metrics=[\"mae\"])\n",
177 "history = model.fit(train_set, epochs=100, callbacks=[lr_schedule])"
178 ],
179 "execution_count": null,
180 "outputs": []
181 },
182 {
183 "cell_type": "code",
184 "metadata": {
185 "id": "5He3pp-Hj758"
186 },
187 "source": [
188 "plt.semilogx(history.history[\"lr\"], history.history[\"loss\"])\n",
189 "plt.axis([1e-8, 1e-4, 0, 30])"
190 ],
191 "execution_count": null,
192 "outputs": []
193 },
194 {
195 "cell_type": "code",
196 "metadata": {
197 "id": "6y1KMowRkHkC"
198 },
199 "source": [
200 "tf.keras.backend.clear_session()\n",
201 "tf.random.set_seed(51)\n",
202 "np.random.seed(51)\n",
203 "\n",
204 "dataset = windowed_dataset(x_train, window_size, batch_size=128, shuffle_buffer=shuffle_buffer_size)\n",
205 "\n",
206 "model = tf.keras.models.Sequential([\n",
207 " tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),\n",
208 " input_shape=[None]),\n",
209 " tf.keras.layers.SimpleRNN(40, return_sequences=True),\n",
210 " tf.keras.layers.SimpleRNN(40),\n",
211 " tf.keras.layers.Dense(1),\n",
212 " tf.keras.layers.Lambda(lambda x: x * 100.0)\n",
213 "])\n",
214 "\n",
215 "optimizer = tf.keras.optimizers.SGD(lr=5e-5, momentum=0.9)\n",
216 "model.compile(loss=tf.keras.losses.Huber(),\n",
217 " optimizer=optimizer,\n",
218 " metrics=[\"mae\"])\n",
219 "history = model.fit(dataset,epochs=400)"
220 ],
221 "execution_count": null,
222 "outputs": []
223 },
224 {
225 "cell_type": "code",
226 "metadata": {
227 "id": "ejBynEKekaKw"
228 },
229 "source": [
230 "forecast=[]\n",
231 "for time in range(len(series) - window_size):\n",
232 " forecast.append(model.predict(series[time:time + window_size][np.newaxis]))\n",
233 "\n",
234 "forecast = forecast[split_time-window_size:]\n",
235 "results = np.array(forecast)[:, 0, 0]\n",
236 "\n",
237 "\n",
238 "plt.figure(figsize=(10, 6))\n",
239 "\n",
240 "plot_series(time_valid, x_valid)\n",
241 "plot_series(time_valid, results)"
242 ],
243 "execution_count": null,
244 "outputs": []
245 },
246 {
247 "cell_type": "code",
248 "metadata": {
249 "id": "hR2BO0Dai_ZT"
250 },
251 "source": [
252 "tf.keras.metrics.mean_absolute_error(x_valid, results).numpy()"
253 ],
254 "execution_count": null,
255 "outputs": []
256 },
257 {
258 "cell_type": "code",
259 "metadata": {
260 "id": "vXaFHOaJqE6M"
261 },
262 "source": [
263 "import matplotlib.image as mpimg\n",
264 "import matplotlib.pyplot as plt\n",
265 "\n",
266 "#-----------------------------------------------------------\n",
267 "# Retrieve a list of list results on training and test data\n",
268 "# sets for each training epoch\n",
269 "#-----------------------------------------------------------\n",
270 "mae=history.history['mae']\n",
271 "loss=history.history['loss']\n",
272 "\n",
273 "epochs=range(len(loss)) # Get number of epochs\n",
274 "\n",
275 "#------------------------------------------------\n",
276 "# Plot MAE and Loss\n",
277 "#------------------------------------------------\n",
278 "plt.plot(epochs, mae, 'r')\n",
279 "plt.plot(epochs, loss, 'b')\n",
280 "plt.title('MAE and Loss')\n",
281 "plt.xlabel(\"Epochs\")\n",
282 "plt.ylabel(\"Accuracy\")\n",
283 "plt.legend([\"MAE\", \"Loss\"])\n",
284 "\n",
285 "plt.figure()\n",
286 "\n",
287 "epochs_zoom = epochs[200:]\n",
288 "mae_zoom = mae[200:]\n",
289 "loss_zoom = loss[200:]\n",
290 "\n",
291 "#------------------------------------------------\n",
292 "# Plot Zoomed MAE and Loss\n",
293 "#------------------------------------------------\n",
294 "plt.plot(epochs_zoom, mae_zoom, 'r')\n",
295 "plt.plot(epochs_zoom, loss_zoom, 'b')\n",
296 "plt.title('MAE and Loss')\n",
297 "plt.xlabel(\"Epochs\")\n",
298 "plt.ylabel(\"Accuracy\")\n",
299 "plt.legend([\"MAE\", \"Loss\"])\n",
300 "\n",
301 "plt.figure()"
302 ],
303 "execution_count": null,
304 "outputs": []
305 }
306 ]
307 }