{"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"}},"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\nprint(\"Setup Complete\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-08-10T13:04:30.755502Z","iopub.execute_input":"2022-08-10T13:04:30.756011Z","iopub.status.idle":"2022-08-10T13:04:30.765483Z","shell.execute_reply.started":"2022-08-10T13:04:30.755971Z","shell.execute_reply":"2022-08-10T13:04:30.763880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***Importing necessary libraries***","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, plot_confusion_matrix, precision_score, recall_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom xgboost import XGBRegressor","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:04:35.040441Z","iopub.execute_input":"2022-08-10T13:04:35.040957Z","iopub.status.idle":"2022-08-10T13:04:35.049641Z","shell.execute_reply.started":"2022-08-10T13:04:35.040919Z","shell.execute_reply":"2022-08-10T13:04:35.048371Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***Loading datasets***","metadata":{}},{"cell_type":"code","source":"# Read the data\ntrain = pd.read_csv('/kaggle/input/titanic/train.csv')\ntest = pd.read_csv('/kaggle/input/titanic/test.csv')\n","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:04:39.089191Z","iopub.execute_input":"2022-08-10T13:04:39.089612Z","iopub.status.idle":"2022-08-10T13:04:39.109360Z","shell.execute_reply.started":"2022-08-10T13:04:39.089570Z","shell.execute_reply":"2022-08-10T13:04:39.108042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***Miss information analysis***","metadata":{}},{"cell_type":"code","source":"print(train.isnull().sum())","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:04:41.791647Z","iopub.execute_input":"2022-08-10T13:04:41.792062Z","iopub.status.idle":"2022-08-10T13:04:41.802561Z","shell.execute_reply.started":"2022-08-10T13:04:41.792031Z","shell.execute_reply":"2022-08-10T13:04:41.800860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test.isnull().sum())","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:04:45.215227Z","iopub.execute_input":"2022-08-10T13:04:45.216554Z","iopub.status.idle":"2022-08-10T13:04:45.224854Z","shell.execute_reply.started":"2022-08-10T13:04:45.216494Z","shell.execute_reply":"2022-08-10T13:04:45.223507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.info()","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:04:48.808684Z","iopub.execute_input":"2022-08-10T13:04:48.809183Z","iopub.status.idle":"2022-08-10T13:04:48.827611Z","shell.execute_reply.started":"2022-08-10T13:04:48.809148Z","shell.execute_reply":"2022-08-10T13:04:48.826115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.info()","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:04:51.954017Z","iopub.execute_input":"2022-08-10T13:04:51.954520Z","iopub.status.idle":"2022-08-10T13:04:51.974218Z","shell.execute_reply.started":"2022-08-10T13:04:51.954479Z","shell.execute_reply":"2022-08-10T13:04:51.973184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***Preprocessing***","metadata":{}},{"cell_type":"code","source":"# Separate target from predictors\ny = train.Survived\nX = train.drop(['Survived'], axis=1)\n# Divide data into training and validation subsets\nX_train_full, X_valid_full, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2,\n                                                                random_state=0)\n# \"Cardinality\" means the number of unique values in a column\n# Select categorical columns with relatively low cardinality (convenient but arbitrary)\ncategorical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].nunique() < 10 and \n                        X_train_full[cname].dtype == \"object\"]\n# Select numerical columns\nnumerical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].dtype in ['int64', 'float64']]\n# Keep selected columns only\nmy_cols = categorical_cols + numerical_cols\nX_train = X_train_full[my_cols].copy()\nX_valid = X_valid_full[my_cols].copy()\nX_test = test[my_cols].copy()\n","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:06.917766Z","iopub.execute_input":"2022-08-10T13:05:06.918200Z","iopub.status.idle":"2022-08-10T13:05:06.938846Z","shell.execute_reply.started":"2022-08-10T13:05:06.918167Z","shell.execute_reply":"2022-08-10T13:05:06.937853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#taking a peek at the training data with the head()\nX_train.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:10.287961Z","iopub.execute_input":"2022-08-10T13:05:10.288399Z","iopub.status.idle":"2022-08-10T13:05:10.304674Z","shell.execute_reply.started":"2022-08-10T13:05:10.288367Z","shell.execute_reply":"2022-08-10T13:05:10.303322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Preprocessing for numerical data\nnumerical_transformer = SimpleImputer(strategy='mean') \n\n# Preprocessing for categorical data\ncategorical_transformer = categorical_transformer = Pipeline(steps=[\n    ('imputer', SimpleImputer(strategy='most_frequent')),\n    ('onehot', OneHotEncoder(handle_unknown='ignore'))\n]) \n\n# Bundle preprocessing for numerical and categorical data\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num', numerical_transformer, numerical_cols),\n        ('cat', categorical_transformer, categorical_cols)\n    ])\n        ","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:15.296437Z","iopub.execute_input":"2022-08-10T13:05:15.296920Z","iopub.status.idle":"2022-08-10T13:05:15.303760Z","shell.execute_reply.started":"2022-08-10T13:05:15.296886Z","shell.execute_reply":"2022-08-10T13:05:15.302645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***Modeling***","metadata":{}},{"cell_type":"markdown","source":"# ***1. Support Vector Machines***","metadata":{}},{"cell_type":"code","source":"# Define model\nmodel_svc = SVC()\n# Bundle preprocessing and modeling code in a pipeline\nmy_pipeline_svc = Pipeline(steps=[('preprocessor', preprocessor),\n                              ('model', model_svc)\n                             ])\n\n# Preprocessing of training data, fit model \nmy_pipeline_svc.fit(X_train, y_train)\n\n# Preprocessing of test data\npredictions = my_pipeline_svc.predict(X_test)\n\n# Evaluate the model\nscore_svc=my_pipeline_svc.score(X_valid,y_valid)\nprint('score from 1:',score_svc)\n","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:21.469267Z","iopub.execute_input":"2022-08-10T13:05:21.469961Z","iopub.status.idle":"2022-08-10T13:05:21.553527Z","shell.execute_reply.started":"2022-08-10T13:05:21.469924Z","shell.execute_reply":"2022-08-10T13:05:21.552337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***2. k-Nearest Neighbors algorithm***","metadata":{}},{"cell_type":"code","source":"# Define model\nmodel_knn = KNeighborsClassifier(n_neighbors = 3)\n# Bundle preprocessing and modeling code in a pipeline\nmy_pipeline_knn = Pipeline(steps=[('preprocessor', preprocessor),\n                              ('model', model_knn)\n                             ])\n\n# Preprocessing of training data, fit model \nmy_pipeline_knn.fit(X_train, y_train)\n\n# Preprocessing of test data\npredictions = my_pipeline_knn.predict(X_test)\n\n# Evaluate the model\nscore_knn=my_pipeline_knn.score(X_valid,y_valid)\nprint('score from 1:',score_knn)\n\n","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:26.284926Z","iopub.execute_input":"2022-08-10T13:05:26.285424Z","iopub.status.idle":"2022-08-10T13:05:26.344587Z","shell.execute_reply.started":"2022-08-10T13:05:26.285387Z","shell.execute_reply":"2022-08-10T13:05:26.343357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***3. Decision Tree***","metadata":{}},{"cell_type":"code","source":"# Define model\nmodel_decision_tree = DecisionTreeClassifier()\n# Bundle preprocessing and modeling code in a pipeline\nmy_pipeline_decision_tree = Pipeline(steps=[('preprocessor', preprocessor),\n                              ('model', model_decision_tree)\n                             ])\n\n# Preprocessing of training data, fit model \nmy_pipeline_decision_tree.fit(X_train, y_train)\n\n# Preprocessing of test data\npredictions = my_pipeline_decision_tree.predict(X_test)\n\n# Evaluate the model\nscore_decision_tree=my_pipeline_decision_tree.score(X_valid,y_valid)\nprint('score from 1:',score_decision_tree)\n\n","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:31.806331Z","iopub.execute_input":"2022-08-10T13:05:31.807497Z","iopub.status.idle":"2022-08-10T13:05:31.848966Z","shell.execute_reply.started":"2022-08-10T13:05:31.807455Z","shell.execute_reply":"2022-08-10T13:05:31.847493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***4. Random Forests***","metadata":{}},{"cell_type":"code","source":"# Define model\nmodel_rf = RandomForestClassifier(n_estimators=100)\n# Bundle preprocessing and modeling code in a pipeline\nmy_pipeline_rf = Pipeline(steps=[('preprocessor', preprocessor),\n                              ('model', model_rf)\n                             ])\n\n\n# Preprocessing of training data, fit model \nmy_pipeline_rf.fit(X_train, y_train)\n\n# Preprocessing of test data\npredictions = my_pipeline_rf.predict(X_test)\n\n\n# Evaluate the model\nscore_rf=my_pipeline_rf.score(X_valid,y_valid)\nprint('score from 1:',score_rf)\n\n","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:38.195588Z","iopub.execute_input":"2022-08-10T13:05:38.196035Z","iopub.status.idle":"2022-08-10T13:05:38.462324Z","shell.execute_reply.started":"2022-08-10T13:05:38.195998Z","shell.execute_reply":"2022-08-10T13:05:38.461421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ***Model evaluation***","metadata":{}},{"cell_type":"code","source":"# Create a dataframe of the models\nmodels = pd.DataFrame({\n    'Model': ['Support Vector Machines', 'KNN', \n              'Random Forest','Decision Tree'],\n    'Score': [score_svc, score_knn, \n              score_rf, score_decision_tree]})\n# Sorting models with the highest score\nmodels.sort_values(by='Score', ascending=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:46.259385Z","iopub.execute_input":"2022-08-10T13:05:46.259866Z","iopub.status.idle":"2022-08-10T13:05:46.275887Z","shell.execute_reply.started":"2022-08-10T13:05:46.259831Z","shell.execute_reply":"2022-08-10T13:05:46.274219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output = pd.DataFrame({'PassengerId': X_test.PassengerId, 'Survived': predictions})\noutput.to_csv('submission.csv', index=False)\nprint(\"Your submission was successfully saved!\")","metadata":{"execution":{"iopub.status.busy":"2022-08-10T13:05:51.863434Z","iopub.execute_input":"2022-08-10T13:05:51.863957Z","iopub.status.idle":"2022-08-10T13:05:51.876262Z","shell.execute_reply.started":"2022-08-10T13:05:51.863918Z","shell.execute_reply":"2022-08-10T13:05:51.875123Z"},"trusted":true},"execution_count":null,"outputs":[]}]}