{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":84896,"databundleVersionId":10305135,"sourceType":"competition"}],"dockerImageVersionId":30805,"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-17T15:09:48.224709Z","iopub.execute_input":"2024-12-17T15:09:48.224962Z","iopub.status.idle":"2024-12-17T15:09:49.194563Z","shell.execute_reply.started":"2024-12-17T15:09:48.224936Z","shell.execute_reply":"2024-12-17T15:09:49.192928Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_log_error\nfrom xgboost import XGBRegressor\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-17T15:15:00.262007Z","iopub.execute_input":"2024-12-17T15:15:00.262362Z","iopub.status.idle":"2024-12-17T15:15:00.267735Z","shell.execute_reply.started":"2024-12-17T15:15:00.262332Z","shell.execute_reply":"2024-12-17T15:15:00.266713Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Example using Dask\nimport dask.dataframe as dd\n\n# Load data using Dask (Dask DataFrame is similar to Pandas DataFrame)\ntrain_df = dd.read_csv('/kaggle/input/playground-series-s4e12/train.csv')\ntest_df = dd.read_csv('/kaggle/input/playground-series-s4e12/test.csv')\n\n# Perform operations using Dask DataFrame\ntrain_df['Policy Start Date'] = dd.to_datetime(train_df['Policy Start Date'])\ntest_df['Policy Start Date'] = dd.to_datetime(test_df['Policy Start Date'])\n\n# Extract year, month, day for both train and test sets\ntrain_df['Policy Start Year'] = train_df['Policy Start Date'].dt.year\ntrain_df['Policy Start Month'] = train_df['Policy Start Date'].dt.month\ntrain_df['Policy Start Day'] = train_df['Policy Start Date'].dt.day\n\ntest_df['Policy Start Year'] = test_df['Policy Start Date'].dt.year\ntest_df['Policy Start Month'] = test_df['Policy Start Date'].dt.month\ntest_df['Policy Start Day'] = test_df['Policy Start Date'].dt.day\n\n# Drop 'Policy Start Date' column\ntrain_df.drop('Policy Start Date', axis=1)\ntest_df.drop('Policy Start Date', axis=1)\n\n# Convert to Pandas DataFrame for further processing if needed\ntrain_df = train_df.compute()\ntest_df = test_df.compute()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-17T15:15:06.183391Z","iopub.execute_input":"2024-12-17T15:15:06.183762Z","iopub.status.idle":"2024-12-17T15:15:11.984289Z","shell.execute_reply.started":"2024-12-17T15:15:06.183723Z","shell.execute_reply":"2024-12-17T15:15:11.983531Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define feature and target columns\nX = train_df.drop(columns=['Premium Amount', 'id'])\ny = train_df['Premium Amount']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-17T15:15:11.985217Z","iopub.execute_input":"2024-12-17T15:15:11.985446Z","iopub.status.idle":"2024-12-17T15:15:12.147326Z","shell.execute_reply.started":"2024-12-17T15:15:11.985423Z","shell.execute_reply":"2024-12-17T15:15:12.146343Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split the training data into train and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-17T15:15:12.148511Z","iopub.execute_input":"2024-12-17T15:15:12.148797Z","iopub.status.idle":"2024-12-17T15:15:12.788211Z","shell.execute_reply.started":"2024-12-17T15:15:12.148771Z","shell.execute_reply":"2024-12-17T15:15:12.787263Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define categorical and numerical features\ncategorical_features = ['Gender', 'Marital Status', 'Education Level', 'Occupation', 'Location', 'Policy Type', 'Customer Feedback', 'Smoking Status', 'Exercise Frequency', 'Property Type']\nnumerical_features = ['Age', 'Annual Income', 'Number of Dependents', 'Health Score', 'Previous Claims', 'Vehicle Age', 'Credit Score', 'Insurance Duration', 'Policy Start Year', 'Policy Start Month', 'Policy Start Day']\n\n# Preprocessing for numerical data (StandardScaler)\nnumerical_transformer = StandardScaler()\n\n# Preprocessing for categorical data (OneHotEncoder)\ncategorical_transformer = OneHotEncoder(handle_unknown='ignore')\n\n# Bundle preprocessing for numerical and categorical data\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num', numerical_transformer, numerical_features),\n        ('cat', categorical_transformer, categorical_features)\n    ])\n\n# Define the model with GPU acceleration\nmodel = XGBRegressor(\n    n_estimators=2000,  # 增加树的数量\n    learning_rate=0.01,  # 更低的学习率\n    max_depth=8,\n    subsample=0.8,  # 控制样本比例，防止过拟合\n    colsample_bytree=0.8,  # 控制特征比例\n    gamma=1,  # 增加分裂的正则化约束\n    reg_alpha=1,  # L1 正则化\n    reg_lambda=1,  # L2 正则化\n    tree_method='gpu_hist',\n    predictor='gpu_predictor',\n    random_state=42\n)\n\n\n# Create and evaluate the pipeline\npipeline = Pipeline(steps=[('preprocessor', preprocessor),\n                           ('model', model)])\n\n# Fit the pipeline on the training data\npipeline.fit(X_train, y_train)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-17T16:47:37.378589Z","iopub.execute_input":"2024-12-17T16:47:37.378929Z","iopub.status.idle":"2024-12-17T16:48:15.525775Z","shell.execute_reply.started":"2024-12-17T16:47:37.3789Z","shell.execute_reply":"2024-12-17T16:48:15.524873Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Make predictions\ny_pred = pipeline.predict(X_val)\n\nfrom sklearn.metrics import mean_squared_error\n\n# Calculate MSE instead of RMSLE\nmse = mean_squared_error(y_val, y_pred)\nprint(f'Mean Squared Error: {mse}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-17T16:48:15.527011Z","iopub.execute_input":"2024-12-17T16:48:15.5273Z","iopub.status.idle":"2024-12-17T16:48:16.620299Z","shell.execute_reply.started":"2024-12-17T16:48:15.527273Z","shell.execute_reply":"2024-12-17T16:48:16.619427Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Prepare the test data (do the same preprocessing as training data)\nX_test = test_df.drop(columns=['id'])\n\n# Generate predictions\ntest_preds = pipeline.predict(X_test)\n\n# Create a DataFrame for submission\nsubmission = pd.DataFrame({\n    'id': test_df['id'],\n    'Premium Amount': test_preds\n})\n\n# Save the submission to a CSV file\nsubmission.to_csv('submission.csv', index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-17T16:48:55.38968Z","iopub.execute_input":"2024-12-17T16:48:55.390028Z","iopub.status.idle":"2024-12-17T16:49:00.043089Z","shell.execute_reply.started":"2024-12-17T16:48:55.389996Z","shell.execute_reply":"2024-12-17T16:49:00.042409Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-17T16:49:00.044483Z","iopub.execute_input":"2024-12-17T16:49:00.044751Z","iopub.status.idle":"2024-12-17T16:49:00.053495Z","shell.execute_reply.started":"2024-12-17T16:49:00.044726Z","shell.execute_reply":"2024-12-17T16:49:00.052701Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}