{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  },
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# PyTorch ile Derin Öğrenme · Tensörler: şekil, veri tipi, yayınlama ve cihaz\n",
    "\n",
    "Macademia · Büyükler için"
   ],
   "id": "c00"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> **Colab'da çalıştırma:** Bu dosyayı [colab.research.google.com](https://colab.research.google.com) adresinde **Dosya → Not defteri yükle** ile aç. GPU için **Çalışma zamanı → Çalışma zamanı türünü değiştir → T4 GPU** seç. Hücreleri yukarıdan aşağı sırayla çalıştır (Shift + Enter). PyTorch Colab'da kuruludur; bilgisayarında çalıştırmak istersen `pip install torch torchvision`."
   ],
   "id": "c01"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch, random, numpy as np\n",
    "torch.manual_seed(0); random.seed(0); np.random.seed(0)          # tekrarlanabilirlik\n",
    "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
    "print('PyTorch', torch.__version__, '| device:', device)"
   ],
   "id": "c02"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Tensör oluşturma\n",
    "Tensör, çok boyutlu bir sayı dizisidir. Şekli (`shape`), veri tipi (`dtype`) ve cihazı (`device`) vardır."
   ],
   "id": "c03"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = torch.arange(12, dtype=torch.float32).reshape(3, 4)\n",
    "print(x)\n",
    "print(x.shape, x.dtype, x.device)\n",
    "z = torch.zeros(2, 3); o = torch.ones(2, 3); r = torch.randn(2, 3)   # sıfırlar, birler, normal dağılım\n",
    "print(torch.from_numpy(np.array([1, 2, 3])).dtype)                  # NumPy'dan: int64"
   ],
   "id": "c04"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Dilimleme\n",
    "`x[satır, sütun]`; dilim bir **görünümdür** (kopya değildir)."
   ],
   "id": "c05"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(x[0], x[:, 1], x[1:, 2:])\n",
    "v = x[0]; v[0] = 100                                                 # görünüm: x de değişir\n",
    "print(x[0, 0])"
   ],
   "id": "c06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Yayınlama\n",
    "Boyutlar **sağdan** hizalanır; her çift eşit olmalı ya da biri 1 olmalı."
   ],
   "id": "c07"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = torch.ones(8, 1, 6, 1); b = torch.ones(7, 1, 5)\n",
    "print((a + b).shape)                                                 # torch.Size([8, 7, 6, 5])\n",
    "pred, target = torch.randn(64), torch.randn(64, 1)\n",
    "print((pred - target).shape, '← sessiz hata!')         # torch.Size([64, 64])\n",
    "print((pred - target.squeeze(1)).shape)                              # doğrusu: torch.Size([64])"
   ],
   "id": "c08"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. matmul, view ve reshape"
   ],
   "id": "c09"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "W = torch.randn(4, 2)\n",
    "print((x @ W).shape)                                                 # (3,4) @ (4,2) → (3,2)\n",
    "try:\n",
    "    torch.randn(64, 784) @ torch.randn(128, 10)\n",
    "except RuntimeError as e:\n",
    "    print('RuntimeError:', e)\n",
    "t = x.T\n",
    "print(t.is_contiguous())\n",
    "try:\n",
    "    t.view(-1)\n",
    "except RuntimeError as e:\n",
    "    print('view:', str(e)[:80])\n",
    "print(t.reshape(-1).shape, t.contiguous().view(-1).shape)"
   ],
   "id": "c10"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Cihaz\n",
    "Model ve veri aynı cihazda olmalı."
   ],
   "id": "c11"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = x.to(device)\n",
    "print(x.device)\n",
    "print((x * 2).sum().item())                                          # .item(): Python sayısı"
   ],
   "id": "c12"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Alıştırmalar\n",
    "1. `(5, 1, 4) + (3, 1)` sonucunun şeklini önce kâğıtta bul, sonra dene.\n",
    "2. 4 görüntülük `(4, 3, 32, 32)` bir yığını `(4, 3072)`'ye çevir.\n",
    "3. Her satırdan kendi ortalamasını çıkar (`keepdim=True` ile)."
   ],
   "id": "c13"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Alıştırma 3 için başlangıç\n",
    "m = torch.randn(5, 4)\n",
    "centered = m - m.mean(dim=1, keepdim=True)\n",
    "print(centered.mean(dim=1))                                          # ≈ 0"
   ],
   "id": "c14"
  }
 ]
}