aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/examples/udacity/3_regularization.ipynb
blob: 7c587a651232c8a623aa802c51163a9ae5b4448c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "version": "0.3.2",
      "views": {},
      "default_view": {},
      "name": "3_regularization.ipynb",
      "provenance": []
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kR-4eNdK6lYS",
        "colab_type": "text"
      },
      "source": [
        "Deep Learning\n",
        "=============\n",
        "\n",
        "Assignment 3\n",
        "------------\n",
        "\n",
        "Previously in `2_fullyconnected.ipynb`, you trained a logistic regression and a neural network model.\n",
        "\n",
        "The goal of this assignment is to explore regularization techniques."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "JLpLa8Jt7Vu4",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "cellView": "both"
      },
      "source": [
        "# These are all the modules we'll be using later. Make sure you can import them\n",
        "# before proceeding further.\n",
        "from __future__ import print_function\n",
        "import numpy as np\n",
        "import tensorflow as tf\n",
        "from six.moves import cPickle as pickle"
      ],
      "outputs": [],
      "execution_count": 0
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1HrCK6e17WzV",
        "colab_type": "text"
      },
      "source": [
        "First reload the data we generated in _notmist.ipynb_."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "y3-cj1bpmuxc",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          },
          "output_extras": [
            {
              "item_id": 1
            }
          ]
        },
        "cellView": "both",
        "executionInfo": {
          "elapsed": 11777,
          "status": "ok",
          "timestamp": 1449849322348,
          "user": {
            "color": "",
            "displayName": "",
            "isAnonymous": false,
            "isMe": true,
            "permissionId": "",
            "photoUrl": "",
            "sessionId": "0",
            "userId": ""
          },
          "user_tz": 480
        },
        "outputId": "e03576f1-ebbe-4838-c388-f1777bcc9873"
      },
      "source": [
        "pickle_file = 'notMNIST.pickle'\n",
        "\n",
        "with open(pickle_file, 'rb') as f:\n",
        "  save = pickle.load(f)\n",
        "  train_dataset = save['train_dataset']\n",
        "  train_labels = save['train_labels']\n",
        "  valid_dataset = save['valid_dataset']\n",
        "  valid_labels = save['valid_labels']\n",
        "  test_dataset = save['test_dataset']\n",
        "  test_labels = save['test_labels']\n",
        "  del save  # hint to help gc free up memory\n",
        "  print('Training set', train_dataset.shape, train_labels.shape)\n",
        "  print('Validation set', valid_dataset.shape, valid_labels.shape)\n",
        "  print('Test set', test_dataset.shape, test_labels.shape)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Training set (200000, 28, 28) (200000,)\n",
            "Validation set (10000, 28, 28) (10000,)\n",
            "Test set (18724, 28, 28) (18724,)\n"
          ],
          "name": "stdout"
        }
      ],
      "execution_count": 0
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L7aHrm6nGDMB",
        "colab_type": "text"
      },
      "source": [
        "Reformat into a shape that's more adapted to the models we're going to train:\n",
        "- data as a flat matrix,\n",
        "- labels as float 1-hot encodings."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "IRSyYiIIGIzS",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          },
          "output_extras": [
            {
              "item_id": 1
            }
          ]
        },
        "cellView": "both",
        "executionInfo": {
          "elapsed": 11728,
          "status": "ok",
          "timestamp": 1449849322356,
          "user": {
            "color": "",
            "displayName": "",
            "isAnonymous": false,
            "isMe": true,
            "permissionId": "",
            "photoUrl": "",
            "sessionId": "0",
            "userId": ""
          },
          "user_tz": 480
        },
        "outputId": "3f8996ee-3574-4f44-c953-5c8a04636582"
      },
      "source": [
        "image_size = 28\n",
        "num_labels = 10\n",
        "\n",
        "def reformat(dataset, labels):\n",
        "  dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)\n",
        "  # Map 2 to [0.0, 1.0, 0.0 ...], 3 to [0.0, 0.0, 1.0 ...]\n",
        "  labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n",
        "  return dataset, labels\n",
        "train_dataset, train_labels = reformat(train_dataset, train_labels)\n",
        "valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)\n",
        "test_dataset, test_labels = reformat(test_dataset, test_labels)\n",
        "print('Training set', train_dataset.shape, train_labels.shape)\n",
        "print('Validation set', valid_dataset.shape, valid_labels.shape)\n",
        "print('Test set', test_dataset.shape, test_labels.shape)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Training set (200000, 784) (200000, 10)\n",
            "Validation set (10000, 784) (10000, 10)\n",
            "Test set (18724, 784) (18724, 10)\n"
          ],
          "name": "stdout"
        }
      ],
      "execution_count": 0
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "RajPLaL_ZW6w",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "cellView": "both"
      },
      "source": [
        "def accuracy(predictions, labels):\n",
        "  return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n",
        "          / predictions.shape[0])"
      ],
      "outputs": [],
      "execution_count": 0
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sgLbUAQ1CW-1",
        "colab_type": "text"
      },
      "source": [
        "---\n",
        "Problem 1\n",
        "---------\n",
        "\n",
        "Introduce and tune L2 regularization for both logistic and neural network models. Remember that L2 amounts to adding a penalty on the norm of the weights to the loss. In TensorFlow, you can compute the L2 loss for a tensor `t` using `nn.l2_loss(t)`. The right amount of regularization should improve your validation / test accuracy.\n",
        "\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "na8xX2yHZzNF",
        "colab_type": "text"
      },
      "source": [
        "---\n",
        "Problem 2\n",
        "---------\n",
        "Let's demonstrate an extreme case of overfitting. Restrict your training data to just a few batches. What happens?\n",
        "\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ww3SCBUdlkRc",
        "colab_type": "text"
      },
      "source": [
        "---\n",
        "Problem 3\n",
        "---------\n",
        "Introduce Dropout on the hidden layer of the neural network. Remember: Dropout should only be introduced during training, not evaluation, otherwise your evaluation results would be stochastic as well. TensorFlow provides `nn.dropout()` for that, but you have to make sure it's only inserted during training.\n",
        "\n",
        "What happens to our extreme overfitting case?\n",
        "\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-b1hTz3VWZjw",
        "colab_type": "text"
      },
      "source": [
        "---\n",
        "Problem 4\n",
        "---------\n",
        "\n",
        "Try to get the best performance you can using a multi-layer model! The best reported test accuracy using a deep network is [97.1%](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html?showComment=1391023266211#c8758720086795711595).\n",
        "\n",
        "One avenue you can explore is to add multiple layers.\n",
        "\n",
        "Another one is to use learning rate decay:\n",
        "\n",
        "    global_step = tf.Variable(0)  # count the number of steps taken.\n",
        "    learning_rate = tf.train.exponential_decay(0.5, step, ...)\n",
        "    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)\n",
        " \n",
        " ---\n"
      ]
    }
  ]
}