~dvshkn/experiment-cifar10-training-order

ref: 340456dee5116812cdeb0c907ffae1e380b80740 experiment-cifar10-training-order/cifar10_training_order.ipynb -rw-r--r-- 25.4 KiB
340456deDavid Knight initial commit 1 year, 1 month ago
                                                                                
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Experiment: CIFAR-10 Training Order\n",
    "## To what extent does training order affect image classifier performance?\n",
    "[Code is based on this PyTorch tutorial!](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The various constants below control the run mode of the experiment.\n",
    "- `ENTROPY_SORT_ENABLED`: This enables or disables entropy sorting of training data. No entropy sorting is the control case and makes this notebook equivalent to the original PyTorch tutorial.\n",
    "- `SORT_GROUPED`: If true this causes each CIFAR-10 image class to be entropy sorted independently. If false this applies entropy sorting globally over all training data. This constant is ignored if `ENTROPY_SORT_ENABLED` is false.\n",
    "- `SORT_ASCENDING`: Entropy sorting is applied in ascending order if true or descending order if false. This constant is ignored if `ENTROPY_SORT_ENABLED` is false.\n",
    "- `TRAINING_SLICE_FACTORS`: For every number (0,1] in this array a net will be trained using that fraction of the CIFAR-10 training set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Experiment Controls\n",
    "#\n",
    "\n",
    "ENTROPY_SORT_ENABLED = True\n",
    "SORT_GROUPED = True\n",
    "SORT_ASCENDING = True\n",
    "TRAINING_SLICE_FACTORS = [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]\n",
    "\n",
    "def get_file_suffix(slice_factor):\n",
    "    if ENTROPY_SORT_ENABLED:\n",
    "        grouped_str = 'grouped' if SORT_GROUPED else 'global'\n",
    "        ascending_str = 'asc' if SORT_ASCENDING else 'desc'\n",
    "        return f'entropy-{grouped_str}-{ascending_str}-{slice_factor}'\n",
    "    else:\n",
    "        return f'random-{slice_factor}'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "import torchvision\n",
    "import torchvision.transforms as transforms\n",
    "import copy\n",
    "\n",
    "class EntropySampler(torch.utils.data.Sampler):\n",
    "    def entropy(self, datum):\n",
    "        arr = datum[0].numpy()\n",
    "        # grayscale coefficients from matlab rgb2gray\n",
    "        arr = 0.2989 * arr[0,:,:] + 0.5870 * arr[1,:,:] + 0.1140 * arr[2,:,:]\n",
    "        hist = np.histogram(arr, bins=256)[0]\n",
    "        hist = hist / np.sum(hist)\n",
    "        hist = hist[hist > 0]\n",
    "        return -np.sum(hist * np.log2(hist))\n",
    "\n",
    "    def __init__(self, data_source, global_sort=False, ascending=True, slice_factor=1):\n",
    "        # some CIFAR-10 magic numbers...\n",
    "        if global_sort:\n",
    "            num_classes = 1\n",
    "            images_per_class = 50000\n",
    "        else:\n",
    "            num_classes = 10\n",
    "            images_per_class = 5000        \n",
    "        \n",
    "        entropies_by_label = {}\n",
    "        source_idx_by_label = {}\n",
    "        pointers_by_label = {}\n",
    "        sorted_idx_by_label = {}\n",
    "        sort_dir_coeff = 1 if ascending else -1\n",
    "                \n",
    "        for i in range(num_classes):\n",
    "            entropies_by_label[i] = np.zeros(images_per_class)\n",
    "            source_idx_by_label[i] = np.zeros(images_per_class)\n",
    "            pointers_by_label[i] = 0\n",
    "        \n",
    "        for i in range(len(data_source)):\n",
    "            if global_sort:\n",
    "                label = 0\n",
    "            else:\n",
    "                label = data_source[i][1]\n",
    "            idx = pointers_by_label[label]\n",
    "            entropies_by_label[label][idx] = sort_dir_coeff * self.entropy(data_source[i])\n",
    "            source_idx_by_label[label][idx] = i\n",
    "            pointers_by_label[label] += 1\n",
    "        \n",
    "        for i in range(num_classes):\n",
    "            sorted_idx_by_label[i] = np.argsort(entropies_by_label[i])\n",
    "        \n",
    "        sliced_images_per_class = int(slice_factor * images_per_class)\n",
    "        \n",
    "        self.grouped_entropy_idx = np.zeros(sliced_images_per_class * num_classes, dtype=int)\n",
    "\n",
    "        for i in range(sliced_images_per_class):\n",
    "            for j in range(num_classes):\n",
    "                sorted_idx = sorted_idx_by_label[j][i]\n",
    "                source_idx = source_idx_by_label[j][sorted_idx]\n",
    "                self.grouped_entropy_idx[i*num_classes + j] = source_idx\n",
    "    \n",
    "    def create_sliced_copy(self, relative_slice_factor=1):\n",
    "        # because the array round-robbins the categories in group sort mode\n",
    "        # we can truncate it the same way as if it was globally sorted\n",
    "        dupe = copy.copy(self)\n",
    "        end_idx = int(relative_slice_factor * len(dupe.grouped_entropy_idx))\n",
    "        dupe.grouped_entropy_idx = dupe.grouped_entropy_idx[:end_idx]\n",
    "        return dupe\n",
    "    \n",
    "    def __iter__(self):\n",
    "        return iter(self.grouped_entropy_idx)\n",
    "    \n",
    "    def __len__(self):\n",
    "        return len(self.grouped_entropy_idx)\n",
    "\n",
    "class ShuffleSampler(torch.utils.data.Sampler):\n",
    "    def __init__(self, length):\n",
    "        self.length = length\n",
    "        self.shuffled_idx = list(range(length))\n",
    "        np.random.shuffle(self.shuffled_idx)\n",
    "    \n",
    "    def __iter__(self):\n",
    "        return iter(self.shuffled_idx)\n",
    "\n",
    "    def __len__(self):\n",
    "        return self.length"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files already downloaded and verified\n",
      "Files already downloaded and verified\n"
     ]
    }
   ],
   "source": [
    "#\n",
    "# Data Prep\n",
    "#\n",
    "transform = transforms.Compose([\n",
    "    transforms.ToTensor(),\n",
    "    transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))\n",
    "])\n",
    "\n",
    "trainset = torchvision.datasets.CIFAR10(\n",
    "    root='./data',\n",
    "    train=True,\n",
    "    download=True,\n",
    "    transform=transform\n",
    ")\n",
    "\n",
    "trainloaders = []\n",
    "if ENTROPY_SORT_ENABLED:\n",
    "    base_entropy_sampler = EntropySampler(trainset, not SORT_GROUPED, SORT_ASCENDING, 1)\n",
    "    for slice_factor in TRAINING_SLICE_FACTORS:\n",
    "        entropy_sampler = base_entropy_sampler.create_sliced_copy(slice_factor)\n",
    "        trainloaders.append(torch.utils.data.DataLoader(\n",
    "            trainset,\n",
    "            batch_size=4,\n",
    "            drop_last=True,\n",
    "            num_workers=2,\n",
    "            sampler=entropy_sampler\n",
    "        ))\n",
    "else:\n",
    "    for slice_factor in TRAINING_SLICE_FACTORS:\n",
    "        trainset_length = int(slice_factor * len(trainset))\n",
    "        shuffle_sampler = ShuffleSampler(trainset_length)\n",
    "        trainloaders.append(torch.utils.data.DataLoader(\n",
    "            trainset,\n",
    "            batch_size=4,\n",
    "            drop_last=True,\n",
    "            num_workers=2,\n",
    "            sampler=shuffle_sampler\n",
    "        ))\n",
    "\n",
    "testset = torchvision.datasets.CIFAR10(\n",
    "    root='./data',\n",
    "    train=False,\n",
    "    download=True,\n",
    "    transform=transform\n",
    ")\n",
    "\n",
    "testloader = torch.utils.data.DataLoader(\n",
    "    testset,\n",
    "    batch_size=4,\n",
    "    shuffle=False,\n",
    "    num_workers=2\n",
    ")\n",
    "\n",
    "classes = (\n",
    "    'plane',\n",
    "    'car',\n",
    "    'bird',\n",
    "    'cat',\n",
    "    'deer',\n",
    "    'dog',\n",
    "    'frog',\n",
    "    'horse',\n",
    "    'ship',\n",
    "    'truck'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXAAAAB5CAYAAAAgYXpDAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjMsIGh0dHA6Ly9tYXRwbG90bGliLm9y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4BsAH4PfAq8ACQrebrADyMtdfnsdrpnYOdc6z54Zvue/07bLRNtR7DbqytO/o+/1uw/pfdMbwB3DTR/S/npTMxFUVREorOxFQURUkoOoAriqIkFB3AFUVREooO4IqiKAlFB3BFUZSEogO4oihKQtEBXFEUJaHoAK4oipJQ/h/EnZ0o0ablPgAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "plane   car  bird   cat\n"
     ]
    }
   ],
   "source": [
    "def imshow(img):\n",
    "    img = img / 2 + 0.5\n",
    "    npimg = img.numpy()\n",
    "    plt.imshow(np.transpose(npimg, (1,2,0)))\n",
    "    plt.show()\n",
    "\n",
    "dataiter = iter(trainloaders[0])\n",
    "images, labels = dataiter.next()\n",
    "\n",
    "imshow(torchvision.utils.make_grid(images))\n",
    "print(' '.join('%5s' % classes[labels[j]] for j in range(4)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `imshow` output above can be used as a quick sanity check that the entropy sorting is behaving. Entropy sorting in ascending order should cause 4 relatively low information images to be shown. Entropy sorting in descending order should cause 4 relatively high information (i.e. busy looking) images to be shown. If grouped sorting is enabled each image should be from a different class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Network Def\n",
    "#\n",
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Net, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(3, 6, 5)\n",
    "        self.pool = nn.MaxPool2d(2, 2)\n",
    "        self.conv2 = nn.Conv2d(6, 16, 5)\n",
    "        self.fc1 = nn.Linear(16 * 5 * 5, 120)\n",
    "        self.fc2 = nn.Linear(120, 84)\n",
    "        self.fc3 = nn.Linear(84, 10)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        x = self.pool(F.relu(self.conv1(x)))\n",
    "        x = self.pool(F.relu(self.conv2(x)))\n",
    "        x = x.view(-1, 16 * 5 * 5)\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = F.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Training\n",
    "#\n",
    "slice_factor_idx = 0\n",
    "loss_curves = []\n",
    "loss_labels = []\n",
    "for trainloader in trainloaders:\n",
    "    net = Net()\n",
    "    criterion = nn.CrossEntropyLoss()\n",
    "    optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n",
    "    slice_factor = TRAINING_SLICE_FACTORS[slice_factor_idx]\n",
    "    suffix = get_file_suffix(slice_factor)\n",
    "    running_period = 2000 * slice_factor\n",
    "    loss_samples = []\n",
    "    \n",
    "    print(f'START Training Time [{suffix}]')\n",
    "    \n",
    "    for epoch in range(2):\n",
    "        running_loss = 0.0\n",
    "    \n",
    "        for i, data in enumerate(trainloader, 0):\n",
    "            inputs, labels = data\n",
    "\n",
    "            optimizer.zero_grad()\n",
    "\n",
    "            outputs = net(inputs)\n",
    "            loss = criterion(outputs, labels)\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "\n",
    "            running_loss += loss.item()\n",
    "            if i % running_period == running_period-1:\n",
    "                curr_loss = running_loss / running_period\n",
    "                loss_samples.append(curr_loss)\n",
    "                print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, curr_loss))\n",
    "                running_loss = 0.0\n",
    "    \n",
    "    \n",
    "    PATH = f'./training/cifar10_training_order-{suffix}.net'\n",
    "    torch.save(net.state_dict(), PATH)\n",
    "    \n",
    "    plt.plot(np.linspace(0, 2, len(loss_samples)), loss_samples)\n",
    "    plt.xlabel('Epoch')\n",
    "    plt.ylabel('Loss')\n",
    "    plt.title(f'Training Loss ({suffix})')\n",
    "    plt.show()\n",
    "\n",
    "    loss_curves.append(loss_samples)\n",
    "    loss_labels.append(suffix)\n",
    "    \n",
    "    print(f'END [{suffix}]')\n",
    "    \n",
    "    slice_factor_idx += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Plot Losses\n",
    "#\n",
    "for i in range(len(loss_labels)):\n",
    "    suffix = loss_labels[i]\n",
    "    loss_samples = loss_curves[i]\n",
    "    plt.plot(np.linspace(0, 2, len(loss_samples)), loss_samples, label=suffix)\n",
    "    \n",
    "all_suffix = get_file_suffix('all')\n",
    "plt.xlabel('Epoch')\n",
    "plt.ylabel('Loss')\n",
    "plt.ylim(1, 2.5)\n",
    "plt.title(f'Training Losses')\n",
    "plt.legend(bbox_to_anchor=(1.52, 1.0))\n",
    "plt.savefig(f'./plots/cifar10_training_order_losses-{all_suffix}.png', bbox_inches='tight', dpi=300)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Test Time\n",
    "#\n",
    "dataiter = iter(testloader)\n",
    "images, labels = dataiter.next()\n",
    "\n",
    "imshow(torchvision.utils.make_grid(images))\n",
    "print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))\n",
    "\n",
    "accuracies = []\n",
    "\n",
    "for slice_factor in TRAINING_SLICE_FACTORS:\n",
    "    suffix = get_file_suffix(slice_factor)\n",
    "    print(f'START Test Time [{suffix}]')\n",
    "    \n",
    "    net = Net()\n",
    "    net_path = f'./training/cifar10_training_order-{suffix}.net'\n",
    "    net.load_state_dict(torch.load(net_path))\n",
    "\n",
    "    outputs = net(images)\n",
    "\n",
    "    correct = 0\n",
    "    total = 0\n",
    "    with torch.no_grad():\n",
    "        for data in testloader:\n",
    "            images, labels = data\n",
    "            outputs = net(images)\n",
    "            _, predicted = torch.max(outputs.data, 1)\n",
    "            total += labels.size(0)\n",
    "            correct += (predicted == labels).sum().item()\n",
    "\n",
    "    accuracy = 100 * correct / total\n",
    "    print('Accuracy of the network on the 10000 test images: %d %%' % accuracy)\n",
    "    accuracies.append(accuracy)\n",
    "\n",
    "    class_correct = list(0. for i in range(10))\n",
    "    class_total = list(0. for i in range(10))\n",
    "    with torch.no_grad():\n",
    "        for data in testloader:\n",
    "            images, labels = data\n",
    "            outputs = net(images)\n",
    "            _, predicted = torch.max(outputs, 1)\n",
    "            c = (predicted == labels).squeeze()\n",
    "            for i in range(4):\n",
    "                label = labels[i]\n",
    "                class_correct[label] += c[i].item()\n",
    "                class_total[label] += 1\n",
    "\n",
    "    for i in range(10):\n",
    "        print('Accuracy of %5s : %2d %%' % (classes[i], 100 * class_correct[i] / class_total[i]))\n",
    "        \n",
    "    print(f'END [{suffix}]')\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#\n",
    "# Plot Accuracy vs. Training Set Size\n",
    "#\n",
    "training_set_sizes = np.array(TRAINING_SLICE_FACTORS) * 50000\n",
    "all_suffix = get_file_suffix('all')\n",
    "plt.plot(training_set_sizes, accuracies, '-o', label=all_suffix)\n",
    "plt.xlabel('Number of Training Images')\n",
    "plt.ylabel('Accuracy (%)')\n",
    "plt.ylim(20, 65)\n",
    "plt.title(f'Test Accuracy vs. Training Set Size')\n",
    "plt.legend(loc=4)\n",
    "plt.savefig(f'./plots/cifar10_training_order_accuracies-{all_suffix}.png', bbox_inches='tight', dpi=300)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}