{"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":"gpu","dataSources":[{"sourceId":3175,"databundleVersionId":44352,"sourceType":"competition"},{"sourceId":52787013,"sourceType":"kernelVersion"},{"sourceId":191277762,"sourceType":"kernelVersion"}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nBASE = \"/kaggle/input/galaxy-zoo-the-galaxy-challenge\"\nprint(\"BASE var mı?:\", os.path.exists(BASE))\nprint(\"BASE içeriği:\", os.listdir(BASE))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:26:32.758237Z","iopub.execute_input":"2025-09-23T10:26:32.758514Z","iopub.status.idle":"2025-09-23T10:26:32.785063Z","shell.execute_reply.started":"2025-09-23T10:26:32.758495Z","shell.execute_reply":"2025-09-23T10:26:32.784295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\n\n# Eğitim görsellerini çıkar\nzip_path = BASE + \"/images_training_rev1.zip\"\nextract_path = \"/kaggle/working/train_images\"\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)\n\nprint(\"Eğitim görselleri:\", os.listdir(extract_path)[:5])\n\n# Etiketleri çıkar\nzip_path = BASE + \"/training_solutions_rev1.zip\"\nextract_path = \"/kaggle/working/train_labels\"\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)\n\nprint(\"Etiket dosyası:\", os.listdir(extract_path))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:27:27.581038Z","iopub.execute_input":"2025-09-23T10:27:27.58134Z","iopub.status.idle":"2025-09-23T10:27:48.663268Z","shell.execute_reply.started":"2025-09-23T10:27:27.581316Z","shell.execute_reply":"2025-09-23T10:27:48.662537Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\n\nlabels_path = \"/kaggle/working/train_labels/training_solutions_rev1.csv\"\nlabels_df = pd.read_csv(labels_path)\n\nprint(\"Etiket dosyası okundu, shape:\", labels_df.shape)\nprint(labels_df.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:28:42.509367Z","iopub.execute_input":"2025-09-23T10:28:42.509977Z","iopub.status.idle":"2025-09-23T10:28:42.781395Z","shell.execute_reply.started":"2025-09-23T10:28:42.509956Z","shell.execute_reply":"2025-09-23T10:28:42.78056Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\n# X = GalaxyID, y = sınıflar\nX = labels_df[\"GalaxyID\"].astype(str)  # string yapalım ki dosya ismiyle eşleşsin\ny = labels_df.drop(\"GalaxyID\", axis=1)\n\n# Eğitim ve doğrulama seti %80 / %20\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\nprint(\"Eğitim seti:\", X_train.shape, y_train.shape)\nprint(\"Doğrulama seti:\", X_val.shape, y_val.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:30:30.561053Z","iopub.execute_input":"2025-09-23T10:30:30.561335Z","iopub.status.idle":"2025-09-23T10:30:30.611131Z","shell.execute_reply.started":"2025-09-23T10:30:30.561311Z","shell.execute_reply":"2025-09-23T10:30:30.610353Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Görsel parametreleri\nimg_size = (64, 64)   # başlangıç için küçük tutuyoruz\nbatch_size = 32\n\n# ID’lere .jpg ekleyelim\ntrain_df = pd.DataFrame({\n    \"GalaxyID\": X_train + \".jpg\",\n    \"label\": list(y_train.values)\n})\n\nval_df = pd.DataFrame({\n    \"GalaxyID\": X_val + \".jpg\",\n    \"label\": list(y_val.values)\n})\n\n# Data augmentation\ndatagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory=\"/kaggle/working/train_images/images_training_rev1\",\n    x_col=\"GalaxyID\",\n    y_col=\"label\",\n    target_size=img_size,\n    batch_size=batch_size,\n    class_mode=\"raw\"   # çoklu etiketler için\n)\n\nval_generator = datagen.flow_from_dataframe(\n    dataframe=val_df,\n    directory=\"/kaggle/working/train_images/images_training_rev1\",\n    x_col=\"GalaxyID\",\n    y_col=\"label\",\n    target_size=img_size,\n    batch_size=batch_size,\n    class_mode=\"raw\"\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:31:59.165879Z","iopub.execute_input":"2025-09-23T10:31:59.16641Z","iopub.status.idle":"2025-09-23T10:31:59.611484Z","shell.execute_reply.started":"2025-09-23T10:31:59.16639Z","shell.execute_reply":"2025-09-23T10:31:59.610699Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\n\nnum_classes = 37  # GalaxyID hariç 37 etiket\n\nmodel = Sequential([\n    Conv2D(32, (3,3), activation=\"relu\", input_shape=(64,64,3)),\n    MaxPooling2D((2,2)),\n\n    Conv2D(64, (3,3), activation=\"relu\"),\n    MaxPooling2D((2,2)),\n\n    Conv2D(128, (3,3), activation=\"relu\"),\n    MaxPooling2D((2,2)),\n\n    Flatten(),\n    Dense(256, activation=\"relu\"),\n    Dropout(0.5),\n    Dense(num_classes, activation=\"sigmoid\")  # multi-label için sigmoid\n])\n\nmodel.compile(optimizer=Adam(1e-4), loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:32:53.890254Z","iopub.execute_input":"2025-09-23T10:32:53.89053Z","iopub.status.idle":"2025-09-23T10:32:55.969553Z","shell.execute_reply.started":"2025-09-23T10:32:53.890509Z","shell.execute_reply":"2025-09-23T10:32:55.969043Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\n# GalaxyID dışındaki tüm kolonları float32'ye çevir\nlabels_df[labels_df.columns[1:]] = labels_df[labels_df.columns[1:]].astype(np.float32)\nprint(labels_df.dtypes[:10])  # ilk 10 kolonun tipini kontrol et\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:45:14.36463Z","iopub.execute_input":"2025-09-23T10:45:14.364938Z","iopub.status.idle":"2025-09-23T10:45:14.397755Z","shell.execute_reply.started":"2025-09-23T10:45:14.364914Z","shell.execute_reply":"2025-09-23T10:45:14.397055Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_df, val_df = train_test_split(labels_df, test_size=0.2, random_state=42)\nprint(\"Eğitim seti:\", train_df.shape)\nprint(\"Doğrulama seti:\", val_df.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:46:06.842243Z","iopub.execute_input":"2025-09-23T10:46:06.842536Z","iopub.status.idle":"2025-09-23T10:46:06.870595Z","shell.execute_reply.started":"2025-09-23T10:46:06.842515Z","shell.execute_reply":"2025-09-23T10:46:06.869817Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# GalaxyID kolonunu string yap ve .jpg ekle\ntrain_df[\"GalaxyID\"] = train_df[\"GalaxyID\"].astype(str) + \".jpg\"\nval_df[\"GalaxyID\"] = val_df[\"GalaxyID\"].astype(str) + \".jpg\"\n\nprint(train_df.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:48:29.136302Z","iopub.execute_input":"2025-09-23T10:48:29.136556Z","iopub.status.idle":"2025-09-23T10:48:29.170818Z","shell.execute_reply.started":"2025-09-23T10:48:29.13654Z","shell.execute_reply":"2025-09-23T10:48:29.170033Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(\n    dataframe=train_df,\n    directory=\"/kaggle/working/train_images/images_training_rev1\",  # ✅ düzeltildi\n    x_col=\"GalaxyID\",\n    y_col=labels_df.columns[1:],  \n    target_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode=\"raw\"\n)\n\nval_generator = val_datagen.flow_from_dataframe(\n    dataframe=val_df,\n    directory=\"/kaggle/working/train_images/images_training_rev1\",  # ✅ düzeltildi\n    x_col=\"GalaxyID\",\n    y_col=labels_df.columns[1:], \n    target_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode=\"raw\"\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:50:18.074334Z","iopub.execute_input":"2025-09-23T10:50:18.074633Z","iopub.status.idle":"2025-09-23T10:50:18.487809Z","shell.execute_reply.started":"2025-09-23T10:50:18.07461Z","shell.execute_reply":"2025-09-23T10:50:18.487135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\n\nnum_classes = 37  # GalaxyID hariç 37 sınıf\n\nmodel = Sequential([\n    Conv2D(32, (3,3), activation=\"relu\", input_shape=(64,64,3)),\n    MaxPooling2D((2,2)),\n\n    Conv2D(64, (3,3), activation=\"relu\"),\n    MaxPooling2D((2,2)),\n\n    Conv2D(128, (3,3), activation=\"relu\"),\n    MaxPooling2D((2,2)),\n\n    Flatten(),\n    Dense(256, activation=\"relu\"),\n    Dropout(0.5),\n    Dense(num_classes, activation=\"sigmoid\")  # multi-label problem olduğu için sigmoid\n])\n\nmodel.compile(optimizer=Adam(1e-4),\n              loss=\"binary_crossentropy\",\n              metrics=[\"accuracy\"])\n\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:53:29.279996Z","iopub.execute_input":"2025-09-23T10:53:29.280528Z","iopub.status.idle":"2025-09-23T10:53:29.344096Z","shell.execute_reply.started":"2025-09-23T10:53:29.280505Z","shell.execute_reply":"2025-09-23T10:53:29.343543Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\n\nearly_stop = EarlyStopping(monitor=\"val_loss\", patience=3, restore_best_weights=True)\n\nhistory = model.fit(\n    train_generator,\n    validation_data=val_generator,\n    epochs=20,\n    callbacks=[early_stop]\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T10:55:37.589965Z","iopub.execute_input":"2025-09-23T10:55:37.590511Z","iopub.status.idle":"2025-09-23T11:17:12.193065Z","shell.execute_reply.started":"2025-09-23T10:55:37.590485Z","shell.execute_reply":"2025-09-23T11:17:12.192496Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Doğruluk grafiği\nplt.plot(history.history['accuracy'], label='Eğitim Doğruluğu')\nplt.plot(history.history['val_accuracy'], label='Doğrulama Doğruluğu')\nplt.xlabel('Epoch')\nplt.ylabel('Doğruluk')\nplt.legend()\nplt.show()\n\n# Kayıp grafiği\nplt.plot(history.history['loss'], label='Eğitim Kayıp')\nplt.plot(history.history['val_loss'], label='Doğrulama Kayıp')\nplt.xlabel('Epoch')\nplt.ylabel('Kayıp')\nplt.legend()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T11:41:21.890201Z","iopub.execute_input":"2025-09-23T11:41:21.890461Z","iopub.status.idle":"2025-09-23T11:41:22.189729Z","shell.execute_reply.started":"2025-09-23T11:41:21.890435Z","shell.execute_reply":"2025-09-23T11:41:22.18894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_loss, test_acc = model.evaluate(val_generator)\nprint(\"Test Doğruluk:\", test_acc)\nprint(\"Test Kayıp:\", test_loss)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T11:43:27.727125Z","iopub.execute_input":"2025-09-23T11:43:27.727612Z","iopub.status.idle":"2025-09-23T11:43:41.167082Z","shell.execute_reply.started":"2025-09-23T11:43:27.727592Z","shell.execute_reply":"2025-09-23T11:43:41.16646Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Gerçek etiketler\ny_true = val_df.drop(columns=[\"GalaxyID\"]).values\nprint(\"y_true shape:\", y_true.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T11:57:32.399369Z","iopub.execute_input":"2025-09-23T11:57:32.399676Z","iopub.status.idle":"2025-09-23T11:57:32.409653Z","shell.execute_reply.started":"2025-09-23T11:57:32.399655Z","shell.execute_reply":"2025-09-23T11:57:32.408908Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Model tahminleri\ny_pred = model.predict(val_generator, verbose=1)\nprint(\"y_pred shape:\", y_pred.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T12:04:06.196547Z","iopub.execute_input":"2025-09-23T12:04:06.197257Z","iopub.status.idle":"2025-09-23T12:04:18.980769Z","shell.execute_reply.started":"2025-09-23T12:04:06.197232Z","shell.execute_reply":"2025-09-23T12:04:18.980025Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Gerçek etiketleri int yap\ny_true_int = y_true.astype(int)\n\n# 0.5 üstünü 1 kabul et\ny_pred_binary = (y_pred > 0.5).astype(int)\n\nfrom sklearn.metrics import classification_report\n\ntarget_names = val_df.columns[1:]  # GalaxyID hariç sınıf isimleri\n\nprint(classification_report(y_true_int, y_pred_binary, target_names=target_names, zero_division=0))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T12:10:42.19112Z","iopub.execute_input":"2025-09-23T12:10:42.191418Z","iopub.status.idle":"2025-09-23T12:10:42.258024Z","shell.execute_reply.started":"2025-09-23T12:10:42.191396Z","shell.execute_reply":"2025-09-23T12:10:42.257331Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# .h5 formatında kaydet\nmodel.save(\"galaxy_cnn_model.h5\")\n\n# alternatif olarak .keras formatında\nmodel.save(\"galaxy_cnn_model.keras\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-23T12:19:24.274038Z","iopub.execute_input":"2025-09-23T12:19:24.274312Z","iopub.status.idle":"2025-09-23T12:19:24.418391Z","shell.execute_reply.started":"2025-09-23T12:19:24.274292Z","shell.execute_reply":"2025-09-23T12:19:24.417603Z"}},"outputs":[],"execution_count":null}]}