{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":84896,"databundleVersionId":10305135,"sourceType":"competition"},{"sourceId":10256213,"sourceType":"datasetVersion","datasetId":6344508}],"dockerImageVersionId":30823,"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,"execution":{"iopub.status.busy":"2024-12-20T16:51:50.870092Z","iopub.execute_input":"2024-12-20T16:51:50.870463Z","iopub.status.idle":"2024-12-20T16:51:51.174851Z","shell.execute_reply.started":"2024-12-20T16:51:50.870437Z","shell.execute_reply":"2024-12-20T16:51:51.174073Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 1. Importing Required Libraries","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport gc\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models, regularizers\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.optimizers import Adam\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nimport optuna\nfrom optuna.samplers import TPESampler","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:51:51.175896Z","iopub.execute_input":"2024-12-20T16:51:51.176354Z","iopub.status.idle":"2024-12-20T16:51:54.175262Z","shell.execute_reply.started":"2024-12-20T16:51:51.176319Z","shell.execute_reply":"2024-12-20T16:51:54.17456Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 2. Defining the RMSLE Loss Function","metadata":{}},{"cell_type":"code","source":"def rmsle(y_true, y_pred):\n    \"\"\"\n    Root Mean Squared Logarithmic Error (RMSLE) loss function.\n    \"\"\"\n    epsilon = K.epsilon()\n    y_pred = K.clip(y_pred, epsilon, None)  # Avoid negative predictions\n    y_true = K.clip(y_true, epsilon, None)  # Avoid negative true values\n    return K.sqrt(K.mean(K.square(K.log(1 + y_pred) - K.log(1 + y_true))))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:51:54.176731Z","iopub.execute_input":"2024-12-20T16:51:54.177292Z","iopub.status.idle":"2024-12-20T16:51:54.181576Z","shell.execute_reply.started":"2024-12-20T16:51:54.177254Z","shell.execute_reply":"2024-12-20T16:51:54.180802Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 3. Loading and Exploring the Datasets","metadata":{}},{"cell_type":"code","source":"# Paths to training and test datasets\ntrain_file_path = '/kaggle/input/3-and-4/data_train_3.csv'  # Path to your training dataset\ntest_file_path = '/kaggle/input/3-and-4/data_test_3.csv'    # Path to your test dataset\n\n# Name of the target column\ntarget_column = 'Premium Amount'\n\n# Load the training dataset\nprint(\"Loading training dataset...\")\ntrain_df = pd.read_csv(train_file_path, dtype={'Gender': 'int64', 'Smoking Status': 'int64'})\nprint(f\"Training dataset shape: {train_df.shape}\")\n\n# Load the test dataset\nprint(\"Loading test dataset...\")\ntest_df = pd.read_csv(test_file_path, dtype={'Gender': 'int64', 'Smoking Status': 'int64'})\nprint(f\"Test dataset shape: {test_df.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:51:54.182869Z","iopub.execute_input":"2024-12-20T16:51:54.183152Z","iopub.status.idle":"2024-12-20T16:52:08.077771Z","shell.execute_reply.started":"2024-12-20T16:51:54.183116Z","shell.execute_reply":"2024-12-20T16:52:08.076658Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Check the number of columns in the datasets\nprint(f\"\\nNumber of columns in training dataset (excluding target): {train_df.shape[1] - 1}\")\nprint(f\"Number of columns in test dataset: {test_df.shape[1]}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:52:08.078844Z","iopub.execute_input":"2024-12-20T16:52:08.07919Z","iopub.status.idle":"2024-12-20T16:52:08.084223Z","shell.execute_reply.started":"2024-12-20T16:52:08.079161Z","shell.execute_reply":"2024-12-20T16:52:08.083441Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 4. Data Preprocessing","metadata":{}},{"cell_type":"code","source":"# Separate features and target variable\nX = train_df.drop(columns=[target_column]).values\ny = train_df[target_column].values.reshape(-1, 1)\n\n# Extract features from the test dataset (excluding the ID column)\nX_test = test_df.drop(columns=['id']).values\ntest_ids = test_df['id'].values  # Save IDs for test predictions\n\nprint(f\"\\nFeature matrix shape (X): {X.shape}\")\nprint(f\"Target variable shape (y): {y.shape}\")\nprint(f\"Feature matrix shape for test data (X_test): {X_test.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:52:08.085253Z","iopub.execute_input":"2024-12-20T16:52:08.085613Z","iopub.status.idle":"2024-12-20T16:52:11.430559Z","shell.execute_reply.started":"2024-12-20T16:52:08.08558Z","shell.execute_reply":"2024-12-20T16:52:11.42975Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Data Normalization\nprint(\"\\nNormalizing data...\")\nscaler = StandardScaler()\nX = scaler.fit_transform(X)\nX_test = scaler.transform(X_test)\n\n# Release memory\ngc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:52:11.431344Z","iopub.execute_input":"2024-12-20T16:52:11.431581Z","iopub.status.idle":"2024-12-20T16:52:19.453941Z","shell.execute_reply.started":"2024-12-20T16:52:11.431562Z","shell.execute_reply":"2024-12-20T16:52:19.453254Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split the data into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(\n    X, y, test_size=0.1, random_state=42\n)\nprint(f\"\\nTraining set size: {X_train.shape}\")\nprint(f\"Validation set size: {X_val.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:52:19.456173Z","iopub.execute_input":"2024-12-20T16:52:19.456417Z","iopub.status.idle":"2024-12-20T16:52:20.347194Z","shell.execute_reply.started":"2024-12-20T16:52:19.456399Z","shell.execute_reply":"2024-12-20T16:52:20.346127Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 5. Building the Model","metadata":{}},{"cell_type":"code","source":"def build_model(input_dim, n_units, dropouts, learning_rate=0.0001):\n    \"\"\"\n    Builds a regression model with specified units and dropout rates.\n    \"\"\"\n    model = models.Sequential()\n    for i, units in enumerate(n_units):\n        if i == 0:\n            model.add(layers.Dense(units, activation='relu', input_shape=(input_dim,),\n                                   kernel_regularizer=regularizers.l2(0.001)))\n        else:\n            model.add(layers.Dense(units, activation='relu', kernel_regularizer=regularizers.l2(0.001)))\n        model.add(layers.BatchNormalization())\n        model.add(layers.Dropout(dropouts[i]))\n\n    model.add(layers.Dense(1, activation='linear'))\n    optimizer = Adam(learning_rate=learning_rate)\n    model.compile(optimizer=optimizer, loss=rmsle, metrics=[rmsle, 'mae'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:52:20.348344Z","iopub.execute_input":"2024-12-20T16:52:20.348599Z","iopub.status.idle":"2024-12-20T16:52:20.354287Z","shell.execute_reply.started":"2024-12-20T16:52:20.348577Z","shell.execute_reply":"2024-12-20T16:52:20.353294Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 6. Objective Function for Optuna","metadata":{}},{"cell_type":"code","source":"def objective(trial):\n    \"\"\"\n    Objective function for Optuna to optimize hyperparameters.\n    \"\"\"\n    # Suggest hyperparameters\n    n_units_layer1 = trial.suggest_categorical(\"n_units_layer1\", [64, 128, 256, 512])\n    n_units_layer2 = trial.suggest_categorical(\"n_units_layer2\", [64, 128, 256, 512])\n    n_units_layer3 = trial.suggest_categorical(\"n_units_layer3\", [64, 128, 256, 512])\n    \n    dropout_layer1 = trial.suggest_categorical(\"dropout_layer1\", [0.1, 0.3, 0.5, 0.7, 0.9])\n    dropout_layer2 = trial.suggest_categorical(\"dropout_layer2\", [0.1, 0.3, 0.5, 0.7, 0.9])\n    dropout_layer3 = trial.suggest_categorical(\"dropout_layer3\", [0.1, 0.3, 0.5, 0.7, 0.9])\n    \n    best_batch_size = 2048  # Fixed batch size\n    \n    model = build_model(\n        input_dim=X_train.shape[1],\n        n_units=[n_units_layer1, n_units_layer2, n_units_layer3],\n        dropouts=[dropout_layer1, dropout_layer2, dropout_layer3],\n    )\n\n    early_stop = EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True, verbose=0)\n    \n    history = model.fit(\n        X_train, y_train,\n        epochs=1000,\n        batch_size=best_batch_size,\n        validation_data=(X_val, y_val),\n        callbacks=[early_stop],\n        verbose=0\n    )\n\n    val_loss = min(history.history['val_loss'])\n\n    # Clean up memory\n    K.clear_session()\n    gc.collect()\n\n    return val_loss","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:52:20.355044Z","iopub.execute_input":"2024-12-20T16:52:20.355328Z","iopub.status.idle":"2024-12-20T16:52:20.367487Z","shell.execute_reply.started":"2024-12-20T16:52:20.355304Z","shell.execute_reply":"2024-12-20T16:52:20.366721Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 7. Running Optuna","metadata":{}},{"cell_type":"code","source":"# Run optimization\nstudy = optuna.create_study(direction='minimize', sampler=TPESampler(seed=42))\nstudy.optimize(objective, n_trials=150)  # For example, 50 trials\n\nprint(\"\\nBest hyperparameter set:\")\nprint(study.best_params)\nprint(f\"Best validation loss (RMSLE): {study.best_value}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T16:52:20.368251Z","iopub.execute_input":"2024-12-20T16:52:20.368542Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 8. Training the Best Model","metadata":{}},{"cell_type":"code","source":"# Rebuild and train the best model\nbest_params = study.best_params","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"best_model = build_model(\n    input_dim=X_train.shape[1],\n    n_units=[best_params['n_units_layer1'], best_params['n_units_layer2'], best_params['n_units_layer3']],\n    dropouts=[best_params['dropout_layer1'], best_params['dropout_layer2'], best_params['dropout_layer3']]\n)\n\nearly_stop = EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True, verbose=1)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = best_model.fit(\n    X_train, y_train,\n    epochs=1000,\n    batch_size=2048,\n    validation_data=(X_val, y_val),\n    callbacks=[early_stop],\n    verbose=1\n)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Test predictions \npreds = best_model.predict(X_test).ravel()\nresults_df = pd.DataFrame({'id': test_ids, target_column: preds})\nresults_df.to_csv('submission.csv', index=False)\nprint(\"Test predictions saved to test_predictions.csv.\")","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}