{ "cells": [ { "cell_type": "code", "execution_count": 10, "id": "3de75f13-7140-4572-a254-dcd42018420c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "PyTorch 版本: 2.5.0\n", "CUDA 是否可用: True\n", "NumPy 版本: 1.26.4\n", "pandas 版本: 2.2.2\n", "Matplotlib 版本: 3.9.2\n", "python版本: 3.12.7\n" ] } ], "source": [ "# 測試 PyTorch\n", "import torch\n", "print(\"PyTorch 版本:\", torch.__version__)\n", "print(\"CUDA 是否可用:\", torch.cuda.is_available())\n", "\n", "# 測試 NumPy、pandas Matplotlib和 python\n", "import platform\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "print(\"NumPy 版本:\", np.__version__)\n", "print(\"pandas 版本:\", pd.__version__)\n", "print(\"Matplotlib 版本:\", plt.matplotlib.__version__)\n", "print(\"python版本:\", platform.python_version())" ] }, { "cell_type": "code", "execution_count": 2, "id": "eebe468a-a38c-4ae2-a1f5-43aa57e8d47f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "當前使用的 GPU: NVIDIA GeForce RTX 3080\n" ] } ], "source": [ "if torch.cuda.is_available():\n", " device = torch.device(\"cuda\")\n", " print(\"當前使用的 GPU:\", torch.cuda.get_device_name(0))\n", "else:\n", " print(\"CUDA 不可用,只能使用 CPU\")" ] }, { "cell_type": "code", "execution_count": 4, "id": "fcedf100-cfed-418b-ba50-7f4bebac5081", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sun Oct 27 19:54:58 2024 \n", "+-----------------------------------------------------------------------------------------+\n", "| NVIDIA-SMI 566.03 Driver Version: 566.03 CUDA Version: 12.7 |\n", "|-----------------------------------------+------------------------+----------------------+\n", "| GPU Name Driver-Model | Bus-Id Disp.A | Volatile Uncorr. ECC |\n", "| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n", "| | | MIG M. |\n", "|=========================================+========================+======================|\n", "| 0 NVIDIA GeForce RTX 3080 WDDM | 00000000:2D:00.0 On | N/A |\n", "| 0% 40C P8 33W / 350W | 1489MiB / 12288MiB | 18% Default |\n", "| | | N/A |\n", "+-----------------------------------------+------------------------+----------------------+\n", " \n", "+-----------------------------------------------------------------------------------------+\n", "| Processes: |\n", "| GPU GI CI PID Type Process name GPU Memory |\n", "| ID ID Usage |\n", "|=========================================================================================|\n", "| 0 N/A N/A 660 C+G ...1.0_x64__8wekyb3d8bbwe\\Video.UI.exe N/A |\n", "| 0 N/A N/A 5808 C+G ...les\\Microsoft OneDrive\\OneDrive.exe N/A |\n", "| 0 N/A N/A 6268 C+G ...__8wekyb3d8bbwe\\Notepad\\Notepad.exe N/A |\n", "| 0 N/A N/A 7864 C+G ...ata\\Local\\LINE\\bin\\current\\LINE.exe N/A |\n", "| 0 N/A N/A 8360 C+G C:\\Windows\\explorer.exe N/A |\n", "| 0 N/A N/A 10268 C+G ...nt.CBS_cw5n1h2txyewy\\SearchHost.exe N/A |\n", "| 0 N/A N/A 10292 C+G ...2txyewy\\StartMenuExperienceHost.exe N/A |\n", "| 0 N/A N/A 11612 C+G ...siveControlPanel\\SystemSettings.exe N/A |\n", "| 0 N/A N/A 12780 C+G ...CBS_cw5n1h2txyewy\\TextInputHost.exe N/A |\n", "| 0 N/A N/A 13556 C+G ...Brave-Browser\\Application\\brave.exe N/A |\n", "| 0 N/A N/A 14224 C+G ...5n1h2txyewy\\ShellExperienceHost.exe N/A |\n", "| 0 N/A N/A 15860 C+G ...nt.CBS_cw5n1h2txyewy\\SearchHost.exe N/A |\n", "| 0 N/A N/A 17692 C+G ...ekyb3d8bbwe\\PhoneExperienceHost.exe N/A |\n", "| 0 N/A N/A 18484 C+G ...crosoft\\Edge\\Application\\msedge.exe N/A |\n", "| 0 N/A N/A 19380 C+G ...Brave-Browser\\Application\\brave.exe N/A |\n", "+-----------------------------------------------------------------------------------------+\n" ] } ], "source": [ "!nvidia-smi" ] }, { "cell_type": "code", "execution_count": 1, "id": "48811db2-a0ff-463e-9a04-2a257b81626d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "執行時間: 157.84243774414062 毫秒\n" ] } ], "source": [ "import torch\n", "import time\n", "\n", "# 確認是否有 GPU 設備\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "# 設定開始和結束的事件\n", "start = torch.cuda.Event(enable_timing=True)\n", "end = torch.cuda.Event(enable_timing=True)\n", "\n", "# 開始計時\n", "start.record()\n", "\n", "# 執行矩陣相乘\n", "x = torch.rand(10000, 10000, device=device)\n", "y = torch.rand(10000, 10000, device=device)\n", "z = torch.matmul(x, y)\n", "\n", "# 結束計時\n", "end.record()\n", "\n", "# 等待所有 CUDA 操作完成\n", "torch.cuda.synchronize()\n", "\n", "# 計算經過時間(以毫秒為單位)\n", "elapsed_time = start.elapsed_time(end)\n", "print(f\"執行時間: {elapsed_time} 毫秒\")\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "fff14081-0aa0-4577-8dd1-70b0b40f57ed", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "執行時間: 98.69107055664062 毫秒\n" ] } ], "source": [ "# 指定使用 GPU\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "# 設定 CUDA 的計時事件\n", "start = torch.cuda.Event(enable_timing=True)\n", "end = torch.cuda.Event(enable_timing=True)\n", "\n", "# 開始計時\n", "start.record()\n", "\n", "# 執行矩陣相乘\n", "x = torch.rand(10000, 10000, device=device)\n", "y = torch.rand(10000, 10000, device=device)\n", "z = torch.matmul(x, y)\n", "\n", "# 結束計時\n", "end.record()\n", "\n", "# 等待所有 CUDA 操作完成\n", "torch.cuda.synchronize()\n", "\n", "# 計算經過時間(以毫秒為單位)\n", "elapsed_time = start.elapsed_time(end)\n", "print(f\"執行時間: {elapsed_time} 毫秒\")" ] }, { "cell_type": "code", "execution_count": 4, "id": "61846cfc-dcdf-4e93-8698-b361540ec84f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Set device type\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "# Count number of devices\n", "torch.cuda.device_count()" ] }, { "cell_type": "code", "execution_count": 5, "id": "f0ac6491-24fd-45d3-aa0f-9f40cef256ad", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor([1, 2, 3]) cpu\n" ] }, { "data": { "text/plain": [ "tensor([1, 2, 3], device='cuda:0')" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create tensor (default on CPU)\n", "tensor = torch.tensor([1, 2, 3])\n", "\n", "# Tensor not on GPU\n", "print(tensor, tensor.device)\n", "\n", "# Move tensor to GPU (if available)\n", "tensor_on_gpu = tensor.to(device)\n", "tensor_on_gpu" ] }, { "cell_type": "code", "execution_count": 6, "id": "0df45458-e9e2-4213-a692-64a11166c6ce", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[6], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# If tensor is on GPU, can't transform it to NumPy (this will error)\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m tensor_on_gpu\u001b[38;5;241m.\u001b[39mnumpy()\n", "\u001b[1;31mTypeError\u001b[0m: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first." ] } ], "source": [ "# If tensor is on GPU, can't transform it to NumPy (this will error)\n", "tensor_on_gpu.numpy()\n", "# NumPy does not leverage the GPU" ] }, { "cell_type": "code", "execution_count": 7, "id": "cce66a6e-5bf9-45d6-bf82-32e42e1e689c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([1, 2, 3], dtype=int64)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Instead, copy the tensor back to cpu\n", "tensor_back_on_cpu = tensor_on_gpu.cpu().numpy()\n", "tensor_back_on_cpu" ] }, { "cell_type": "code", "execution_count": 8, "id": "8833452a-9db2-4c7b-a739-9c3632d5fe69", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tensor(7)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Scalar\n", "scalar = torch.tensor(7)\n", "scalar" ] }, { "cell_type": "code", "execution_count": 9, "id": "835a965b-6990-4dfb-b9a9-ea8012031ddd", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "scalar.ndim" ] }, { "cell_type": "code", "execution_count": 10, "id": "6eba4e4e-d399-4b4f-b021-78897eb7656e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tensor([7, 7])" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Vector\n", "vector = torch.tensor([7, 7])\n", "vector" ] }, { "cell_type": "code", "execution_count": 11, "id": "6d2cfdfe-150c-44c1-ad56-22d51f34ca4b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check the number of dimensions of vector\n", "vector.ndim" ] }, { "cell_type": "code", "execution_count": 12, "id": "4234de6e-0dff-4ad6-9c51-f4808cd8b376", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(torch.Size([2]), torch.Size([]))" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check shape of vector\n", "vector.shape, scalar.shape" ] }, { "cell_type": "code", "execution_count": 13, "id": "60f0cc6a-d04f-41af-ad19-763e9214485d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2, torch.Size([2, 2]))" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Matrix\n", "MATRIX = torch.tensor([[7, 8], \n", " [9, 10]])\n", "MATRIX.ndim, MATRIX.shape" ] }, { "cell_type": "code", "execution_count": 14, "id": "2b308352-f9d5-4d92-8f0f-5ac8d6fb84ee", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3, torch.Size([1, 3, 3]))" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Tensor\n", "TENSOR = torch.tensor([[[1, 2, 3],\n", " [3, 6, 9],\n", " [2, 4, 5]]])\n", "TENSOR.ndim, TENSOR.shape" ] }, { "cell_type": "code", "execution_count": 15, "id": "393fdaea-fe4a-4e91-a76d-dde715fb0a04", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(torch.Size([224, 224, 3]), 3)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a random tensor of size (224, 224, 3)\n", "random_image_size_tensor = torch.rand(size=(224, 224, 3))\n", "random_image_size_tensor.shape, random_image_size_tensor.ndim" ] }, { "cell_type": "code", "execution_count": 16, "id": "cbda99ba-03cc-4196-a9ca-113af3284809", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(torch.Size([3]), torch.float32, device(type='cpu'))" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Default datatype for tensors is float32\n", "float_32_tensor = torch.tensor([3.0, 6.0, 9.0],\n", " dtype=None, # defaults to None, which is torch.float32 or whatever datatype is passed\n", " device=None, # defaults to None, which uses the default tensor type\n", " requires_grad=False) # if True, operations performed on the tensor are recorded \n", "\n", "float_32_tensor.shape, float_32_tensor.dtype, float_32_tensor.device" ] }, { "cell_type": "code", "execution_count": 17, "id": "eddf8eee-e6e7-4b97-a71d-6c3afbb50328", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor([[0.7984, 0.3269, 0.3039, 0.2807],\n", " [0.0025, 0.2863, 0.5769, 0.3109],\n", " [0.1705, 0.5987, 0.8661, 0.6635]])\n", "Shape of tensor: torch.Size([3, 4])\n", "Datatype of tensor: torch.float32\n", "Device tensor is stored on: cpu\n" ] } ], "source": [ "# Create a tensor\n", "some_tensor = torch.rand(3, 4)\n", "\n", "# Find out details about it\n", "print(some_tensor)\n", "print(f\"Shape of tensor: {some_tensor.shape}\")\n", "print(f\"Datatype of tensor: {some_tensor.dtype}\")\n", "print(f\"Device tensor is stored on: {some_tensor.device}\") # will default to CPU" ] }, { "cell_type": "code", "execution_count": 19, "id": "1294e9fd-e6f7-46f5-bd8f-091569c11f92", "metadata": {}, "outputs": [], "source": [ "# Shapes need to be in the right way \n", "tensor_A = torch.tensor([[1, 2],\n", " [3, 4],\n", " [5, 6]], dtype=torch.float32)\n", "\n", "tensor_B = torch.tensor([[7, 10],\n", " [8, 11], \n", " [9, 12]], dtype=torch.float32)" ] }, { "cell_type": "code", "execution_count": 20, "id": "ca005cae-2ad5-4a99-9391-8c5a0c8d7714", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor([[1., 2.],\n", " [3., 4.],\n", " [5., 6.]])\n", "tensor([[ 7., 10.],\n", " [ 8., 11.],\n", " [ 9., 12.]])\n" ] } ], "source": [ "# View tensor_A and tensor_B\n", "print(tensor_A)\n", "print(tensor_B)" ] }, { "cell_type": "code", "execution_count": 21, "id": "e43b936a-4baa-40c7-ad02-f2cb6158ea8c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tensor([[1., 2.],\n", " [3., 4.],\n", " [5., 6.]])\n", "tensor([[ 7., 8., 9.],\n", " [10., 11., 12.]])\n" ] } ], "source": [ "# View tensor_A and tensor_B.T\n", "print(tensor_A)\n", "print(tensor_B.T)" ] }, { "cell_type": "code", "execution_count": 22, "id": "d3a9dae7-c0a9-4967-9af4-ee77688810a9", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tensor([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a tensor\n", "x = torch.arange(0, 100, 10)\n", "x" ] }, { "cell_type": "code", "execution_count": 23, "id": "3e8a01e5-afa2-4307-99ff-a18f040b920d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Minimum: 0\n", "Maximum: 90\n", "Mean: 45.0\n", "Sum: 450\n" ] } ], "source": [ "print(f\"Minimum: {x.min()}\")\n", "print(f\"Maximum: {x.max()}\")\n", "# print(f\"Mean: {x.mean()}\") # this will error\n", "print(f\"Mean: {x.type(torch.float32).mean()}\") # won't work without float datatype\n", "print(f\"Sum: {x.sum()}\")" ] }, { "cell_type": "code", "execution_count": 24, "id": "5d079a9a-3f01-4299-ade6-8f21e9cb0ff5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Tensor: tensor([10, 20, 30, 40, 50, 60, 70, 80, 90])\n", "Index where max value occurs: 8\n", "Index where min value occurs: 0\n" ] } ], "source": [ "# Create a tensor\n", "tensor = torch.arange(10, 100, 10)\n", "print(f\"Tensor: {tensor}\")\n", "\n", "# Returns index of max and min values\n", "print(f\"Index where max value occurs: {tensor.argmax()}\")\n", "print(f\"Index where min value occurs: {tensor.argmin()}\")" ] }, { "cell_type": "code", "execution_count": 28, "id": "e4c4e47f-460f-4d84-a73f-3fc88915d7b3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(tensor([1., 2., 3., 4., 5., 6., 7.]), torch.Size([7]))" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = torch.arange(1., 8.)\n", "x, x.shape" ] }, { "cell_type": "code", "execution_count": 29, "id": "89b7318b-4aa5-4218-b3ca-cce6eb85c882", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Add an extra dimension\n", "x_reshaped = x.reshape(1, 7)\n", "x_reshaped, x_reshaped.shape" ] }, { "cell_type": "code", "execution_count": 31, "id": "0e7d8f0c-d1da-40ef-bee4-21531f1d2389", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z = x.view(1, 7)\n", "z, z.shape" ] }, { "cell_type": "code", "execution_count": 35, "id": "ae52e298-5c91-4f97-b75c-06d2a9c5d63f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(tensor([[5., 2., 3., 4., 5., 6., 7.]]), tensor([5., 2., 3., 4., 5., 6., 7.]))" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Changing z changes x\n", "z[:, 0] = 5\n", "z, x" ] }, { "cell_type": "code", "execution_count": 34, "id": "8e3533cc-93b3-4d8d-b686-fe219be03ee0", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tensor([[5., 2., 3., 4., 5., 6., 7.],\n", " [5., 2., 3., 4., 5., 6., 7.],\n", " [5., 2., 3., 4., 5., 6., 7.],\n", " [5., 2., 3., 4., 5., 6., 7.]])" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Stack tensors on top of each other\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": "code", "execution_count": null, "id": "73b9a862-afaf-4e54-b21d-9a147547d930", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.12.7" } }, "nbformat": 4, "nbformat_minor": 5 }