{"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":"gpu","dataSources":[{"sourceId":84896,"databundleVersionId":10305135,"sourceType":"competition"}],"dockerImageVersionId":30822,"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)\nfrom sklearn.preprocessing import LabelEncoder,OrdinalEncoder,OneHotEncoder\nfrom sklearn.model_selection import KFold\nfrom catboost import CatBoostRegressor \n\nfrom sklearn.metrics import mean_squared_log_error\nimport joblib\nimport warnings\nwarnings.filterwarnings(\"ignore\")\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\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:06.477134Z","iopub.execute_input":"2024-12-27T11:14:06.47743Z","iopub.status.idle":"2024-12-27T11:14:06.48553Z","shell.execute_reply.started":"2024-12-27T11:14:06.477395Z","shell.execute_reply":"2024-12-27T11:14:06.484545Z"}},"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\")\nsample=pd.read_csv(\"/kaggle/input/playground-series-s4e12/sample_submission.csv\")\ntrain.drop(columns=\"id\",inplace=True)\ntest.drop(columns=\"id\",inplace=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:06.486921Z","iopub.execute_input":"2024-12-27T11:14:06.487148Z","iopub.status.idle":"2024-12-27T11:14:12.762116Z","shell.execute_reply.started":"2024-12-27T11:14:06.487117Z","shell.execute_reply":"2024-12-27T11:14:12.761431Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Feature Engineering for \"Policy Start Date\" column \ndef date(df):\n    df[\"Policy Start Date\"]=pd.to_datetime(df[\"Policy Start Date\"])\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[\"month_name\"]=df[\"Policy Start Date\"].dt.month_name()\n    df['day_of_week']=df[\"Policy Start Date\"].dt.dayofweek\n    df[\"week\"]=df[\"Policy Start Date\"].dt.isocalendar().week\n    df[\"year_sin\"]=np.sin(2*np.pi*df[\"year\"]) \n    df[\"year_cos\"]=np.cos(2*np.pi*df[\"year\"])\n    \n    df[\"month_sin\"]=np.sin(2*np.pi*df[\"month\"])\n    df[\"month_cos\"]=np.cos(2*np.pi*df[\"month\"])\n    df[\"day_sin\"]=np.sin(2*np.pi*df[\"day\"])\n    df[\"day_cos\"]=np.cos(2*np.pi*df[\"day\"])\n    df[\"group\"]=(df[\"year\"]-2020*48+df[\"month\"]*4+df[\"day\"]//7)\n    df.drop(columns=\"Policy Start Date\",inplace=True)\n    return df   ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:12.763721Z","iopub.execute_input":"2024-12-27T11:14:12.764026Z","iopub.status.idle":"2024-12-27T11:14:12.770128Z","shell.execute_reply.started":"2024-12-27T11:14:12.763996Z","shell.execute_reply":"2024-12-27T11:14:12.769257Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train=date(train)\ntest=date(test)\ntrain=fe(train)\ntest=fe(test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:12.791515Z","iopub.execute_input":"2024-12-27T11:14:12.791793Z","iopub.status.idle":"2024-12-27T11:14:14.912919Z","shell.execute_reply.started":"2024-12-27T11:14:12.791765Z","shell.execute_reply":"2024-12-27T11:14:14.912267Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cat_cols=list(train.select_dtypes(include=\"object\"))\nfeature_cols=list(test.columns)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:14.913709Z","iopub.execute_input":"2024-12-27T11:14:14.914003Z","iopub.status.idle":"2024-12-27T11:14:15.464134Z","shell.execute_reply.started":"2024-12-27T11:14:14.913974Z","shell.execute_reply":"2024-12-27T11:14:15.463461Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Create class for encode object data\nclass CategoricalEncoder:\n    def __init__ (self,train,test):\n        self.train=train\n        self.test=test\n    def frequency_encode(self,cat_cols,feature_cols,drop_org=False):\n        combined=pd.concat([self.train,self.test],axis=0,ignore_index=True)\n        new_cat_cols=[]\n        for col in cat_cols:\n            encoding_dict=combined[col].value_counts().to_dict() #This dictionary \n            self.train[f'{col}_en']=self.train[col].map(encoding_dict).astype('float')\n            self.test[f\"{col}_en\"]=self.test[col].map(encoding_dict).astype(\"float\")\n            new_col_name=f\"{col}_en\"\n            new_cat_cols.append(new_col_name)\n            feature_cols.append(new_col_name)\n            if drop_org:\n                feature_cols.remove(col)\n        return self.train,self.test,new_cat_cols,feature_cols\n           ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:15.466603Z","iopub.execute_input":"2024-12-27T11:14:15.466863Z","iopub.status.idle":"2024-12-27T11:14:15.472827Z","shell.execute_reply.started":"2024-12-27T11:14:15.466841Z","shell.execute_reply":"2024-12-27T11:14:15.471958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"encoder=CategoricalEncoder(train,test)\ntrain,test,cat_cols,feature_cols=encoder.frequency_encode(cat_cols,feature_cols,drop_org=True)\ntrain=train[feature_cols+[\"Premium Amount\"]]\ntest=test[feature_cols]\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:15.47378Z","iopub.execute_input":"2024-12-27T11:14:15.474021Z","iopub.status.idle":"2024-12-27T11:14:18.611106Z","shell.execute_reply.started":"2024-12-27T11:14:15.474003Z","shell.execute_reply":"2024-12-27T11:14:18.610186Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:18.612002Z","iopub.execute_input":"2024-12-27T11:14:18.612299Z","iopub.status.idle":"2024-12-27T11:14:18.633945Z","shell.execute_reply.started":"2024-12-27T11:14:18.61227Z","shell.execute_reply":"2024-12-27T11:14:18.63304Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Saperate train into x,y\nx=train.drop(columns=\"Premium Amount\")\ny=train[\"Premium Amount\"]\ny_log=np.log1p(y)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:18.634793Z","iopub.execute_input":"2024-12-27T11:14:18.634977Z","iopub.status.idle":"2024-12-27T11:14:18.797024Z","shell.execute_reply.started":"2024-12-27T11:14:18.634961Z","shell.execute_reply":"2024-12-27T11:14:18.796364Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndef rmsle(y_true,y_pred):\n    return np.sqrt(mean_squared_log_error(y_true,y_pred))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:18.797685Z","iopub.execute_input":"2024-12-27T11:14:18.797902Z","iopub.status.idle":"2024-12-27T11:14:18.801642Z","shell.execute_reply.started":"2024-12-27T11:14:18.797883Z","shell.execute_reply":"2024-12-27T11:14:18.800835Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Train model\n\n\ndef train_model():\n    kf=KFold(n_splits=5,shuffle=True,random_state=42)\n    oof=np.zeros(len(x))\n    models=[]\n    for fold,(train_idx,valid_idx) in enumerate(kf.split(x)):\n        print(f\"fold{fold+1}\")\n        x_train,x_valid=x.iloc[train_idx],x.iloc[valid_idx]\n        y_train,y_valid=y_log.iloc[train_idx],y_log.iloc[valid_idx]\n        model=CatBoostRegressor(\n            iterations=3000,\n            learning_rate=0.05,\n            depth=6,\n            eval_metric=\"RMSE\",\n            random_seed=42,\n            verbose=200,\n            task_type=\"GPU\",\n            l2_leaf_reg=0.7\n        )\n        model.fit(x_train,y_train,eval_set=(x_valid,y_valid),early_stopping_rounds=300,)\n        models.append(model)\n        oof[valid_idx]=np.maximum(0,model.predict(x_valid))\n        fold_rmsle=rmsle(np.expm1(y_valid),np.expm1(oof[valid_idx]))\n        print(f'fold{fold+1}RMSLE:{fold_rmsle}')\n    return models,oof\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:18.802374Z","iopub.execute_input":"2024-12-27T11:14:18.802655Z","iopub.status.idle":"2024-12-27T11:14:18.817288Z","shell.execute_reply.started":"2024-12-27T11:14:18.802623Z","shell.execute_reply":"2024-12-27T11:14:18.81652Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"models,oof=train_model()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:14:18.818005Z","iopub.execute_input":"2024-12-27T11:14:18.818267Z","iopub.status.idle":"2024-12-27T11:15:28.627801Z","shell.execute_reply.started":"2024-12-27T11:14:18.818247Z","shell.execute_reply":"2024-12-27T11:15:28.626857Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(rmsle(y,np.expm1(oof)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:15:28.628736Z","iopub.execute_input":"2024-12-27T11:15:28.62902Z","iopub.status.idle":"2024-12-27T11:15:28.65088Z","shell.execute_reply.started":"2024-12-27T11:15:28.628994Z","shell.execute_reply":"2024-12-27T11:15:28.650007Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Create csv gile for submission \ntest_predictions=np.zeros(len(test))\nfor model in models:\n    test_predictions+=np.maximum(0,np.expm1(model.predict(test)))/len(models)\nsample[\"Premium Amount\"]=test_predictions \nsample.to_csv(\"cat_insurance.csv\",index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-27T11:15:55.185982Z","iopub.execute_input":"2024-12-27T11:15:55.18627Z","iopub.status.idle":"2024-12-27T11:16:00.370276Z","shell.execute_reply.started":"2024-12-27T11:15:55.186248Z","shell.execute_reply":"2024-12-27T11:16:00.369405Z"}},"outputs":[],"execution_count":null}]}