File size: 19,037 Bytes
525fbd4 |
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 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"source": [
"from graphviz import Digraph\n",
"\n",
"def trace(root):\n",
" #Builds a set of all nodes and edges in a graph\n",
" nodes, edges = set(), set()\n",
" def build(v):\n",
" if v not in nodes:\n",
" nodes.add(v)\n",
" for child in v._prev:\n",
" edges.add((child, v))\n",
" build(child)\n",
" build(root)\n",
" return nodes, edges\n",
"\n",
"def draw_dot(root):\n",
" dot = Digraph(format='svg', graph_attr={'rankdir': 'LR'}) #LR == Left to Right\n",
"\n",
" nodes, edges = trace(root)\n",
" for n in nodes:\n",
" uid = str(id(n))\n",
" #For any value in the graph, create a rectangular ('record') node for it\n",
" dot.node(name = uid, label = \"{ %s | data %.4f | grad %.4f }\" % ( n.label, n.data, n.grad), shape='record')\n",
" if n._op:\n",
" #If this value is a result of some operation, then create an op node for it\n",
" dot.node(name = uid + n._op, label=n._op)\n",
" #and connect this node to it\n",
" dot.edge(uid + n._op, uid)\n",
"\n",
" for n1, n2 in edges:\n",
" #Connect n1 to the node of n2\n",
" dot.edge(str(id(n1)), str(id(n2)) + n2._op)\n",
"\n",
" return dot"
],
"metadata": {
"id": "T0rN8d146jvF"
},
"execution_count": 1,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import math"
],
"metadata": {
"id": "JlYxBvFK0AjA"
},
"execution_count": 2,
"outputs": []
},
{
"cell_type": "code",
"source": [
"class Value:\n",
"\n",
" def __init__(self, data, _children=(), _op='', label=''):\n",
" self.data = data\n",
" self.grad = 0.0\n",
" self._backward = lambda: None #Its an empty function by default. This is what will do that gradient calculation at each of the operations.\n",
" self._prev = set(_children)\n",
" self._op = _op\n",
" self.label = label\n",
"\n",
"\n",
" def __repr__(self):\n",
" return f\"Value(data={self.data})\"\n",
"\n",
" def __add__(self, other):\n",
" other = other if isinstance(other, Value) else Value(other)\n",
" out = Value(self.data + other.data, (self, other), '+')\n",
"\n",
" def backward():\n",
" self.grad += 1.0 * out.grad\n",
" other.grad += 1.0 * out.grad\n",
"\n",
" out._backward = backward\n",
" return out\n",
"\n",
" def __radd__(self, other): #here\n",
" return self + other\n",
"\n",
" def __mul__(self, other):\n",
" other = other if isinstance(other, Value) else Value(other)\n",
" out = Value(self.data * other.data, (self, other), '*')\n",
"\n",
" def backward():\n",
" self.grad += other.data * out.grad\n",
" other.grad += self.data * out.grad\n",
" out._backward = backward\n",
" return out\n",
"\n",
" def __rmul__(self, other): #other * self\n",
" return self * other\n",
"\n",
" def __truediv__(self, other): #self/other\n",
" return self * other**-1\n",
"\n",
" def __neg__(self):\n",
" return self * -1\n",
"\n",
" def __sub__(self, other): #self - other\n",
" return self + (-other)\n",
"\n",
" def __pow__(self, other):\n",
" assert isinstance(other, (int, float)), \"only supporting int/float powers for now\"\n",
" out = Value(self.data ** other, (self, ), f\"**{other}\")\n",
"\n",
" def backward():\n",
" self.grad += (other * (self.data ** (other - 1))) * out.grad\n",
"\n",
" out._backward = backward\n",
" return out\n",
"\n",
" def tanh(self):\n",
" x = self.data\n",
" t = (math.exp(2*x) - 1)/(math.exp(2*x) + 1)\n",
" out = Value(t, (self, ), 'tanh')\n",
"\n",
" def backward():\n",
" self.grad += 1 - (t**2) * out.grad\n",
"\n",
" out._backward = backward\n",
" return out\n",
"\n",
" def exp(self):\n",
" x = self.data\n",
" out = Value(math.exp(x), (self, ), 'exp') #We merged t and out, into just out\n",
"\n",
" def backward():\n",
" self.grad += out.data * out.grad\n",
"\n",
" out._backward = backward\n",
" return out\n",
"\n",
" def backward(self):\n",
"\n",
" topo = []\n",
" visited = set()\n",
" def build_topo(v):\n",
" if v not in visited:\n",
" visited.add(v)\n",
" for child in v._prev:\n",
" build_topo(child)\n",
" topo.append(v)\n",
"\n",
" build_topo(self)\n",
"\n",
" self.grad = 1.0\n",
" for node in reversed(topo):\n",
" node._backward()"
],
"metadata": {
"id": "tA0zbyEwFbD5"
},
"execution_count": 3,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"---------------"
],
"metadata": {
"id": "m9hy05zbxhLP"
}
},
{
"cell_type": "code",
"source": [
"import random"
],
"metadata": {
"id": "gu3tnJu1Wti5"
},
"execution_count": 4,
"outputs": []
},
{
"cell_type": "code",
"source": [
"class Neuron:\n",
" def __init__(self, nin):\n",
" self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)]\n",
" self.b = Value(random.uniform(-1, 1))\n",
"\n",
" def __call__(self, x):\n",
" act = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)\n",
" out = act.tanh()\n",
" return out\n",
"\n",
" def parameters(self):\n",
" return self.w + [self.b]\n",
"\n",
"class Layer:\n",
" def __init__(self, nin, nout):\n",
" self.neurons = [Neuron(nin) for _ in range(nout)]\n",
"\n",
" def __call__(self, x):\n",
" outs = [n(x) for n in self.neurons]\n",
" return outs[0] if len(outs) == 1 else outs\n",
"\n",
" def parameters(self):\n",
" return [p for n in self.neurons for p in n.parameters()]\n",
"\n",
" # Alternative way of writing the above return function:\n",
" # parameters = []\n",
" # for n in self.neurons:\n",
" # p = n.parameters()\n",
" # parameters.extend(p)\n",
"\n",
"class MLP:\n",
" def __init__(self, nin, nouts):\n",
" sz = [nin] + nouts\n",
" self.layers = [Layer(sz[i], sz[i + 1]) for i in range(len(nouts))]\n",
"\n",
" def __call__(self, x):\n",
" for layer in self.layers:\n",
" x = layer(x)\n",
" return x\n",
"\n",
" def parameters(self):\n",
" return [p for l in self.layers for p in l.parameters()]"
],
"metadata": {
"id": "HmEO8Gi1KN_m"
},
"execution_count": 5,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"-------------"
],
"metadata": {
"id": "VHG86ZRipV_g"
}
},
{
"cell_type": "markdown",
"source": [
"Now we are trying to slighly nudge the value in order to reduce the loss"
],
"metadata": {
"id": "4P4QTecRpfJy"
}
},
{
"cell_type": "markdown",
"source": [
"So this essentially adds as an **update function**"
],
"metadata": {
"id": "VoV7xT_Ip60A"
}
},
{
"cell_type": "code",
"source": [
"for p in n.parameters():\n",
" p.data += -0.01 * p.grad #The negative sign is to convert any negative value to positive. Therefore increasing the value of the data, therefore decresing the loss"
],
"metadata": {
"id": "9GQoQUYEpMRP"
},
"execution_count": 12,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"------------------"
],
"metadata": {
"id": "TwdGr8Awqam4"
}
},
{
"cell_type": "markdown",
"source": [
"------------"
],
"metadata": {
"id": "ux4ZrKc_riiA"
}
},
{
"cell_type": "markdown",
"source": [
"Now we follow three steps: Forward pass -> Backward pass -> Update"
],
"metadata": {
"id": "dyoqzuslp-kP"
}
},
{
"cell_type": "code",
"source": [
"x = [2.0, 3.0, -1.0]\n",
"n = MLP(3, [4, 4, 1])\n",
"n(x)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "SYoQlzlMrelv",
"outputId": "3ce2cbfa-fec9-4618-cd27-8ed9d28bcf5b"
},
"execution_count": 35,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Value(data=0.33215137965743546)"
]
},
"metadata": {},
"execution_count": 35
}
]
},
{
"cell_type": "code",
"source": [
"xs = [\n",
" [2.0, 3.0, -1.0],\n",
" [3.0, -1.0, 0.5],\n",
" [0.5, 1.0, 1.0],\n",
" [1.0, 1.0, -1.0]\n",
"]\n",
"\n",
"ys = [1.0, -1.0, -1.0, 1.0] #output we want"
],
"metadata": {
"id": "wRwCzkhequ5C"
},
"execution_count": 36,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#forward pass\n",
"ypred = [n(x) for x in xs]\n",
"loss = sum((yout - ygt)**2 for ygt, yout in zip(ys, ypred))\n",
"loss"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Bxbev90VqFnG",
"outputId": "52407404-8787-4e29-c07b-31063bea7111"
},
"execution_count": 54,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Value(data=5.767047506521353)"
]
},
"metadata": {},
"execution_count": 54
}
]
},
{
"cell_type": "code",
"source": [
"#backward pass\n",
"loss.backward()"
],
"metadata": {
"id": "swKzizdIqJQf"
},
"execution_count": 55,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#update\n",
"for p in n.parameters():\n",
" p.data += -0.01 * p.grad"
],
"metadata": {
"id": "BtOE6keaqLse"
},
"execution_count": 56,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#check the prediction\n",
"ypred"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "O5iGQsw3qY-S",
"outputId": "2b14907c-d35f-4c4d-e503-d954e6f74435"
},
"execution_count": 57,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[Value(data=-0.25151630590655727),\n",
" Value(data=0.42164884655021817),\n",
" Value(data=-0.09631033350969018),\n",
" Value(data=-0.16748189979649136)]"
]
},
"metadata": {},
"execution_count": 57
}
]
},
{
"cell_type": "markdown",
"source": [
"-----------"
],
"metadata": {
"id": "qvIdNB-LsBFt"
}
},
{
"cell_type": "markdown",
"source": [
"-------------"
],
"metadata": {
"id": "XR8TNjCDsKfb"
}
},
{
"cell_type": "markdown",
"source": [
"Putting the entire process together in a single function"
],
"metadata": {
"id": "jUvrBdh9sLPt"
}
},
{
"cell_type": "code",
"source": [
"#Initialize the neural net\n",
"x = [2.0, 3.0, -1.0]\n",
"n = MLP(3, [4, 4, 1])\n",
"n(x)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "8wJ2E5Vsshho",
"outputId": "416ad55f-351d-4e98-f1ff-7108a2a32f65"
},
"execution_count": 58,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Value(data=0.9135198339971514)"
]
},
"metadata": {},
"execution_count": 58
}
]
},
{
"cell_type": "code",
"source": [
"#Data definition\n",
"xs = [\n",
" [2.0, 3.0, -1.0],\n",
" [3.0, -1.0, 0.5],\n",
" [0.5, 1.0, 1.0],\n",
" [1.0, 1.0, -1.0]\n",
"]\n",
"\n",
"ys = [1.0, -1.0, -1.0, 1.0] #output we want"
],
"metadata": {
"id": "qqZYLdOVrQ2i"
},
"execution_count": 59,
"outputs": []
},
{
"cell_type": "code",
"source": [
"\n",
"for k in range(10):\n",
"\n",
" #forward pass\n",
" ypred = [n(x) for x in xs]\n",
" loss = sum((yout - ygt)**2 for ygt, yout in zip(ys, ypred))\n",
"\n",
" #backward pass\n",
" for p in n.parameters():\n",
" p.grad = 0.0 #This is because after one round of update, we need to reset the value of the grads so that it can calculate and store the grad value of the updated loss function (i.e. The loss value that was improved after gradient descent). If we don't do this, the previous value of grad gets increamented with the new value during each back propagation (each time backward is called)\n",
" loss.backward()\n",
"\n",
" #update\n",
" #THIS HERE, WHAT WE ARE DOING IS 'GRADIENT DESCENT'. WE ARE NUDGING THE INPUT VALUES BY A LITTLE BIT\n",
" for p in n.parameters():\n",
" p.data += -0.04 * p.grad\n",
"\n",
" print(k, loss.data) #Printing the current number/iteration number plus how much loss"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "S3ffWvfDsS88",
"outputId": "d3b74c8c-2d0d-4b8b-e31e-f1081138a321"
},
"execution_count": 92,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"0 7.6021312440956095\n",
"1 8.0\n",
"2 6.398187062451399\n",
"3 7.999999999997639\n",
"4 8.0\n",
"5 7.999964084143684\n",
"6 8.0\n",
"7 8.0\n",
"8 7.999999961266539\n",
"9 8.0\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"ypred"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JoKOXxUWtB7K",
"outputId": "3420fc62-2352-47fc-d0e5-6547f3748ca5"
},
"execution_count": 93,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[Value(data=-1.0), Value(data=-1.0), Value(data=-1.0), Value(data=-1.0)]"
]
},
"metadata": {},
"execution_count": 93
}
]
},
{
"cell_type": "code",
"source": [
"loss"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "iyZ2e7FvwT5H",
"outputId": "5666e89c-6a29-486b-d3c8-290c29635124"
},
"execution_count": 94,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Value(data=8.0)"
]
},
"metadata": {},
"execution_count": 94
}
]
},
{
"cell_type": "markdown",
"source": [
"If the loss was reduced, then you can `n.parameters` to see what were the values into the NN that caused to get the desired target outputs"
],
"metadata": {
"id": "JLcsDJkhwsVS"
}
},
{
"cell_type": "markdown",
"source": [
"--------------------------"
],
"metadata": {
"id": "ubTHHuwzvNNh"
}
},
{
"cell_type": "markdown",
"source": [
"Okay so the predicted output didn't exactly come as expected 🥲 (The first and last value weren't supposed to be negative lol) \\\n",
"\\\n",
"But that was the idea of how we **train a neural net**!"
],
"metadata": {
"id": "xFwHw6IVvOKb"
}
}
]
} |