diff --git a/00_pytorch_fundamentals.ipynb b/00_pytorch_fundamentals.ipynb index cb29a4b..ed78ac2 100644 --- a/00_pytorch_fundamentals.ipynb +++ b/00_pytorch_fundamentals.ipynb @@ -90,14 +90,14 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 1, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "id": "1VxEOik46Y4i", - "outputId": "b80240cb-a904-4d84-96b4-7b0b49f4f64c" + "outputId": "9057186d-e741-4840-d9db-a7a42fc047b8" }, "outputs": [ { @@ -111,7 +111,7 @@ ] }, "metadata": {}, - "execution_count": 2 + "execution_count": 1 } ], "source": [ @@ -178,13 +178,13 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 2, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "YUDgG2zk7Us5", - "outputId": "ccd84329-3950-413c-e4cc-cc7337583c98" + "outputId": "78b9eb98-cbb9-48dd-eef5-6d74790dbad4" }, "outputs": [ { @@ -195,7 +195,7 @@ ] }, "metadata": {}, - "execution_count": 3 + "execution_count": 2 } ], "source": [ @@ -219,13 +219,13 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 3, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "lV98Yz868bav", - "outputId": "6f339674-fce5-4111-9e33-5eb5e8ccf37d" + "outputId": "39beb641-ed7a-42b7-fce3-4680d2964d43" }, "outputs": [ { @@ -236,7 +236,7 @@ ] }, "metadata": {}, - "execution_count": 4 + "execution_count": 3 } ], "source": [ @@ -258,13 +258,13 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 4, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "-k4cyKumPfbE", - "outputId": "872383f5-672e-4a36-b8db-683643b622fb" + "outputId": "21acc793-b821-4f6a-e572-91a946a16762" }, "outputs": [ { @@ -275,7 +275,7 @@ ] }, "metadata": {}, - "execution_count": 5 + "execution_count": 4 } ], "source": [ @@ -300,13 +300,13 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 5, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "-IZF6ASs8QH9", - "outputId": "bc505e0f-bd96-4c8d-c6e5-81f623a36daf" + "outputId": "aa7aff30-967f-4895-f104-2869400c4258" }, "outputs": [ { @@ -317,7 +317,7 @@ ] }, "metadata": {}, - "execution_count": 6 + "execution_count": 5 } ], "source": [ @@ -339,13 +339,13 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 6, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "03hm3VVv8kr4", - "outputId": "1895687c-395c-4664-af14-e85215985174" + "outputId": "08093600-6203-40eb-a92b-f095adc8f73b" }, "outputs": [ { @@ -356,7 +356,7 @@ ] }, "metadata": {}, - "execution_count": 7 + "execution_count": 6 } ], "source": [ @@ -385,10 +385,10 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 7, "metadata": { "id": "6zREV1bDTGe2", - "outputId": "373f92e3-8074-4cc9-e89e-7f5975012ccb", + "outputId": "7e9afd6b-1d40-48b2-dff2-bd68568308e9", "colab": { "base_uri": "https://localhost:8080/" } @@ -402,7 +402,7 @@ ] }, "metadata": {}, - "execution_count": 8 + "execution_count": 7 } ], "source": [ @@ -423,13 +423,13 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 8, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "D5iNwCYL8QO9", - "outputId": "b61ce644-fb1e-45fd-a416-8d96f7ffa79e" + "outputId": "cae4060d-eed3-4867-d3e5-97a83655b495" }, "outputs": [ { @@ -441,7 +441,7 @@ ] }, "metadata": {}, - "execution_count": 9 + "execution_count": 8 } ], "source": [ @@ -463,13 +463,13 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8LREUbeb8r8j", - "outputId": "0aec1384-e8be-4ec4-821b-daf37ef079fa" + "outputId": "7e672ffa-ab11-4709-f962-bc98c63ba4f3" }, "outputs": [ { @@ -480,7 +480,7 @@ ] }, "metadata": {}, - "execution_count": 10 + "execution_count": 9 } ], "source": [ @@ -501,10 +501,10 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 10, "metadata": { "id": "_TL26I31TGe3", - "outputId": "7cfadd2c-472e-4ae3-b77b-d6c1bc4bac74", + "outputId": "1fb55bb7-37f0-450f-e16b-ee87938baab6", "colab": { "base_uri": "https://localhost:8080/" } @@ -518,7 +518,7 @@ ] }, "metadata": {}, - "execution_count": 11 + "execution_count": 10 } ], "source": [ @@ -538,13 +538,13 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 11, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "wEMDQr188QWW", - "outputId": "00f116c3-5d72-4dfa-b0e7-2ef276eb8ac1" + "outputId": "a55d486b-1ba7-4435-a7d0-97d7e5da882e" }, "outputs": [ { @@ -557,7 +557,7 @@ ] }, "metadata": {}, - "execution_count": 12 + "execution_count": 11 } ], "source": [ @@ -587,13 +587,13 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 12, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8dhuEsjS8QcT", - "outputId": "90371d99-4db0-4ea4-8419-9ec458a10827" + "outputId": "592a2c6a-1cff-4833-d018-cf96b48fb79d" }, "outputs": [ { @@ -604,7 +604,7 @@ ] }, "metadata": {}, - "execution_count": 13 + "execution_count": 12 } ], "source": [ @@ -623,10 +623,10 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 13, "metadata": { "id": "hdVv4iNRTGe5", - "outputId": "69f6b6e5-128b-48e1-bf70-b239971eefdc", + "outputId": "412839c2-723f-4e78-a064-627ed063073e", "colab": { "base_uri": "https://localhost:8080/" } @@ -640,7 +640,7 @@ ] }, "metadata": {}, - "execution_count": 14 + "execution_count": 13 } ], "source": [ @@ -709,26 +709,26 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 14, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "EOJEtDx--GnK", - "outputId": "b0c8c3b3-14b3-4514-fb3c-83fcc523f589" + "outputId": "34c9a7a1-012d-4f7e-aeac-81f1c955fd4e" }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ - "(tensor([[0.7907, 0.6947, 0.0406, 0.9267],\n", - " [0.9972, 0.1773, 0.7616, 0.6983],\n", - " [0.8819, 0.8777, 0.2598, 0.8966]]), torch.float32)" + "(tensor([[0.8852, 0.5874, 0.7129, 0.2844],\n", + " [0.0955, 0.8288, 0.9870, 0.7897],\n", + " [0.6978, 0.0017, 0.4756, 0.3552]]), torch.float32)" ] }, "metadata": {}, - "execution_count": 15 + "execution_count": 14 } ], "source": [ @@ -760,9 +760,9 @@ "base_uri": "https://localhost:8080/" }, "id": "xMF_NUp3Ym__", - "outputId": "8dd35e78-aa91-4d90-e07d-93a02cb1678b" + "outputId": "21840ba1-65c5-44df-c946-09e2cf639ecc" }, - "execution_count": 16, + "execution_count": 15, "outputs": [ { "output_type": "execute_result", @@ -772,7 +772,7 @@ ] }, "metadata": {}, - "execution_count": 16 + "execution_count": 15 } ] }, @@ -795,13 +795,13 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 16, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "oCzhd0hl9Vp6", - "outputId": "ac872d53-c25e-495c-a52c-e2f5c680c5b3" + "outputId": "dd4e3690-42a2-424e-f2c3-e176126068cb" }, "outputs": [ { @@ -814,7 +814,7 @@ ] }, "metadata": {}, - "execution_count": 17 + "execution_count": 16 } ], "source": [ @@ -834,10 +834,10 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 17, "metadata": { "id": "HRe6sSXiTGe6", - "outputId": "ea976213-d476-4a6e-a10c-1cacc563f9e5", + "outputId": "c34fa1de-49a6-4909-8e5f-1e5785e9f6f1", "colab": { "base_uri": "https://localhost:8080/" } @@ -853,7 +853,7 @@ ] }, "metadata": {}, - "execution_count": 18 + "execution_count": 17 } ], "source": [ @@ -884,13 +884,13 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 18, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "1IqUs81d9W4W", - "outputId": "8e5428fd-6bcb-474a-db6d-d0f9b89f6d77" + "outputId": "fe2305b1-b1b0-477f-dd3f-2137d515ff95" }, "outputs": [ { @@ -909,7 +909,7 @@ ] }, "metadata": {}, - "execution_count": 19 + "execution_count": 18 } ], "source": [ @@ -936,13 +936,13 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 19, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ZvXwUut5BhHq", - "outputId": "926b79d0-5c2c-4450-c6a3-513f12160c66" + "outputId": "27a445cc-7476-4b65-dd0b-d721e9bbabdf" }, "outputs": [ { @@ -953,7 +953,7 @@ ] }, "metadata": {}, - "execution_count": 20 + "execution_count": 19 } ], "source": [ @@ -1009,13 +1009,13 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 20, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "q3MoGnpw9XaF", - "outputId": "d62ce2a0-b2b2-4ce2-f207-e39c6395a060" + "outputId": "853be01c-96b1-4c5a-d347-a0971f6cd4e4" }, "outputs": [ { @@ -1026,7 +1026,7 @@ ] }, "metadata": {}, - "execution_count": 21 + "execution_count": 20 } ], "source": [ @@ -1058,13 +1058,13 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 21, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PKSuajld_09s", - "outputId": "b7b1b2e5-6f90-4592-9941-aa9c826add56" + "outputId": "7ef35574-ba0c-4588-8029-ac802b27ac71" }, "outputs": [ { @@ -1075,7 +1075,7 @@ ] }, "metadata": {}, - "execution_count": 22 + "execution_count": 21 } ], "source": [ @@ -1105,22 +1105,22 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 22, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "hd_X4D0j7Umq", - "outputId": "960f2778-81d5-4633-9b59-c39db87a379c" + "outputId": "bc363cdc-8bd6-4038-c723-62fe603ab98d" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ - "tensor([[0.8791, 0.3106, 0.3004, 0.8722],\n", - " [0.8353, 0.3828, 0.3335, 0.3006],\n", - " [0.2225, 0.1692, 0.0564, 0.3756]])\n", + "tensor([[0.2186, 0.8424, 0.0791, 0.7177],\n", + " [0.1445, 0.7466, 0.1414, 0.7535],\n", + " [0.3222, 0.3009, 0.1660, 0.9803]])\n", "Shape of tensor: torch.Size([3, 4])\n", "Datatype of tensor: torch.float32\n", "Device tensor is stored on: cpu\n" @@ -1187,13 +1187,13 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 23, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "X71WpQoPD7a4", - "outputId": "63866028-a07d-41e0-ba78-e94b06a6c93c" + "outputId": "08ad8877-d6fc-4f2a-ef73-51a076b33355" }, "outputs": [ { @@ -1204,7 +1204,7 @@ ] }, "metadata": {}, - "execution_count": 24 + "execution_count": 23 } ], "source": [ @@ -1215,13 +1215,13 @@ }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 24, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Sp4TlTWWEFeO", - "outputId": "0848ef00-e945-42b9-f004-438b53d1c2f1" + "outputId": "0e3436ef-4b48-44e7-b365-9d31939987d4" }, "outputs": [ { @@ -1232,7 +1232,7 @@ ] }, "metadata": {}, - "execution_count": 25 + "execution_count": 24 } ], "source": [ @@ -1251,13 +1251,13 @@ }, { "cell_type": "code", - "execution_count": 26, + "execution_count": 25, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "XuB1UjCIEJIA", - "outputId": "5eae722c-5cad-4e2b-b71a-e41a8fcd8f93" + "outputId": "9d3ec535-5bd3-4486-ecf1-3f88e2efeca6" }, "outputs": [ { @@ -1268,7 +1268,7 @@ ] }, "metadata": {}, - "execution_count": 26 + "execution_count": 25 } ], "source": [ @@ -1287,13 +1287,13 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 26, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "U4iWKoLsENry", - "outputId": "7081d041-8c2a-4276-bd82-5709f94a6ba4" + "outputId": "383ee127-4b6d-48f9-a0d8-6a6fbc057fbb" }, "outputs": [ { @@ -1304,7 +1304,7 @@ ] }, "metadata": {}, - "execution_count": 27 + "execution_count": 26 } ], "source": [ @@ -1315,13 +1315,13 @@ }, { "cell_type": "code", - "execution_count": 28, + "execution_count": 27, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "tFgZY-PaFNXa", - "outputId": "bfad3a61-4385-4b32-d7b7-673b7d383d40" + "outputId": "bbb21693-b064-49d5-afea-03cc8a537b6f" }, "outputs": [ { @@ -1332,7 +1332,7 @@ ] }, "metadata": {}, - "execution_count": 28 + "execution_count": 27 } ], "source": [ @@ -1352,13 +1352,13 @@ }, { "cell_type": "code", - "execution_count": 29, + "execution_count": 28, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uVysdk3kFWbY", - "outputId": "e9e9dfcc-355d-49fe-b140-6ea4d660031a" + "outputId": "9efb48da-4a00-45dc-ffa6-7d4b8b89f7ab" }, "outputs": [ { @@ -1369,7 +1369,7 @@ ] }, "metadata": {}, - "execution_count": 29 + "execution_count": 28 } ], "source": [ @@ -1379,13 +1379,13 @@ }, { "cell_type": "code", - "execution_count": 30, + "execution_count": 29, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "IxuPJIpNFbqO", - "outputId": "d939294f-72d0-4d1c-9a01-8a790cebd872" + "outputId": "ccb19a0f-61a4-40b7-9c53-1ddaeb783ae6" }, "outputs": [ { @@ -1396,7 +1396,7 @@ ] }, "metadata": {}, - "execution_count": 30 + "execution_count": 29 } ], "source": [ @@ -1415,13 +1415,13 @@ }, { "cell_type": "code", - "execution_count": 31, + "execution_count": 30, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "S5v3RkR0F2Jq", - "outputId": "a0d18399-85b1-4aba-ef66-787a4b32ed4f" + "outputId": "1d7ac72a-a01b-4f50-fb77-d2c4e5f68218" }, "outputs": [ { @@ -1470,13 +1470,13 @@ }, { "cell_type": "code", - "execution_count": 32, + "execution_count": 31, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ZE7loucmDlEM", - "outputId": "93923424-8d16-49dc-e390-1985dddcf7d2" + "outputId": "4dedbf9b-9082-4386-95f5-25b1a7529de7" }, "outputs": [ { @@ -1487,7 +1487,7 @@ ] }, "metadata": {}, - "execution_count": 32 + "execution_count": 31 } ], "source": [ @@ -1503,8 +1503,10 @@ "\n", "For our `tensor` variable with values `[1, 2, 3]`:\n", "\n", - "* **Element-wise** = `[1*1, 2*2, 3*3]` = `[1, 4, 9]`\n", - "* **Matrix multiplication (also called dot product)** = `[1*1 + 2*2 + 3*3]` = `[14]`" + "| Operation | Calculation | Code |\n", + "| ----- | ----- | ----- |\n", + "| **Element-wise multiplication** | `[1*1, 2*2, 3*3]` = `[1, 4, 9]` | `tensor * tensor` |\n", + "| **Matrix multiplication** | `[1*1 + 2*2 + 3*3]` = `[14]` | `tensor.matmul(tensor)` |\n" ], "metadata": { "id": "VUAZ3_b0vOKv" @@ -1521,9 +1523,9 @@ "base_uri": "https://localhost:8080/" }, "id": "i42gkUeHvI_1", - "outputId": "a1037745-bf96-4a3c-a082-d2c40409cead" + "outputId": "08b24696-438d-4ba4-9feb-076bcaa93af2" }, - "execution_count": 33, + "execution_count": 32, "outputs": [ { "output_type": "execute_result", @@ -1533,8 +1535,35 @@ ] }, "metadata": {}, + "execution_count": 32 + } + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "PvCBiiTTDk8y", + "outputId": "f05fbec7-2ba4-46fb-96e1-61546940db14" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "tensor(14)" + ] + }, + "metadata": {}, "execution_count": 33 } + ], + "source": [ + "# Matrix multiplication\n", + "torch.matmul(tensor, tensor)" ] }, { @@ -1544,8 +1573,8 @@ "colab": { "base_uri": "https://localhost:8080/" }, - "id": "PvCBiiTTDk8y", - "outputId": "f5f58b69-43c6-4904-ca53-8bfc3738ce91" + "id": "m4E_pROBDk2r", + "outputId": "3a78d79c-5d6d-44a6-c900-50225d392174" }, "outputs": [ { @@ -1559,33 +1588,6 @@ "execution_count": 34 } ], - "source": [ - "# Matrix multiplication\n", - "torch.matmul(tensor, tensor)" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "metadata": { - "colab": { - "base_uri": "https://localhost:8080/" - }, - "id": "m4E_pROBDk2r", - "outputId": "171aeee3-7eb7-4e30-dd95-44515819176c" - }, - "outputs": [ - { - "output_type": "execute_result", - "data": { - "text/plain": [ - "tensor(14)" - ] - }, - "metadata": {}, - "execution_count": 35 - } - ], "source": [ "# Can also use the \"@\" symbol for matrix multiplication, though not recommended\n", "tensor @ tensor" @@ -1604,21 +1606,21 @@ }, { "cell_type": "code", - "execution_count": 36, + "execution_count": 35, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6qMSaLOoJscL", - "outputId": "b372f8eb-a2ef-4cb1-9060-d77a5839b76f" + "outputId": "4489dbac-ad18-46f7-be9d-3c0a405a9f63" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ - "CPU times: user 134 µs, sys: 44 µs, total: 178 µs\n", - "Wall time: 187 µs\n" + "CPU times: user 1.35 ms, sys: 140 µs, total: 1.49 ms\n", + "Wall time: 1.33 ms\n" ] } ], @@ -1643,16 +1645,16 @@ "base_uri": "https://localhost:8080/" }, "id": "vVWiKB0KwH74", - "outputId": "0201145c-f0bf-4f71-ce49-a78c830a7aea" + "outputId": "12f6154f-ad86-407b-a515-9bf4816f136a" }, - "execution_count": 37, + "execution_count": 36, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ - "CPU times: user 38 µs, sys: 0 ns, total: 38 µs\n", - "Wall time: 41.2 µs\n" + "CPU times: user 91 µs, sys: 0 ns, total: 91 µs\n", + "Wall time: 96.3 µs\n" ] }, { @@ -1663,7 +1665,7 @@ ] }, "metadata": {}, - "execution_count": 37 + "execution_count": 36 } ] }, @@ -1680,14 +1682,14 @@ }, { "cell_type": "code", - "execution_count": 38, + "execution_count": 37, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 201 }, "id": "rN5RcoD4Jo6y", - "outputId": "31045115-a707-47cc-e2f6-aa8f1f36ef3e" + "outputId": "f969f45b-48db-4720-dbc2-fb1bea6d4940" }, "outputs": [ { @@ -1697,7 +1699,7 @@ "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m [9, 12]], dtype=torch.float32)\n\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmatmul\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtensor_A\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtensor_B\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 8\u001b[0m [9, 12]], dtype=torch.float32)\n\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmatmul\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtensor_A\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtensor_B\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# (this will error)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mRuntimeError\u001b[0m: mat1 and mat2 shapes cannot be multiplied (3x2 and 3x2)" ] } @@ -1744,9 +1746,9 @@ "base_uri": "https://localhost:8080/" }, "id": "lUqgaANiy1wq", - "outputId": "69b40f65-4d92-4827-b557-d8c93c20bf25" + "outputId": "d7b35a76-4220-45eb-b370-381a8d16bbb5" }, - "execution_count": 39, + "execution_count": 38, "outputs": [ { "output_type": "stream", @@ -1774,9 +1776,9 @@ "base_uri": "https://localhost:8080/" }, "id": "DveqxO7iy_Fi", - "outputId": "21e96e94-fabe-4c49-c23a-acb13472abe5" + "outputId": "e47f8036-9e16-4701-9252-f574be1ea1f6" }, - "execution_count": 40, + "execution_count": 39, "outputs": [ { "output_type": "stream", @@ -1793,13 +1795,13 @@ }, { "cell_type": "code", - "execution_count": 41, + "execution_count": 40, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "35rEIu-NKtVE", - "outputId": "22d45d73-73bf-4b2f-8032-853a30b68c80" + "outputId": "8f83cd5b-7afc-41b1-d431-f697b152483b" }, "outputs": [ { @@ -1844,10 +1846,10 @@ }, { "cell_type": "code", - "execution_count": 42, + "execution_count": 41, "metadata": { "id": "x3rJvW_TTGe_", - "outputId": "48f03659-b63d-4f18-9722-e7f57be489b1", + "outputId": "329beb01-a327-46b7-aa67-496d90fab7da", "colab": { "base_uri": "https://localhost:8080/" } @@ -1863,7 +1865,7 @@ ] }, "metadata": {}, - "execution_count": 42 + "execution_count": 41 } ], "source": [ @@ -1918,13 +1920,13 @@ }, { "cell_type": "code", - "execution_count": 50, + "execution_count": 42, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "mC_MjKW1LX7T", - "outputId": "0cf24e9f-745c-49b7-8270-11e4cc0dae60" + "outputId": "7f2218f4-9f31-4a66-ea40-51640448cbd4" }, "outputs": [ { @@ -1974,6 +1976,7 @@ "Remember, matrix multiplication is all you need.\n", "\n", "![matrix multiplication is all you need](https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/00_matrix_multiplication_is_all_you_need.jpeg)\n", + "\n", "*When you start digging into neural network layers and building your own, you'll find matrix multiplications everywhere. **Source:** https://marksaroufim.substack.com/p/working-class-deep-learner*" ], "metadata": { @@ -1998,13 +2001,13 @@ }, { "cell_type": "code", - "execution_count": 51, + "execution_count": 43, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "jrFQbe5fP1Rk", - "outputId": "2cab7180-2e17-41ed-f2bb-2aa5156f9fee" + "outputId": "c6b488c4-7808-4bd5-fcd6-3913e07beca6" }, "outputs": [ { @@ -2015,7 +2018,7 @@ ] }, "metadata": {}, - "execution_count": 51 + "execution_count": 43 } ], "source": [ @@ -2035,13 +2038,13 @@ }, { "cell_type": "code", - "execution_count": 56, + "execution_count": 44, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "e5wSP9YKP3Lb", - "outputId": "c0a55faf-aa21-4193-973f-47c39b149a81" + "outputId": "3b501b08-de1f-49e5-e820-c0bfc5d9b5c8" }, "outputs": [ { @@ -2076,13 +2079,13 @@ }, { "cell_type": "code", - "execution_count": 53, + "execution_count": 45, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "0Cr23Y9uP3HO", - "outputId": "3ea44e67-2fb8-440f-9547-9b899f71f836" + "outputId": "b778397c-d56d-4413-995c-2078cb99cf34" }, "outputs": [ { @@ -2093,7 +2096,7 @@ ] }, "metadata": {}, - "execution_count": 53 + "execution_count": 45 } ], "source": [ @@ -2106,7 +2109,7 @@ "id": "i7ApCaZjDkvp" }, "source": [ - "### TK - Positional min/max\n", + "### Positional min/max\n", "\n", "You can also find the index of a tensor where the max or minimum occurs with [`torch.argmax()`](https://pytorch.org/docs/stable/generated/torch.argmax.html) and [`torch.argmin()`](https://pytorch.org/docs/stable/generated/torch.argmin.html) respectively.\n", "\n", @@ -2115,13 +2118,13 @@ }, { "cell_type": "code", - "execution_count": 58, + "execution_count": 46, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "FzNBl9JSGlHi", - "outputId": "02271427-c06d-4a11-dc60-55090b366568" + "outputId": "981a9ed0-69e5-4126-907b-20aeaf74ad19" }, "outputs": [ { @@ -2152,95 +2155,125 @@ "source": [ "### TK - Change tensor datatype\n", "\n", - "UPTOHERE\n", + "As mentioned, a common issue with deep learning operations is having your tensors in different datatypes.\n", "\n", - "See torch datatypes here - https://pytorch.org/docs/stable/tensors.html " + "If one tensor is in `torch.float64` and another is in `torch.float32`, you might run into some errors.\n", + "\n", + "But there's a fix.\n", + "\n", + "You can change the datatypes of tensors using [`torch.Tensor.type(dtype=None)`](https://pytorch.org/docs/stable/generated/torch.Tensor.type.html) where the `dtype` parameter is the datatype you'd like to use.\n", + "\n", + "First we'll create a tensor and check it's datatype (the default is `torch.float32`)." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 47, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "rY2FEsCAOaLu", - "outputId": "fa6b90bf-60a4-4769-b6a9-b29c080a6df6" + "outputId": "da8f0d9b-1d60-4396-8bcd-8155bee83c64" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ "torch.float32" ] }, - "execution_count": 48, "metadata": {}, - "output_type": "execute_result" + "execution_count": 47 } ], "source": [ + "# Create a tensor and check its datatype\n", "tensor = torch.arange(10., 100., 10.)\n", "tensor.dtype" ] }, + { + "cell_type": "markdown", + "source": [ + "Now we'll create another tensor the same as before but change its datatype to `torch.float16`.\n", + "\n" + ], + "metadata": { + "id": "jR30FHEc92of" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 48, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Cac8gRYjOeab", - "outputId": "e160bb02-9961-4c34-9ef3-d0acfcd4ca4d" + "outputId": "a63ed159-1d38-4d1d-8acd-435abed00728" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ "tensor([10., 20., 30., 40., 50., 60., 70., 80., 90.], dtype=torch.float16)" ] }, - "execution_count": 49, "metadata": {}, - "output_type": "execute_result" + "execution_count": 48 } ], "source": [ + "# Create a float16 tensor\n", "tensor_float16 = tensor.type(torch.float16)\n", "tensor_float16" ] }, + { + "cell_type": "markdown", + "source": [ + "And we can do something similar to make a `torch.int8` tensor." + ], + "metadata": { + "id": "ndVlKJZ4-7_5" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 50, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8Yqovld2Oj6s", - "outputId": "f501e583-feed-447c-f8ee-9fe56bf6c2e5" + "outputId": "73c6737b-d89f-4e81-e032-d6a782f9bbb0" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int32)" + "tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int8)" ] }, - "execution_count": 50, "metadata": {}, - "output_type": "execute_result" + "execution_count": 50 } ], "source": [ - "tensor_int32 = tensor.type(torch.int32)\n", - "tensor_int32" + "# Create a int8 tensor\n", + "tensor_int8 = tensor.type(torch.int8)\n", + "tensor_int8" ] }, { "cell_type": "markdown", "source": [ + "> **Note:** Different datatypes can be confusing to begin with. But think of it like this, the lower the number (e.g. 32, 16, 8), the less precise a computer stores the value. And with a lower amount of storage, this generally results in faster computation and a smaller overall model. Mobile-based neural networks often operate with 8-bit integers, smaller and faster to run but less accurate than their float32 counterparts. For more on this, I'd read up about [precision in computing](https://en.wikipedia.org/wiki/Precision_(computer_science)).\n", + "\n", "> **Exercise:** So far we've covered a fair few tensor methods but there's a bunch more in the [`torch.Tensor` documentation](https://pytorch.org/docs/stable/tensors.html), I'd recommend spending 10-minutes scrolling through and looking into any that catch your eye. Click on them and then write them out in code yourself to see what happens." ], "metadata": { @@ -2255,61 +2288,86 @@ "source": [ "### TK - Reshaping, stacking, squeezing and unsqueezing\n", "\n", + "Often times you'll want to reshape or change the dimensions of your tensors without actually changing the values inside them.\n", + "\n", + "To do so, some popular methods are:\n", + "\n", + "| Method | One-line description |\n", + "| ----- | ----- |\n", + "| [`torch.reshape(input, shape)`](https://pytorch.org/docs/stable/generated/torch.reshape.html#torch.reshape) | Reshapes `input` to `shape` (if compatible), can also use `torch.Tensor.reshape()`. |\n", + "| [`torch.Tensor.view(shape)`](https://pytorch.org/docs/stable/generated/torch.Tensor.view.html) | Returns a view of the original tensor in a different `shape` but shares the same data as the original tensor. |\n", + "| [`torch.stack(tensors, dim=0)`](https://pytorch.org/docs/1.9.1/generated/torch.stack.html) | Concatenates a sequence of `tensors` along a new dimension (`dim`), all `tensors` must be same size. |\n", + "| [`torch.squeeze(input)`](https://pytorch.org/docs/stable/generated/torch.squeeze.html) | Squeezes `input` to remove all the dimenions with value `1`. |\n", + "| [`torch.unsqueeze(input, dim)`](https://pytorch.org/docs/1.9.1/generated/torch.unsqueeze.html) | Returns `input` with a dimension value of `1` added at `dim`. | \n", + "| [`torch.permute(input, dims)`](https://pytorch.org/docs/stable/generated/torch.permute.html) | Returns a *view* of the original `input` with its dimensions permuted (rearranged) to `dims`. | \n", + "\n", "Why do any of these?\n", "\n", - "Avoid for loops in your tensor code.\n", + "Because deep learning models (neural networks) are all about manipulating tensors in some way. And because of the rules of matrix multiplication, if you've got shape mismatches, you'll run into errors. These methods help you make the right elements of your tensors are mixing with the right elements of other tensors. \n", "\n", - "For loops slow things down." + "Let's try them out.\n", + "\n", + "First, we'll create a tensor." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 52, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "EYjRTLOzG4Ev", - "outputId": "207416f6-9862-4a20-c216-290f04c84408" + "outputId": "3ab8581d-196f-4362-dba3-4f61e7aa608e" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "tensor([1., 2., 3., 4., 5., 6., 7.])" + "(tensor([1., 2., 3., 4., 5., 6., 7.]), torch.Size([7]))" ] }, - "execution_count": 52, "metadata": {}, - "output_type": "execute_result" + "execution_count": 52 } ], "source": [ + "# Create a tensor\n", "import torch\n", "x = torch.arange(1., 8.)\n", - "x" + "x, x.shape" ] }, + { + "cell_type": "markdown", + "source": [ + "Now let's add an extra dimension with `torch.reshape()`. " + ], + "metadata": { + "id": "3_VarMO9CoT8" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 53, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "US4WjpQ3SG-8", - "outputId": "44e3fb5c-2cbf-439e-e293-ddc7475a3660" + "outputId": "630f14d2-e5fc-4f55-a440-5cf5dc8fef7c" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ "(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))" ] }, - "execution_count": 53, "metadata": {}, - "output_type": "execute_result" + "execution_count": 53 } ], "source": [ @@ -2318,23 +2376,35 @@ "x_reshaped, x_reshaped.shape" ] }, + { + "cell_type": "markdown", + "source": [ + "We can also change the view with `torch.view()`." + ], + "metadata": { + "id": "tig5xm0jCxuU" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 55, "metadata": { "id": "WDN2BNe5TGfB", - "outputId": "6e4df071-86db-43b7-a86f-607e30d2f5a9" + "outputId": "2dc0e767-6cc4-464f-d6ca-ab210ac2f366", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ "(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))" ] }, - "execution_count": 54, "metadata": {}, - "output_type": "execute_result" + "execution_count": 55 } ], "source": [ @@ -2344,23 +2414,37 @@ "z, z.shape" ] }, + { + "cell_type": "markdown", + "source": [ + "Remember though, changing the view of a tensor with `torch.view()` really only creates a new view of the *same* tensor.\n", + "\n", + "So changing the view changes the original tensor too. " + ], + "metadata": { + "id": "m8joAaUEC2NX" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 56, "metadata": { "id": "2DxURVvXTGfC", - "outputId": "f2710ddd-7caa-433f-eba6-32bc7c445908" + "outputId": "6e7d3e46-968f-4082-a1f0-05d5d7bc73bd", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ "(tensor([[5., 2., 3., 4., 5., 6., 7.]]), tensor([5., 2., 3., 4., 5., 6., 7.]))" ] }, - "execution_count": 55, "metadata": {}, - "output_type": "execute_result" + "execution_count": 56 } ], "source": [ @@ -2369,18 +2453,28 @@ "z, x" ] }, + { + "cell_type": "markdown", + "source": [ + "If we wanted to stack our new tensor on top of itself five times, we could do so with `torch.stack()`." + ], + "metadata": { + "id": "YxnqDBlpDDJ_" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 58, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "pX5Adf3ORiTK", - "outputId": "60b3ae0d-b819-4765-9987-70a71ec4bc78" + "outputId": "849aed7e-60a6-42e8-fe8f-5bd0a8750ce1" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ "tensor([[5., 2., 3., 4., 5., 6., 7.],\n", @@ -2389,323 +2483,448 @@ " [5., 2., 3., 4., 5., 6., 7.]])" ] }, - "execution_count": 56, "metadata": {}, - "output_type": "execute_result" + "execution_count": 58 } ], "source": [ "# Stack tensors on top of each other\n", - "x_stacked = torch.stack([x, x, x, x], dim=0)\n", + "x_stacked = torch.stack([x, x, x, x], dim=0) # try changing dim to dim=1 and see what happens\n", "x_stacked" ] }, + { + "cell_type": "markdown", + "source": [ + "How about removing all single dimensions from a tensor?\n", + "\n", + "To do so you can use `torch.squeeze()` (I remember this as *squeezing* the tensor to only have dimensions over 1)." + ], + "metadata": { + "id": "ET56QzNHDuOI" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 61, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "w2Y2HEoDRxJZ", - "outputId": "7fdf9ae2-250f-463c-9b93-38246e992fbf" + "outputId": "c04b3fb8-3f7e-4546-e578-80ad03954c60" }, "outputs": [ { - "data": { - "text/plain": [ - "(tensor([5., 2., 3., 4., 5., 6., 7.]), torch.Size([7]))" - ] - }, - "execution_count": 57, - "metadata": {}, - "output_type": "execute_result" + "output_type": "stream", + "name": "stdout", + "text": [ + "Previous tensor: tensor([[5., 2., 3., 4., 5., 6., 7.]])\n", + "Previous shape: torch.Size([1, 7])\n", + "\n", + "New tensor: tensor([5., 2., 3., 4., 5., 6., 7.])\n", + "New shape: torch.Size([7])\n" + ] } ], "source": [ + "print(f\"Previous tensor: {x_reshaped}\")\n", + "print(f\"Previous shape: {x_reshaped.shape}\")\n", + "\n", "# Remove extra dimension from x_reshaped\n", "x_squeezed = x_reshaped.squeeze()\n", - "x_squeezed, x_squeezed.shape" + "print(f\"\\nNew tensor: {x_squeezed}\")\n", + "print(f\"New shape: {x_squeezed.shape}\")" ] }, + { + "cell_type": "markdown", + "source": [ + "And to do the reverse of `torch.squeeze()` you can use `torch.unsqueeze()` to add a dimension value of 1 at a specific index." + ], + "metadata": { + "id": "acjDLk8WD8NC" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 62, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "CUC-DEEwSYv7", - "outputId": "adc36fde-58ce-472f-af8f-2e6362f0a360" + "outputId": "fefaa6a4-f5e4-41f8-9545-c952965f749f" }, "outputs": [ { - "data": { - "text/plain": [ - "(tensor([[5., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))" - ] - }, - "execution_count": 58, - "metadata": {}, - "output_type": "execute_result" + "output_type": "stream", + "name": "stdout", + "text": [ + "Previous tensor: tensor([5., 2., 3., 4., 5., 6., 7.])\n", + "Previous shape: torch.Size([7])\n", + "\n", + "New tensor: tensor([[5., 2., 3., 4., 5., 6., 7.]])\n", + "New shape: torch.Size([1, 7])\n" + ] } ], "source": [ - "# Add an extra dimension with unsqueeze\n", + "print(f\"Previous tensor: {x_squeezed}\")\n", + "print(f\"Previous shape: {x_squeezed.shape}\")\n", + "\n", + "## Add an extra dimension with unsqueeze\n", "x_unsqueezed = x_squeezed.unsqueeze(dim=0)\n", - "x_unsqueezed, x_unsqueezed.shape" + "print(f\"\\nNew tensor: {x_unsqueezed}\")\n", + "print(f\"New shape: {x_unsqueezed.shape}\")" ] }, + { + "cell_type": "markdown", + "source": [ + "You can also rearrange the order of axes values with `torch.permute(input, dims)`, where the `input` gets turned into a *view* with new `dims`." + ], + "metadata": { + "id": "R9DuJzXgFbM5" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 63, "metadata": { "id": "fCRGCX8DTGfC", - "outputId": "ca52f97f-b310-4731-df1f-afb7f65bd6fb" + "outputId": "a64ed4cc-7d45-41bc-9623-906af3edaf1a", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { - "data": { - "text/plain": [ - "(torch.Size([224, 224, 3]), torch.Size([3, 224, 224]))" - ] - }, - "execution_count": 63, - "metadata": {}, - "output_type": "execute_result" + "output_type": "stream", + "name": "stdout", + "text": [ + "Previous shape: torch.Size([224, 224, 3])\n", + "New shape: torch.Size([3, 224, 224])\n" + ] } ], "source": [ - "# Change different axes\n", + "# Create tensor with specific shape\n", "x_original = torch.rand(size=(224, 224, 3))\n", + "\n", + "# Permute the original tensor to rearrange the axis order\n", "x_permuted = x_original.permute(2, 0, 1) # shifts axis 0->1, 1->2, 2->0\n", - "x_original.shape, x_permuted.shape" + "\n", + "print(f\"Previous shape: {x_original.shape}\")\n", + "print(f\"New shape: {x_permuted.shape}\")" ] }, + { + "cell_type": "markdown", + "source": [ + "> **Note**: Because permuting returns a *view* (shares the same data as the original), the values in the permuted tensor will be the same as the original tensor and if you change the values in the view, it will change the values of the original." + ], + "metadata": { + "id": "06LKaFemGBoE" + } + }, { "cell_type": "markdown", "metadata": { "id": "nEPqVL7fTGfC" }, "source": [ - "## TK - Indexing (selecting data from tensors)" + "## TK - Indexing (selecting data from tensors)\n", + "\n", + "Sometimes you'll want to select specific data from tensors (for example, only the first column or second row).\n", + "\n", + "To do so, you can use indexing.\n", + "\n", + "If you've ever done indexing on Python lists or NumPy arrays, indexing in PyTorch with tensors is very similar." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 78, "metadata": { - "id": "oSXzdxCQTGfD" + "id": "oSXzdxCQTGfD", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "40101f58-f772-4a3e-b38d-4a4a955c74e1" }, - "outputs": [], + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "(tensor([[[1, 2, 3],\n", + " [4, 5, 6],\n", + " [7, 8, 9]]]), torch.Size([1, 3, 3]))" + ] + }, + "metadata": {}, + "execution_count": 78 + } + ], "source": [ - "# Indexing goes outer to inner...\n", - "TENSOR[0][0]" + "# Create a tensor \n", + "import torch\n", + "x = torch.arange(1, 10).reshape(1, 3, 3)\n", + "x, x.shape" ] }, + { + "cell_type": "markdown", + "source": [ + "Indexing values goes outer dimension -> inner dimension (check out the square brackets)." + ], + "metadata": { + "id": "xQG5krnKG43B" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 72, "metadata": { "id": "zv_Z3IAzTGfD", - "outputId": "7dd2d749-7c2f-4fbf-f16b-b705ed24b770" + "outputId": "95cacaa6-586e-4ae8-9bee-279c8c56c818", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { - "data": { - "text/plain": [ - "tensor([[[0, 1, 2],\n", - " [3, 4, 5],\n", - " [6, 7, 8]]])" - ] - }, - "execution_count": 64, - "metadata": {}, - "output_type": "execute_result" + "output_type": "stream", + "name": "stdout", + "text": [ + "First square bracket:\n", + "tensor([[1, 2, 3],\n", + " [4, 5, 6],\n", + " [7, 8, 9]])\n", + "Second square bracket: tensor([1, 2, 3])\n", + "Third square bracket: 1\n" + ] } ], "source": [ - "import torch\n", - "tensor = torch.arange(0, 9, 1).view(1, 3, 3)\n", - "tensor" + "# Let's index bracket by bracket\n", + "print(f\"First square bracket:\\n{x[0]}\") \n", + "print(f\"Second square bracket: {x[0][0]}\") \n", + "print(f\"Third square bracket: {x[0][0][0]}\")" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", + "source": [ + "You can also use `:` to specify \"all values in this dimension\" and then use a comma (`,`) to add another dimension." + ], "metadata": { - "id": "BuKrGOvBTGfD", - "outputId": "a73878e7-ef80-4da9-8d38-ac20a3cc2085" - }, - "outputs": [ - { - "data": { - "text/plain": [ - "tensor([[0, 1, 2],\n", - " [3, 4, 5],\n", - " [6, 7, 8]])" - ] - }, - "execution_count": 65, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "tensor[0]" - ] + "id": "XaLjaIFxHe89" + } }, { "cell_type": "code", - "execution_count": null, + "execution_count": 77, "metadata": { "id": "gCT09pqeTGfD", - "outputId": "621490ff-773f-450f-99df-dad374819eb4" + "outputId": "a7eb3481-1bdf-4eca-bfe3-4c1d894543b9", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "tensor([[0, 1, 2]])" + "tensor([[1, 2, 3]])" ] }, - "execution_count": 66, "metadata": {}, - "output_type": "execute_result" + "execution_count": 77 } ], "source": [ - "tensor[:, 0]" + "# Get all values of 0th dimension and the 0 index of 1st dimension\n", + "x[:, 0]" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 79, "metadata": { "id": "dwDx_gMsTGfD", - "outputId": "9cde0d76-4254-476d-d287-287bbbb8f787" + "outputId": "9fd40d00-3283-4299-e62d-bd19840cbe19", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "tensor([[1, 4, 7]])" + "tensor([[2, 5, 8]])" ] }, - "execution_count": 67, "metadata": {}, - "output_type": "execute_result" + "execution_count": 79 } ], "source": [ - "tensor[:, :, 1]" + "# Get all values of 0th & 1st dimensions but only index 1 of 2nd dimension\n", + "x[:, :, 1]" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 75, "metadata": { "id": "xiw3_1E3TGfD", - "outputId": "3164c108-4d2a-44cf-b0cf-da84de63aea3" + "outputId": "afbba395-3cc5-4230-f82c-f17f9007a6d1", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "tensor([4])" + "tensor([5])" ] }, - "execution_count": 68, "metadata": {}, - "output_type": "execute_result" + "execution_count": 75 } ], "source": [ - "tensor[:, 1, 1]" + "# Get all values of the 0 dimension but only the 1 index value of the 1st and 2nd dimension\n", + "x[:, 1, 1]" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 81, "metadata": { "id": "XFVEgrKhTGfD", - "outputId": "24500ee4-f6d9-47f7-dbd9-1e24b5a9993f" + "outputId": "aca47cf7-eb40-4e79-9dc8-dbc1fba2da8b", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "tensor([[0, 3, 6]])" + "tensor([1, 2, 3])" ] }, - "execution_count": 69, "metadata": {}, - "output_type": "execute_result" + "execution_count": 81 } ], "source": [ - "tensor[:, :, 0]" + "# Get index 0 of 0th and 1st dimension and all values of 2nd dimension \n", + "x[0, 0, :] # same as x[0][0]" ] }, + { + "cell_type": "markdown", + "source": [ + "Indexing can be quite confusing to begin with, especially with larger tensors (I still have to try indexing multiple times to get it right). But with a bit of practice and following the data explorer's motto (***visualize, visualize, visualize***), you'll start to get the hang of it." + ], + "metadata": { + "id": "6Ik0r11RIxtm" + } + }, { "cell_type": "markdown", "metadata": { "id": "h8ZaW0Bq7rCm" }, "source": [ - "## TK - PyTorch tensors & NumPy" + "## TK - PyTorch tensors & NumPy\n", + "\n", + "Since NumPy is a very popular Python numerical computing library, PyTorch has functionality to interact with it nicely. \n", + "\n", + "The two main methods you'll want to use for NumPy to PyTorch (and back again) are: \n", + "* [`torch.from_numpy(ndarray)`](https://pytorch.org/docs/stable/generated/torch.from_numpy.html) - NumPy array -> PyTorch tensor. \n", + "* [`torch.Tensor.numpy()`](https://pytorch.org/docs/stable/generated/torch.Tensor.numpy.html) - PyTorch tensor -> NumPy array.\n", + "\n", + "Let's try them out." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 91, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "yDrDCnvY7rKS", - "outputId": "0344f8be-632b-40d9-9d48-afdeebf1b804" + "outputId": "4ee42d42-dbf6-4c29-f172-52fab20a4907" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "(array([1, 2, 3, 4, 5, 6, 7]), tensor([1, 2, 3, 4, 5, 6, 7]))" + "(array([1., 2., 3., 4., 5., 6., 7.]),\n", + " tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64))" ] }, - "execution_count": 130, "metadata": {}, - "output_type": "execute_result" + "execution_count": 91 } ], "source": [ "# NumPy array to tensor\n", + "import torch\n", "import numpy as np\n", - "array = np.arange(1, 8)\n", + "array = np.arange(1.0, 8.0)\n", "tensor = torch.from_numpy(array)\n", "array, tensor" ] }, + { + "cell_type": "markdown", + "source": [ + "> **Note:** By default, NumPy arrays are created with the datatype `float64` and if you convert it to a PyTorch tensor, it'll keep the same datatype (as above). \n", + ">\n", + "> However, many PyTorch calculations default to using `float32`. \n", + "> \n", + "> So if you want to convert your NumPy array (float64) -> PyTorch tensor (float64) -> PyTorch tensor (float32), you can use `tensor = torch.from_numpy(array).type(torch.float32)`.\n", + "\n", + "Because we reassigned `tensor` above, if you change the tensor, the array stays the same." + ], + "metadata": { + "id": "16JG6cONLPnO" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 92, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ovwl7VCREv8L", - "outputId": "5c91968e-a9f9-4434-d950-a22a78d5a12e" + "outputId": "b7934817-4ff5-4892-9f8e-9af92f623a53" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "(array([2, 3, 4, 5, 6, 7, 8]), tensor([1, 2, 3, 4, 5, 6, 7]))" + "(array([2., 3., 4., 5., 6., 7., 8.]),\n", + " tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64))" ] }, - "execution_count": 131, "metadata": {}, - "output_type": "execute_result" + "execution_count": 92 } ], "source": [ @@ -2714,57 +2933,75 @@ "array, tensor" ] }, + { + "cell_type": "markdown", + "source": [ + "And if you want to go from PyTorch tensor to NumPy array, you can call `tensor.numpy()`." + ], + "metadata": { + "id": "geVvu1p0MTWc" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 93, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "xw_7ZyVaTKxQ", - "outputId": "340fc9a4-2a46-48af-fd9e-1bc1d6d6c7e5" + "outputId": "85d4c35c-09e4-48ac-f481-5e48708b684f" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ "(tensor([1., 1., 1., 1., 1., 1., 1.]),\n", " array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))" ] }, - "execution_count": 134, "metadata": {}, - "output_type": "execute_result" + "execution_count": 93 } ], "source": [ "# Tensor to NumPy array\n", - "tensor = torch.ones(7)\n", - "numpy_tensor = tensor.numpy()\n", + "tensor = torch.ones(7) # create a tensor of ones with dtype=float32\n", + "numpy_tensor = tensor.numpy() # will be dtype=float32 unless changed\n", "tensor, numpy_tensor" ] }, + { + "cell_type": "markdown", + "source": [ + "And the same rule applies as above, if you change the original `tensor`, the new `numpy_tensor` stays the same." + ], + "metadata": { + "id": "Dt8yEV1jMfi2" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 94, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "mMp6ZSkET4_Y", - "outputId": "a9d5e467-b35e-4aca-b1d7-3fc7034ebd20" + "outputId": "a32b32fa-f3c0-4966-a945-5f660cc029c8" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ "(tensor([2., 2., 2., 2., 2., 2., 2.]),\n", " array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))" ] }, - "execution_count": 135, "metadata": {}, - "output_type": "execute_result" + "execution_count": 94 } ], "source": [ @@ -2779,23 +3016,71 @@ "id": "7gU3ubCrUkI-" }, "source": [ - "## TK - Reproducibility\n", + "## TK - Reproducibility (trying to take the random out of random)\n", "\n", - "* Create tensors with same values...\n", - "* Show PyTorch random seed so we can all use similar values\n", + "As you learn more about neural networks and machine learning, you'll start to discover how much randomness plays a part.\n", "\n", - "See: https://pytorch.org/docs/stable/notes/randomness.html" + "Well, pseudorandomness that is. Because after all, as they're designed, a computer is fundamentally deterministic (each step is predictable) so the randomness they create are simulated randomness (though there is debate on this too, but since I'm not a computer scientist, I'll let you find out more yourself).\n", + "\n", + "How does this relate to neural networks and deep learning then?\n", + "\n", + "We've discussed neural networks start with random numbers to describe patterns in data (these numbers are poor descriptions) and try to improve those random numbers using tensor operations (and a few other things we haven't discussed yet) to better describe patterns in data.\n", + "\n", + "In short: \n", + "\n", + "``start with random numbers -> tensor operations -> try to make better (again and again and again)``\n", + "\n", + "Although randomness is nice and powerful, sometimes you'd like there to be a little less randomness.\n", + "\n", + "Why?\n", + "\n", + "So you can perform repeatable experiments.\n", + "\n", + "For example, you create an algorithm capable of achieving X performance.\n", + "\n", + "And then your friend tries it out to verify you're not crazy.\n", + "\n", + "How could they do such a thing?\n", + "\n", + "That's where **reproducibility** comes in.\n", + "\n", + "In other words, can you get the same (or very similar) results on your computer running the same code as I get on mine?\n", + "\n", + "Let's see a brief example of reproducibility in PyTorch.\n", + "\n", + "We'll start by creating two random tensors, since they're random, you'd expect them to be different right? " ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 99, "metadata": { "id": "eSwxnwEbTGfF", - "outputId": "f0e7734a-0e53-429c-a234-f4e28d4af087" + "outputId": "b487fc83-2db5-4009-d991-3731eb53c3e6", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { + "output_type": "stream", + "name": "stdout", + "text": [ + "Tensor A:\n", + "tensor([[0.8694, 0.5677, 0.7411, 0.4294],\n", + " [0.8854, 0.5739, 0.2666, 0.6274],\n", + " [0.2696, 0.4414, 0.2969, 0.8317]])\n", + "\n", + "Tensor B:\n", + "tensor([[0.1053, 0.2695, 0.3588, 0.1994],\n", + " [0.5472, 0.0062, 0.9516, 0.0753],\n", + " [0.8860, 0.5832, 0.3376, 0.8090]])\n", + "\n", + "Does Tensor A equal Tensor B? (anywhere)\n" + ] + }, + { + "output_type": "execute_result", "data": { "text/plain": [ "tensor([[False, False, False, False],\n", @@ -2803,30 +3088,70 @@ " [False, False, False, False]])" ] }, - "execution_count": 32, "metadata": {}, - "output_type": "execute_result" + "execution_count": 99 } ], "source": [ - "# No seed\n", "import torch\n", "\n", + "# Create two random tensors\n", "random_tensor_A = torch.rand(3, 4)\n", "random_tensor_B = torch.rand(3, 4)\n", "\n", + "print(f\"Tensor A:\\n{random_tensor_A}\\n\")\n", + "print(f\"Tensor B:\\n{random_tensor_B}\\n\")\n", + "print(f\"Does Tensor A equal Tensor B? (anywhere)\")\n", "random_tensor_A == random_tensor_B" ] }, + { + "cell_type": "markdown", + "source": [ + "Just as you might've expected, the tensors come out with different values.\n", + "\n", + "But what if you wanted to created two random tensors with the *same* values.\n", + "\n", + "As in, the tensors would still contain random values but they would be of the same flavour.\n", + "\n", + "That's where [`torch.manual_seed(seed)`](https://pytorch.org/docs/stable/generated/torch.manual_seed.html) comes in, where `seed` is an integer (like `42` but it could be anything) that flavours the randomness.\n", + "\n", + "Let's try it out by creating some more *flavoured* random tensors." + ], + "metadata": { + "id": "nPU6mDKJnr8M" + } + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 109, "metadata": { "id": "sB6d1GfYTGfF", - "outputId": "6241f9c6-570a-4355-f92f-34a9f3608011" + "outputId": "6dcd5264-c8be-4091-e15a-b17b2b3b3e2b", + "colab": { + "base_uri": "https://localhost:8080/" + } }, "outputs": [ { + "output_type": "stream", + "name": "stdout", + "text": [ + "Tensor C:\n", + "tensor([[0.8823, 0.9150, 0.3829, 0.9593],\n", + " [0.3904, 0.6009, 0.2566, 0.7936],\n", + " [0.9408, 0.1332, 0.9346, 0.5936]])\n", + "\n", + "Tensor D:\n", + "tensor([[0.8823, 0.9150, 0.3829, 0.9593],\n", + " [0.3904, 0.6009, 0.2566, 0.7936],\n", + " [0.9408, 0.1332, 0.9346, 0.5936]])\n", + "\n", + "Does Tensor C equal Tensor D? (anywhere)\n" + ] + }, + { + "output_type": "execute_result", "data": { "text/plain": [ "tensor([[True, True, True, True],\n", @@ -2834,33 +3159,76 @@ " [True, True, True, True]])" ] }, - "execution_count": 40, "metadata": {}, - "output_type": "execute_result" + "execution_count": 109 } ], "source": [ - "# With seed\n", "import torch\n", + "import random\n", "\n", - "# Set the random seed\n", - "torch.random.manual_seed(42)\n", + "# # Set the random seed\n", + "RANDOM_SEED=42 # try changing this to different values and see what happens to the numbers below\n", + "torch.manual_seed(seed=RANDOM_SEED) \n", "random_tensor_C = torch.rand(3, 4)\n", "\n", "# Have to reset the seed every time a new rand() is called \n", - "torch.random.manual_seed(42) # Without this, tensor_D would be different to tensor_C\n", + "# Without this, tensor_D would be different to tensor_C \n", + "torch.random.manual_seed(seed=RANDOM_SEED) # try commenting this line out and seeing what happens\n", "random_tensor_D = torch.rand(3, 4)\n", "\n", - "random_tensor_C == random_tensor_D\n" + "print(f\"Tensor C:\\n{random_tensor_C}\\n\")\n", + "print(f\"Tensor D:\\n{random_tensor_D}\\n\")\n", + "print(f\"Does Tensor C equal Tensor D? (anywhere)\")\n", + "random_tensor_C == random_tensor_D" ] }, + { + "cell_type": "markdown", + "source": [ + "Nice!\n", + "\n", + "It looks like setting the seed worked. \n", + "\n", + "> **Resource:** What we've just covered only scratches the surface of reproducibility in PyTorch. For more, on reproducbility in general and random seeds, I'd checkout:\n", + "> * [The PyTorch reproducibility documentation](https://pytorch.org/docs/stable/notes/randomness.html) (a good exericse would be to read through this for 10-minutes and even if you don't understand it now, being aware of it is important).\n", + "> * [The Wikipedia random seed page](https://en.wikipedia.org/wiki/Random_seed) (this'll give a good overview of random seeds and pseudorandomness in general)." + ], + "metadata": { + "id": "uct53Xr5QRC_" + } + }, { "cell_type": "markdown", "metadata": { "id": "hxIIM7t27rQ-" }, "source": [ - "## TK - Running tensors on GPUs \n", + "## TK - Running tensors on GPUs (and making faster computations)\n", + "\n", + "Deep learning algorithms require a lot of numerical operations.\n", + "\n", + "And by default these operations are often done on a CPU (computer processing unit).\n", + "\n", + "However, there's another common piece of hardware called a GPU (graphics processing unit), which is often much faster at performing the specific types of operations neural networks need (matrix multiplications) than CPUs.\n", + "\n", + "Your computer might have one.\n", + "\n", + "If so, you should look to use it whenever you can to train neural networks because chances are it'll speed up the training time dramatically.\n", + "\n", + "There are a few ways to first get access to a GPU and secondly get PyTorch to use the GPU.\n", + "\n", + "> **Note:** When I reference \"GPU\" throughout this course, I'm referencing a [Nvidia GPU with CUDA](https://developer.nvidia.com/cuda-gpus) enabled (CUDA helps speed up computations) unless otherwise specified.\n", + "\n", + "### Getting a GPU\n", + "\n", + "UPTOHERE: To get a GPU, you'll either have one installed on your machine \n", + "\n", + "* TK - colab, cloud computing...\n", + "* TK - fast.ai access to a GPU...\n", + "* TK - insert methods for installing PyTorch... \n", + "\n", + "---\n", "\n", "The cuda module is what you'll want:\n", "\n", @@ -2870,24 +3238,24 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 104, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "OweDLgwjEvZ2", - "outputId": "959a6350-9eee-4a02-d66c-1a870f9f1d9b" + "outputId": "4102cb3e-6dfd-4dae-e27c-ccc1faba15d6" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "True" + "False" ] }, - "execution_count": 70, "metadata": {}, - "output_type": "execute_result" + "execution_count": 104 } ], "source": [ @@ -3148,8 +3516,8 @@ }, "source": [ "UPTOHERE:\n", + "* TK - manaul seed on the GPU \n", "* Fix up section for .cpu() and .detach() to make it clearer\n", - "* add in scatter (for changing values)\n", "* go back through headings and make sure cells are complete \n" ] }, @@ -3162,17 +3530,8 @@ "## TK - Exercises\n", "## TK - Extra-curriculum\n", "\n", - "* [read through the documentation on `torch.Tensor`](https://pytorch.org/docs/stable/generated/torch.tensor.html#torch.tensor) for 10-minutes.\n", - "* to learn more on how a tensor can represent data, see this video: [What's a tensor?](https://youtu.be/f5liqUk0ZTw)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "DAeNflY9TGfI" - }, - "source": [ - "" + "* [Read through the documentation on `torch.Tensor`](https://pytorch.org/docs/stable/generated/torch.tensor.html#torch.tensor) for 10-minutes.\n", + "* To learn more on how a tensor can represent data, see this video: [What's a tensor?](https://youtu.be/f5liqUk0ZTw)" ] } ],