{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":13461564,"sourceType":"datasetVersion","datasetId":8544795}],"dockerImageVersionId":31153,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"**Problem Tanımı:** Cifar10 veriseti içerisindeki 10 farklı sınıfın sınıflandırılması\n\n**Sınıflar:** kedi, kurbağa, uçak, araba ...\n\n**Kullanılacak Deep Learning Algoritması:** CNN","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.datasets import cifar10 # our dataset\nfrom tensorflow.keras.utils import to_categorical # to apply one-hot encoding\nfrom tensorflow.keras.models import Sequential # for modelling\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D # feature extraction\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout # classification\nfrom tensorflow.keras.optimizers import RMSprop # optimizer algorithm like Adam or Gradient descent\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator # for data augmentation\n\nfrom sklearn.metrics import classification_report # for evaluating our results","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T04:51:03.961331Z","iopub.execute_input":"2025-10-22T04:51:03.961948Z","iopub.status.idle":"2025-10-22T04:51:20.055114Z","shell.execute_reply.started":"2025-10-22T04:51:03.961926Z","shell.execute_reply":"2025-10-22T04:51:20.053936Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport os\nimport pickle\nfrom tensorflow.keras.datasets import cifar10 # Sadece kontrol için gerekli, load_data kullanılmayacak\n\n# 1. Yardımcı Fonksiyon: Pickle dosyasını açar\ndef unpickle(file):\n    with open(file, 'rb') as fo:\n        # Kodun eski Python versiyonlarıyla uyumlu olması için encoding='bytes' kullanıyoruz\n        dict = pickle.load(fo, encoding='bytes') \n    return dict\n\n# 2. Ana Yükleme Fonksiyonu\ndef load_cifar10_manually(data_dir):\n    x_train_batches, y_train_batches = [], []\n    \n    # Tüm 5 eğitim dosyasını yükle\n    for i in range(1, 6):\n        file_path = os.path.join(data_dir, f'data_batch_{i}')\n        data_dict = unpickle(file_path)\n        x_train_batches.append(data_dict[b'data'])\n        y_train_batches.append(data_dict[b'labels'])\n\n    # Eğitim verilerini birleştir ve NumPy dizisine çevir\n    x_train = np.concatenate(x_train_batches)\n    y_train = np.concatenate(y_train_batches).reshape(-1, 1)\n\n    # Test dosyasını yükle\n    test_file_path = os.path.join(data_dir, 'test_batch')\n    test_dict = unpickle(test_file_path)\n    x_test = test_dict[b'data']\n    y_test = np.array(test_dict[b'labels']).reshape(-1, 1)\n\n    # Görüntüleri yeniden şekillendir: (N, 3072) -> (N, 32, 32, 3)\n    # CIFAR-10 verisi (Kanal, Yükseklik, Genişlik) formatında depolanmıştır, transpose ile (Yükseklik, Genişlik, Kanal) formatına çevrilir.\n    x_train = x_train.reshape((len(x_train), 3, 32, 32)).transpose(0, 2, 3, 1)\n    x_test = x_test.reshape((len(x_test), 3, 32, 32)).transpose(0, 2, 3, 1)\n\n    return (x_train, y_train), (x_test, y_test)\n\n# 3. Çalıştırma\nDATA_DIR = '/kaggle/input/cifar10/' # Sizin görselinize göre doğru yol\n\n(x_train, y_train), (x_test, y_test) = load_cifar10_manually(DATA_DIR)\n\n# Kontrol\nprint(f\"Eğitim Verisi Şekli: {x_train.shape}\")\nprint(f\"Eğitim Etiketleri Şekli: {y_train.shape}\")\nprint(f\"Test Verisi Şekli: {x_test.shape}\")\nprint(f\"Test Etiketleri Şekli: {y_test.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T05:34:56.485939Z","iopub.execute_input":"2025-10-22T05:34:56.486259Z","iopub.status.idle":"2025-10-22T05:34:56.916796Z","shell.execute_reply.started":"2025-10-22T05:34:56.486237Z","shell.execute_reply":"2025-10-22T05:34:56.915923Z"},"jupyter":{"source_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# verisetindeki ilk 5 değeri görselleştirme\n\nclass_labels = [\"Airplane\", \"Automobile\", \"Bird\", \"Cat\", \"Deer\", \"Dog\", \"Frog\", \"Horse\", \"Ship\", \"Truck\"]\n\nfig, axes = plt.subplots(1, 5, figsize=(25, 20)) # boyutu 25'e 20 olan, 1 satır ve 5 sütundan oluşan bir tane plot oluştur\n\nfor i in range(5):\n    axes[i].imshow(x_train[i])\n    label = class_labels[int(y_train[i])]\n    axes[i].set_title(label)\n    axes[i].axis(\"off\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T05:34:56.918445Z","iopub.execute_input":"2025-10-22T05:34:56.918701Z","iopub.status.idle":"2025-10-22T05:34:57.290594Z","shell.execute_reply.started":"2025-10-22T05:34:56.918681Z","shell.execute_reply":"2025-10-22T05:34:57.289556Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" # normalization\n\nx_train = (x_train).astype(\"float32\")/255\nx_test = (x_test).astype(\"float32\")/255\n\n# Bağımsız değişkenleri 0-1 arasına eşitlemek için 255'e bölüyoruz, çünkü resimler 0 ile 255 arasında piksel değerlerine sahip","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T05:34:57.291760Z","iopub.execute_input":"2025-10-22T05:34:57.292064Z","iopub.status.idle":"2025-10-22T05:34:57.691748Z","shell.execute_reply.started":"2025-10-22T05:34:57.292044Z","shell.execute_reply":"2025-10-22T05:34:57.690795Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# one-hot encoding\n\ny_train = to_categorical(y_train,10)\ny_test = to_categorical(y_test, 10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T05:43:24.074947Z","iopub.execute_input":"2025-10-22T05:43:24.075760Z","iopub.status.idle":"2025-10-22T05:43:24.081413Z","shell.execute_reply.started":"2025-10-22T05:43:24.075707Z","shell.execute_reply":"2025-10-22T05:43:24.080540Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# data augmentation\n\ndatagen = ImageDataGenerator(\n    rotation_range = 20,      # resmi 20 derece döndürme\n    width_shift_range = 0.2,  # resmi yatayda %20 kaydırma\n    height_shift_range = 0.2, # resmi dikeyde %20 kaydırma\n    shear_range = 0.2,        # resmi %20 rastgele açıyla eğme/yamultma\n    zoom_range = 0.2,         # resmi %20 yaklaştırma\n    horizontal_flip = True,   # resmi yatayda ters çevir\n)\n\ndatagen.fit(x_train)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T05:54:06.677027Z","iopub.execute_input":"2025-10-22T05:54:06.677897Z","iopub.status.idle":"2025-10-22T05:54:06.978884Z","shell.execute_reply.started":"2025-10-22T05:54:06.677862Z","shell.execute_reply":"2025-10-22T05:54:06.977973Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create model \n\nmodel = Sequential()\n\n# feature extraction\nmodel.add(Conv2D(32, (3,3), padding=\"same\", activation=\"relu\", input_shape=x_train.shape[1:])) # convolution katmanı\nmodel.add(MaxPooling2D(pool_size=(2,2))) # pooling katmanı\nmodel.add(Conv2D(32, (3,3), activation=\"relu\")) # tekrardan convolution katmanı\nmodel.add(Dropout(0.25)) # dropout katmanı\n\n# tekrardan aynı yapı\nmodel.add(Conv2D(64, (3,3), padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Conv2D(64, (3,3), activation=\"relu\"))\nmodel.add(Dropout(0.25))\n\n\n# classification\nmodel.add(Flatten()) # flatten katmanı - işlemlere başlamadan önce\nmodel.add(Dense(512, activation=\"relu\")) # normal neural network kısmı\nmodel.add(Dropout(0.50)) # dropout layer\nmodel.add(Dense(10, activation=\"softmax\")) # output layer - çıktı 10 tane olduğundan 10\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T06:20:32.700562Z","iopub.execute_input":"2025-10-22T06:20:32.701199Z","iopub.status.idle":"2025-10-22T06:20:32.830231Z","shell.execute_reply.started":"2025-10-22T06:20:32.701152Z","shell.execute_reply":"2025-10-22T06:20:32.829370Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model compile\n\nmodel.compile(optimizer=RMSprop(learning_rate=0.0001), loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T06:24:06.630282Z","iopub.execute_input":"2025-10-22T06:24:06.630640Z","iopub.status.idle":"2025-10-22T06:24:06.646475Z","shell.execute_reply.started":"2025-10-22T06:24:06.630617Z","shell.execute_reply":"2025-10-22T06:24:06.645615Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model training\n\nhistory = model.fit(datagen.flow(x_train, y_train, batch_size=512), epochs=10, validation_data=(x_test, y_test))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T06:26:06.161709Z","iopub.execute_input":"2025-10-22T06:26:06.162034Z","iopub.status.idle":"2025-10-22T06:37:10.136261Z","shell.execute_reply.started":"2025-10-22T06:26:06.162012Z","shell.execute_reply":"2025-10-22T06:37:10.135222Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# modelin test seti üzerinden tahminini yap\ny_pred = model.predict(x_test)\ny_pred_class = np.argmax(y_pred, axis=1)\ny_true = np.argmax(y_test, axis=1) # gerçek sınıfları al (One-Hot'tan normal etikete çevir)\n\n# classification report hesapla\nreport = classification_report(y_true, y_pred_class, target_names=class_labels)\nprint(report)\n\n# kayıp grafikleri\nplt.figure(figsize=(12, 5)) # figür boyutunu eklemek iyi olur\n\nplt.subplot(1, 2, 1) # 1 satır, 2 sütun ve 1. subplot\nplt.plot(history.history[\"loss\"], label = \"Train Loss\")\nplt.plot(history.history[\"val_loss\"], label = \"Validation Loss\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.title(\"Training and Validation Loss\")\nplt.legend()\nplt.grid()\n\n# accuracy grafikleri\nplt.subplot(1, 2, 2)\nplt.plot(history.history[\"accuracy\"], label = \"Train Accuracy\")\nplt.plot(history.history[\"val_accuracy\"], label = \"Validation Accuracy\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.title(\"Training and Validation Accuracy\")\nplt.legend()\nplt.grid()\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-22T06:37:44.374941Z","iopub.execute_input":"2025-10-22T06:37:44.375583Z","iopub.status.idle":"2025-10-22T06:37:48.499270Z","shell.execute_reply.started":"2025-10-22T06:37:44.375559Z","shell.execute_reply":"2025-10-22T06:37:48.498196Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}