{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":84896,"databundleVersionId":10305135,"sourceType":"competition"},{"sourceId":9178166,"sourceType":"datasetVersion","datasetId":5547076}],"isInternetEnabled":false,"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 numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import PercentFormatter\nimport seaborn as sns\nfrom datetime import datetime\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nimport lightgbm as lgb\nfrom catboost import CatBoostRegressor\nfrom sklearn.model_selection import RepeatedKFold\nfrom tqdm import tqdm\nimport lightgbm as lgb\nfrom sklearn.metrics import mean_squared_error\nimport optuna\nfrom IPython.display import clear_output\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/playground-series-s4e12/train.csv')\ntest = pd.read_csv('/kaggle/input/playground-series-s4e12/test.csv')\norginal = pd.read_csv('/kaggle/input/insurance-premium-prediction/Insurance Premium Prediction Dataset.csv')\nsample_submission = pd.read_csv('/kaggle/input/playground-series-s4e12/sample_submission.csv')\n\ntarget = 'Premium Amount'","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# category/object & numerous variable\nnum_var = train.select_dtypes(include=['int','float']).columns.to_list()\ncate_var = train.select_dtypes(include=['object','category']).columns.to_list()\nprint(f'numerous variables: {num_var}')\nprint(f'category/object variable: {cate_var}')\nprint(len(num_var) + len(cate_var) == 21)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# missing values\nmissing_count = train.isnull().sum().reset_index()\nmissing_count.columns = ['feature', 'null_count']\nmissing_count = missing_count.sort_values('null_count', ascending=False)\nmissing_count['null_ratio'] = missing_count['null_count'] / len(train)\n\nplt.figure(figsize=(6, 8))\nplt.title(f'Missing values over the {len(train)} samples')\n\nplt.barh(np.arange(len(missing_count)), missing_count['null_ratio'], color='coral', label='missing')\nplt.barh(np.arange(len(missing_count)), \n         1 - missing_count['null_ratio'],\n         left=missing_count['null_ratio'],\n         color='darkseagreen', label='available')\nplt.yticks(np.arange(len(missing_count)), missing_count['feature'])\nplt.gca().xaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))\nplt.xlim(0, 1)\n\nplt.legend()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%time\n\nstats_df = pd.DataFrame(index=train[num_var].columns,columns=['Q1','Q3','IQR','min','max'])\n\ndef preprocess(df):\n\n    label_encoder = LabelEncoder()\n    scaler = StandardScaler()\n\n    df = df.drop('id', axis=1)\n\n    num_var = df.select_dtypes(include=['int','float']).columns.to_list()\n    num_var = [col for col in num_var if col != 'target']\n\n    for col in num_var:\n        Q1 = df[col].describe()['25%']\n        Q3 = df[col].describe()['75%']\n        IQR = Q3 - Q1\n        min = Q1 - 1.5 * IQR\n        max = Q3 + 1.5 * IQR\n        stats_df.loc[col,'Q1'] = Q1\n        stats_df.loc[col,'Q3'] = Q3\n        stats_df.loc[col,'IQR'] = IQR\n        stats_df.loc[col,'min'] = min\n        stats_df.loc[col,'max'] = max\n\n        lower_bound = Q1 - 1.5 * IQR\n        upper_bound = Q3 + 1.5 * IQR\n        \n        positive_values = df[df[col] > 0][col]\n        mean_positive_value = positive_values.mean()\n        df[col] = df[col].apply(lambda x: mean_positive_value if x <= 0 or pd.isnull(x) or x < lower_bound or x > upper_bound else x)\n\n    cate_var = df.select_dtypes(include=['object','category']).columns.to_list()\n    cate_var = [col for col in cate_var if col != 'Policy Start Date']\n    \n    df['Policy Start Date'] = pd.to_datetime(df['Policy Start Date'], errors='coerce')\n    df['year'] = df['Policy Start Date'].dt.year\n    df['month'] = df['Policy Start Date'].dt.month\n    df['day'] = df['Policy Start Date'].dt.day\n    df = df.drop('Policy Start Date', axis=1)\n\n    for col in cate_var:\n        if df[col].isnull().sum() > 0:\n            df[col] = df[col].fillna('Unknown')\n        df[col] = label_encoder.fit_transform(df[col])\n\n    return df, stats_df","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train, stats_df = preprocess(train)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test, stats_df = preprocess(test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = train.drop(target, axis=1)\ny = train[target]","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split the data\nx_train, x_cv, y_train, y_cv = train_test_split(X, y, train_size=0.8, test_size=0.2, random_state=60)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define the objective function to optimize LightGBM for regression\ndef objective_lgb(trial):\n    params = {\n        'objective': 'regression',  \n        'metric': 'rmse',           \n        'boosting_type': 'gbdt',\n        'num_leaves': trial.suggest_int('num_leaves', 20, 150),\n        'max_depth': trial.suggest_int('max_depth', 3, 15),\n        'learning_rate': trial.suggest_loguniform('learning_rate', 0.001, 0.1),\n        'n_estimators': trial.suggest_int('n_estimators', 50, 500),\n        'min_child_samples': trial.suggest_int('min_child_samples', 5, 50),\n        'subsample': trial.suggest_uniform('subsample', 0.6, 1.0),\n        'colsample_bytree': trial.suggest_uniform('colsample_bytree', 0.6, 1.0)\n    }\n\n    # Train the model with the specified parameters\n    model = lgb.LGBMRegressor(**params)\n    model.fit(x_train, y_train, eval_set=[(x_cv, y_cv)], eval_metric='rmse')\n\n    # Make predictions on the validation set\n    y_pred = model.predict(x_cv)\n\n    # Calculate RMSE score (or other regression metrics like MAE)\n    return mean_squared_error(y_cv, y_pred)  # Minimize MSE or RMSE for regression\n\n# Optimize LightGBM using Optuna\nstudy_lgb = optuna.create_study(direction='minimize')  # Minimize MSE for regression\nstudy_lgb.optimize(objective_lgb, n_trials=10)\n\n# Final LightGBM model with optimized parameters\nlgb_best_model = lgb.LGBMRegressor(**study_lgb.best_params, random_state=42)\nlgb_best_model.fit(X, y)\n\n# Optionally, evaluate the best model on the test set\ny_test_pred = lgb_best_model.predict(test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample_submission[target] = y_test_pred\nsample_submission.to_csv('submission.csv', index=False)\nsample_submission.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}