{"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"}],"dockerImageVersionId":31194,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import time, os, sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nfrom tensorflow.keras import layers, losses, callbacks\nfrom sklearn.model_selection import train_test_split\n\nplt.rc('figure', autolayout=True)\nplt.rc('axes', labelweight='bold', labelsize='large', titleweight='bold', titlesize=18, titlepad=10)\nplt.rc('image', cmap='magma')\n\nprint(\"Python version:\", sys.version_info)\nprint(\"Numpy version:\", np.version.version)\nprint(\"Tensorflow version:\", tf.__version__)\n\n# -----------------------------------\n# Download dataset\n# -----------------------------------\n!unzip -q -n ../input/galaxy-zoo-the-galaxy-challenge/images_training_rev1.zip -d ../temp/\n!unzip -q -n ../input/galaxy-zoo-the-galaxy-challenge/images_test_rev1.zip -d ../temp/\n\nlabels_pd = pd.read_csv(\n    '../input/galaxy-zoo-the-galaxy-challenge/training_solutions_rev1.zip',\n    compression='zip'\n)\n\nprint(\"Dataset loading done!\")\n\n# -------------------------------------------------------------------\n# 🔧 FIX: Clean GalaxyID column (string → int)\n# -------------------------------------------------------------------\nlabels_pd[\"GalaxyID\"] = (\n    labels_pd[\"GalaxyID\"]\n    .astype(str)\n    .str.replace(\".0\", \"\", regex=False)\n    .astype(\"int32\")\n)\n\n# -----------------------------------\n# Hardware strategy\n# -----------------------------------\nstrategy = tf.distribute.get_strategy()\nprint(\"Running on CPU/GPU\")\n\n# Constants\nBATCH_SIZE = 64\nAUTOTUNE = tf.data.AUTOTUNE\nIMAGE_SIZE = 160\nNUM_FEATURES = 37\n\n# -----------------------------------\n# Image loader\n# -----------------------------------\ndef get_image_and_features(image_path, training=True):\n    if isinstance(image_path, tf.Tensor):\n        image_path = image_path.numpy().decode('utf-8')\n    \n    image = tf.io.read_file(image_path)\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.image.convert_image_dtype(image, tf.float32)\n    image = tf.image.resize(image, [IMAGE_SIZE, IMAGE_SIZE])\n\n    if training:\n        filename = os.path.basename(image_path)\n        galaxyID = int(filename.split('.')[0])\n\n        galaxy_row = labels_pd.loc[labels_pd[\"GalaxyID\"] == galaxyID]\n        if galaxy_row.empty:\n            features = np.zeros((NUM_FEATURES,), dtype=np.float32)\n        else:\n            features = galaxy_row.iloc[0, 1:].values.astype(np.float32)\n\n        return image, features\n    else:\n        return image\n\n# -----------------------------------\n# Dataset preprocessing\n# -----------------------------------\ndef dataset_preprocessing(images_path, training=True):\n    images_path_ds = tf.data.Dataset.from_tensor_slices(images_path)\n\n    def train_map_function(x):\n        image, features = tf.py_function(\n            func=lambda p: get_image_and_features(p, True),\n            inp=[x],\n            Tout=(tf.float32, tf.float32)\n        )\n        image.set_shape([IMAGE_SIZE, IMAGE_SIZE, 3])\n        features.set_shape([NUM_FEATURES])\n        return image, features\n    \n    def test_map_function(x):\n        image = tf.py_function(\n            func=lambda p: get_image_and_features(p, False),\n            inp=[x],\n            Tout=tf.float32\n        )\n        image.set_shape([IMAGE_SIZE, IMAGE_SIZE, 3])\n        return image\n    \n    if training:\n        dataset = images_path_ds.map(train_map_function, num_parallel_calls=AUTOTUNE)\n        dataset = dataset.shuffle(2048)\n    else:\n        dataset = images_path_ds.map(test_map_function, num_parallel_calls=AUTOTUNE)\n\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset\n\n# -----------------------------------\n# Load image paths\n# -----------------------------------\nimages_path = tf.io.gfile.glob('../temp/images_training_rev1/*')\nimages_path = [p for p in images_path if p.lower().endswith(('.jpg', '.jpeg'))]\n\nseed = 54\ntf.random.set_seed(seed)\n\nimages_path = tf.random.shuffle(images_path)\nsamples_size = len(images_path)\nprint(\"Number of total samples:\", samples_size)\n\nsplitIndex = int(samples_size * 0.8)\nimages_path_train = images_path[:splitIndex]\nimages_path_val = images_path[splitIndex:]\n\ntrain_dataset = dataset_preprocessing(images_path_train)\nval_dataset = dataset_preprocessing(images_path_val)\n\nprint(\"Training batches:\", tf.data.experimental.cardinality(train_dataset))\nprint(\"Validation batches:\", tf.data.experimental.cardinality(val_dataset))\n\nprint(\"Dataset preprocessing done!\")\n\n# -----------------------------------\n# Plot examples\n# -----------------------------------\ndef plot_example(dataset, rows=2, cols=3):\n    for images, labels in dataset.take(1):\n        break\n    \n    fig, axes = plt.subplots(rows, cols, figsize=(12, 6))\n    for i in range(rows):\n        for j in range(cols):\n            idx = i * cols + j\n            if idx < images.shape[0]:\n                img = images[idx].numpy()\n                img = (img - img.min()) / (img.max() - img.min() + 1e-8)\n                axes[i, j].imshow(img)\n                axes[i, j].axis(\"off\")\n\n    plt.show()\n    return images[0].shape, labels[0].shape\n\nimage_shape, features_num = plot_example(train_dataset)\nprint(\"Images shape:\", image_shape)\nprint(\"Features length:\", features_num)\n\n# -----------------------------------\n# Model\n# -----------------------------------\ndef create_model(input_shape, use_augmentation=False):\n    if use_augmentation:\n        data_augmentation = tf.keras.Sequential([\n            layers.RandomFlip(\"horizontal_and_vertical\"),\n            layers.RandomRotation(0.3),\n            layers.RandomZoom(height_factor=0.2, width_factor=0.2),\n            layers.RandomContrast(0.05),\n        ], name=\"augmentation\")\n    else:\n        data_augmentation = None\n\n    model_layers = [\n        layers.Conv2D(16, (6, 6), activation='relu', input_shape=input_shape),\n        layers.BatchNormalization(),\n        layers.MaxPooling2D((2, 2)),\n        layers.Dropout(0.1),\n\n        layers.Conv2D(32, (5, 5), activation='relu'),\n        layers.BatchNormalization(),\n        layers.MaxPooling2D((2, 2)),\n        layers.Dropout(0.1),\n\n        layers.Conv2D(64, (3, 3), activation='relu'),\n        layers.BatchNormalization(),\n        layers.MaxPooling2D((2, 2)),\n        layers.Dropout(0.1),\n\n        layers.Conv2D(128, (3, 3), activation='relu'),\n        layers.BatchNormalization(),\n        layers.MaxPooling2D((2, 2)),\n        layers.Dropout(0.1),\n\n        layers.Flatten(),\n        layers.Dense(512, activation='relu'),\n        layers.Dropout(0.2),\n        layers.Dense(256, activation='relu'),\n        layers.Dropout(0.2),\n        layers.Dense(NUM_FEATURES, activation='sigmoid')\n    ]\n    \n    model = tf.keras.Sequential(model_layers, name=\"galaxyClassifier\")\n\n    if use_augmentation:\n        model = tf.keras.Sequential([data_augmentation, model], name=\"galaxyClassifier_with_aug\")\n\n    return model\n\nwith strategy.scope():\n    image_shape = (IMAGE_SIZE, IMAGE_SIZE, 3)\n    model = create_model(image_shape, True)\n    optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3)\n    loss_func = losses.MeanSquaredError()\n\n    model.compile(\n        loss=loss_func,\n        optimizer=optimizer,\n        metrics=[tf.keras.metrics.RootMeanSquaredError()]\n    )\n\n    model.summary()\n\n# -----------------------------------\n# Training\n# -----------------------------------\nnum_epochs = 50\nreduce_lr = callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=7, min_lr=1e-5)\nearly_stop = callbacks.EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=7)\ncheckpoint = callbacks.ModelCheckpoint('best_model.keras', save_best_only=True, monitor='val_root_mean_squared_error', mode='min')\n\ncallbacksInUse = [reduce_lr, early_stop, checkpoint]\n\nprint('------- Training -------')\nstart = time.time()\n\nfor images, labels in train_dataset.take(1):\n    print(f\"Image batch shape: {images.shape}\")\n    print(f\"Label batch shape: {labels.shape}\")\n    print(f\"Image dtype: {images.dtype}\")\n    print(f\"Label dtype: {labels.dtype}\")\n\nhistory = model.fit(\n    train_dataset,\n    validation_data=val_dataset,\n    epochs=num_epochs,\n    callbacks=callbacksInUse,\n    verbose=1\n)\n\nend = time.time()\nprint(\"Total training took {:.2f} hours.\".format((end - start)/3600))\n\n# -----------------------------------\n# Learning curves\n# -----------------------------------\nmetrics_history = history.history\nfig, axes = plt.subplots(1, 2, figsize=(12, 6))\n\naxes[0].plot(metrics_history['root_mean_squared_error'], label='train_rmse')\naxes[0].plot(metrics_history['val_root_mean_squared_error'], label='val_rmse')\naxes[0].set_xlabel('Epoch')\naxes[0].set_ylabel('RMSE')\naxes[0].legend()\naxes[0].set_title('RMSE over epochs')\n\naxes[1].plot(metrics_history['loss'], label='train_loss')\naxes[1].plot(metrics_history['val_loss'], label='val_loss')\naxes[1].set_xlabel('Epoch')\naxes[1].set_ylabel('Loss')\naxes[1].legend()\naxes[1].set_title('Loss over epochs')\n\nplt.tight_layout()\nplt.show()\n\n# -----------------------------------\n# Evaluation\n# -----------------------------------\nresults = model.evaluate(val_dataset, verbose=1)\nprint(\"Test Loss: {:.4f}\".format(results[0]))\nprint(\"Test RMSE: {:.4f}\".format(results[1]))\n\n# -----------------------------------\n# Save model\n# -----------------------------------\noutPath = model.name + \".keras\"\nmodel.save(outPath)\nprint(\"Model is saved:\", outPath)\n\n# -----------------------------------\n# Prediction\n# -----------------------------------\ntest_images_path = tf.io.gfile.glob('../temp/images_test_rev1/*')\ntest_images_path = [p for p in test_images_path if p.lower().endswith(('.jpg', '.jpeg'))]\ntest_dataset = dataset_preprocessing(test_images_path, False)\nprint('Number of test batches:', tf.data.experimental.cardinality(test_dataset))\n\nresult = model.predict(test_dataset, verbose=1)\nprint(\"result shape:\", result.shape)\n\n# -----------------------------------\n# Kaggle submission\n# -----------------------------------\ngalaxyIDs = [int(os.path.basename(p).split('.')[0]) for p in test_images_path]\ngalaxyIDs = np.array(galaxyIDs).reshape(-1, 1)\n\nsubmission = pd.DataFrame(\n    np.hstack((galaxyIDs, result)),\n    columns=labels_pd.columns\n)\n\nsubmission = submission.sort_values(by=['GalaxyID'])\nsubmission.to_csv('submission.csv', index=False)\nprint(\"Submission file is saved successfully!\")\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-12-07T15:01:01.332121Z","iopub.execute_input":"2025-12-07T15:01:01.332708Z","iopub.status.idle":"2025-12-07T18:03:16.646997Z","shell.execute_reply.started":"2025-12-07T15:01:01.332682Z","shell.execute_reply":"2025-12-07T18:03:16.646171Z"}},"outputs":[],"execution_count":null}]}