File size: 15,442 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 |
{
"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",
"\tdef __init__(self, nin):\n",
"\t\tself.w = [ Value(random.uniform(-1,1)) for _ in range(nin) ]\n",
"\t\tself.b = Value(random.uniform(-1,1))\n",
"\n",
"\tdef __call__(self, x):\n",
"\t\t# (w*x)+b\n",
"\t\tact = sum( (wi*xi for wi,xi in zip(self.w, x)), self.b )\n",
"\t\tout = act.tanh()\n",
"\t\treturn out\n",
"\n",
"class Layer:\n",
"\tdef __init__(self, nin, nout):\n",
"\t\tself.neurons = [Neuron(nin) for _ in range(nout)]\n",
"\n",
"\tdef __call__(self, x):\n",
"\t\touts = [n(x) for n in self.neurons]\n",
"\t\treturn outs[0] if len(outs)==1 else outs #The New added line for making the output better\n",
"\n",
"class MLP:\n",
"\tdef __init__(self, nin, nouts):\n",
"\t\tsz = [nin] + nouts\n",
"\t\tself.layers = [ Layer(sz[i], sz[i+1]) for i in range(len(nouts)) ]\n",
"\n",
"\tdef __call__(self, x):\n",
"\t\tfor layer in self.layers:\n",
"\t\t\tx = layer(x)\n",
"\t\treturn x"
],
"metadata": {
"id": "aCXXYNg_W680"
},
"execution_count": null,
"outputs": []
},
{
"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": "aG9pKV_RXsO8",
"outputId": "e6f183b9-896b-458f-9322-e91bc79e9da2",
"collapsed": true
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Value(data=-0.33393070997191954)"
]
},
"metadata": {},
"execution_count": 23
}
]
},
{
"cell_type": "markdown",
"source": [
"-----------"
],
"metadata": {
"id": "6DemdSsv_abu"
}
},
{
"cell_type": "markdown",
"source": [
"Now, we'll be returning the **parameters** from the MLP. So that will be from Neuron -> Layer -> MLP"
],
"metadata": {
"id": "rhKQgN2LKBf9"
}
},
{
"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": "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": "e2VaJPFdMVUs",
"outputId": "0a229e8c-2084-4037-e808-cc27cb3fd2ca"
},
"execution_count": 6,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"Value(data=0.7625252102576119)"
]
},
"metadata": {},
"execution_count": 6
}
]
},
{
"cell_type": "code",
"source": [
"n.parameters()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "cfOp08kYNmDX",
"outputId": "fe98dfd7-0e2b-4dd7-fb08-6f4cf60161ff"
},
"execution_count": 7,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[Value(data=0.31785584973173164),\n",
" Value(data=0.2998372553774835),\n",
" Value(data=-0.8029008199517247),\n",
" Value(data=-0.39340060142531286),\n",
" Value(data=0.23322412084873956),\n",
" Value(data=0.29891813550514534),\n",
" Value(data=-0.5314862907700675),\n",
" Value(data=0.19661072911432642),\n",
" Value(data=0.9142418954398666),\n",
" Value(data=0.041208786424172805),\n",
" Value(data=-0.23983634992214187),\n",
" Value(data=-0.593538786941121),\n",
" Value(data=0.39482399486723296),\n",
" Value(data=-0.9880306400643504),\n",
" Value(data=-0.8097855189886964),\n",
" Value(data=0.4629484174790124),\n",
" Value(data=0.31168805444961634),\n",
" Value(data=-0.9828138115624934),\n",
" Value(data=0.5221437252554255),\n",
" Value(data=-0.19703997468926882),\n",
" Value(data=-0.5504279057638468),\n",
" Value(data=-0.8365261779265616),\n",
" Value(data=-0.22783861276612227),\n",
" Value(data=0.5666981389300718),\n",
" Value(data=-0.06415010714317604),\n",
" Value(data=0.845414529622897),\n",
" Value(data=0.4793425135418725),\n",
" Value(data=-0.38321354069020086),\n",
" Value(data=-0.10963021731006206),\n",
" Value(data=0.14485994942129898),\n",
" Value(data=-0.19028270981146433),\n",
" Value(data=0.5148204886483112),\n",
" Value(data=-0.8559156650791364),\n",
" Value(data=0.3778416962066449),\n",
" Value(data=0.09608787032156774),\n",
" Value(data=-0.8288362456839788),\n",
" Value(data=0.5641592956285757),\n",
" Value(data=0.13764114112689052),\n",
" Value(data=-0.19625087652731277),\n",
" Value(data=-0.6117936229921406),\n",
" Value(data=0.7546009612155813)]"
]
},
"metadata": {},
"execution_count": 7
}
]
},
{
"cell_type": "markdown",
"source": [
"So these are all our parameters provided as inputs. The weights, inputs and biases"
],
"metadata": {
"id": "W0hGhhMaNozj"
}
},
{
"cell_type": "code",
"source": [
"len(n.parameters())"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "itFmD8hFNnph",
"outputId": "f43eee99-5831-4708-f203-518ddf7011e5"
},
"execution_count": 8,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"41"
]
},
"metadata": {},
"execution_count": 8
}
]
}
]
} |