{"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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-22T10:45:19.302796Z","iopub.execute_input":"2022-07-22T10:45:19.303192Z","iopub.status.idle":"2022-07-22T10:45:19.313073Z","shell.execute_reply.started":"2022-07-22T10:45:19.303161Z","shell.execute_reply":"2022-07-22T10:45:19.311756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt # data visualization\nimport seaborn as sns # data visualization\nimport os \nimport warnings\nwarnings.filterwarnings(\"ignore\")\n","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.348942Z","iopub.execute_input":"2022-07-22T10:45:19.349687Z","iopub.status.idle":"2022-07-22T10:45:19.355025Z","shell.execute_reply.started":"2022-07-22T10:45:19.349650Z","shell.execute_reply":"2022-07-22T10:45:19.353981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_data():\n    train_data = pd.read_csv(\"/kaggle/input/titanic/train.csv\")\n    print(\"Train data imported successfully!!\")\n    print(\"-\"*50)\n    test_data = pd.read_csv(\"/kaggle/input/titanic/test.csv\")\n    print(\"Test data imported successfully!!\")\n    return train_data , test_data","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.389125Z","iopub.execute_input":"2022-07-22T10:45:19.390177Z","iopub.status.idle":"2022-07-22T10:45:19.395291Z","shell.execute_reply.started":"2022-07-22T10:45:19.390134Z","shell.execute_reply":"2022-07-22T10:45:19.394421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data , test_data = read_data()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.416094Z","iopub.execute_input":"2022-07-22T10:45:19.416504Z","iopub.status.idle":"2022-07-22T10:45:19.432817Z","shell.execute_reply.started":"2022-07-22T10:45:19.416469Z","shell.execute_reply":"2022-07-22T10:45:19.431934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head(3)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.449420Z","iopub.execute_input":"2022-07-22T10:45:19.450222Z","iopub.status.idle":"2022-07-22T10:45:19.466517Z","shell.execute_reply.started":"2022-07-22T10:45:19.450179Z","shell.execute_reply":"2022-07-22T10:45:19.465709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.info()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.473124Z","iopub.execute_input":"2022-07-22T10:45:19.473685Z","iopub.status.idle":"2022-07-22T10:45:19.487586Z","shell.execute_reply.started":"2022-07-22T10:45:19.473652Z","shell.execute_reply":"2022-07-22T10:45:19.486593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ==============================================================================\n#  Missed Values\n# ==============================================================================\n\ntrain_data.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.489710Z","iopub.execute_input":"2022-07-22T10:45:19.490076Z","iopub.status.idle":"2022-07-22T10:45:19.499570Z","shell.execute_reply.started":"2022-07-22T10:45:19.490024Z","shell.execute_reply":"2022-07-22T10:45:19.498512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ==============================================================================\n# Data Cleaning:\n# ==============================================================================\n\n# Dropping Unuseful feature because it has too many missed values:\n\ntrain_data.drop(columns = [\"Cabin\"] , inplace = True)\ntrain_data.drop(columns = [\"Ticket\"] , inplace = True)\n\n\n# ==============================================================================\n#  Fill missed embarked values:  \n\ntrain_data.Embarked = train_data.Embarked.fillna(train_data.Embarked.dropna().max())\n\n# ==============================================================================\n#  Fill missed age values:  \n\ntrain_data['Sex'] = train_data['Sex'].map( {'female': 1, 'male': 0} ).astype(int)\nguess_ages = np.zeros((2,3))\nfor i in range(0, 2):\n    for j in range(0, 3):\n        guess_df = train_data[(train_data['Sex'] == i) & \\\n                              (train_data['Pclass'] == j+1)]['Age'].dropna()\n        age_guess = guess_df.median()\n\n        # Convert random age float to nearest .5 age\n        guess_ages[i,j] = int( age_guess/0.5 + 0.5 ) * 0.5\n\nfor i in range(0, 2):\n    for j in range(0, 3):\n        train_data.loc[ (train_data.Age.isnull()) & (train_data.Sex == i) & (train_data.Pclass == j+1),\\\n                'Age'] = guess_ages[i,j]\n\ntrain_data['Age'] = train_data['Age'].astype(int)\ntrain_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.508990Z","iopub.execute_input":"2022-07-22T10:45:19.509770Z","iopub.status.idle":"2022-07-22T10:45:19.557010Z","shell.execute_reply.started":"2022-07-22T10:45:19.509717Z","shell.execute_reply":"2022-07-22T10:45:19.555829Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.isnull().sum()\n","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.560266Z","iopub.execute_input":"2022-07-22T10:45:19.561048Z","iopub.status.idle":"2022-07-22T10:45:19.571559Z","shell.execute_reply.started":"2022-07-22T10:45:19.560986Z","shell.execute_reply":"2022-07-22T10:45:19.570488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#No More Missed Values !!!\n\n#Now Let's see the correlation between the features and our target.","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.573418Z","iopub.execute_input":"2022-07-22T10:45:19.573885Z","iopub.status.idle":"2022-07-22T10:45:19.582600Z","shell.execute_reply.started":"2022-07-22T10:45:19.573841Z","shell.execute_reply":"2022-07-22T10:45:19.581418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.corr()[\"Survived\"].sort_values(ascending=False)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.585047Z","iopub.execute_input":"2022-07-22T10:45:19.586078Z","iopub.status.idle":"2022-07-22T10:45:19.602197Z","shell.execute_reply.started":"2022-07-22T10:45:19.586017Z","shell.execute_reply":"2022-07-22T10:45:19.600982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"From the correlation above:\n\nSex and Fare has strong positive correlation with the target.\nPassengerId has very weak correlation with the target.\nPclass has strong negative correlation with the target.\nIt's obviouse that Data Engineering is very important for this problem.\n\nNote : This approach to feature selection will likely fail if there are important interactions between attributes where only one of the attributes is significant","metadata":{}},{"cell_type":"markdown","source":"Let's see the correlation between all our features:","metadata":{}},{"cell_type":"code","source":"sns.set(rc = {'figure.figsize':(10,6)})\nsns.heatmap(train_data.corr(), annot = True, fmt='.2g',cmap= 'YlGnBu')","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:19.603896Z","iopub.execute_input":"2022-07-22T10:45:19.604653Z","iopub.status.idle":"2022-07-22T10:45:20.204554Z","shell.execute_reply.started":"2022-07-22T10:45:19.604610Z","shell.execute_reply":"2022-07-22T10:45:20.203414Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head()\n","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:20.206495Z","iopub.execute_input":"2022-07-22T10:45:20.207693Z","iopub.status.idle":"2022-07-22T10:45:20.223910Z","shell.execute_reply.started":"2022-07-22T10:45:20.207640Z","shell.execute_reply":"2022-07-22T10:45:20.222617Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ==========================================================================================\n# Data Engineering:\n# ==========================================================================================\n\n# Family Size:\n\ntrain_data['Family_Size'] = train_data[\"Parch\"] + train_data[\"SibSp\"] + 1\n\n# ==========================================================================================\n# Is Alone:\n\ntrain_data['IsAlone'] = 0\ntrain_data.loc[train_data['Family_Size'] == 1, 'IsAlone'] = 1\n\n# ==========================================================================================\n# Age Band:\n\ntrain_data.loc[ train_data['Age'] <= 16, 'Age'] = 0\ntrain_data.loc[(train_data['Age'] > 16) & (train_data['Age'] <= 32), 'Age'] = 1\ntrain_data.loc[(train_data['Age'] > 32) & (train_data['Age'] <= 48), 'Age'] = 2\ntrain_data.loc[(train_data['Age'] > 48) & (train_data['Age'] <= 64), 'Age'] = 3\ntrain_data.loc[ train_data['Age'] > 64, 'Age']\n\n# ==========================================================================================\n# Fare Band:\n\ntrain_data.loc[ train_data['Fare'] <= 130, 'Fare'] = 0\ntrain_data.loc[(train_data['Fare'] > 130) & (train_data['Fare'] <= 256), 'Fare'] = 1\ntrain_data.loc[(train_data['Fare'] > 256) & (train_data['Fare'] <= 384), 'Fare'] = 2\ntrain_data.loc[ train_data['Fare'] > 384, 'Fare'] = 3\ntrain_data['Fare'] = train_data['Fare'].astype(int)\n\n# ==========================================================================================\n# Name Title:\n\ntrain_data['Title'] = train_data.Name.str.extract(' ([A-Za-z]+)\\.', expand=False)\ntrain_data['Title'] = train_data['Title'].replace(['Lady', 'Countess','Capt', 'Col',\\\n'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')\ntrain_data['Title'] = train_data['Title'].replace('Mlle', 'Miss')\ntrain_data['Title'] = train_data['Title'].replace('Ms', 'Miss')\ntrain_data['Title'] = train_data['Title'].replace('Mme', 'Mrs')\ntitle_mapping = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Rare\": 5}\ntrain_data['Title'] = train_data['Title'].map(title_mapping)\ntrain_data['Title'] = train_data['Title'].fillna(0)\n\ntrain_data.drop(columns = [\"Name\"] , inplace = True)\n\n\n# ==========================================================================================\n# Embarked:\ntrain_data['Embarked'] = train_data['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)\n\n# ==========================================================================================\n# Passenger Id:\ntrain_data.drop(columns = [\"PassengerId\"] , inplace = True)\n# ==========================================================================================\n# ==========================================================================================\n\nprint(\"Data Engineering Finished !!!\")","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:20.226538Z","iopub.execute_input":"2022-07-22T10:45:20.226881Z","iopub.status.idle":"2022-07-22T10:45:20.267482Z","shell.execute_reply.started":"2022-07-22T10:45:20.226852Z","shell.execute_reply":"2022-07-22T10:45:20.266352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head()\n","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:20.269351Z","iopub.execute_input":"2022-07-22T10:45:20.269800Z","iopub.status.idle":"2022-07-22T10:45:20.286138Z","shell.execute_reply.started":"2022-07-22T10:45:20.269754Z","shell.execute_reply":"2022-07-22T10:45:20.284894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.corr()[\"Survived\"].sort_values(ascending=False)\n","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:20.287644Z","iopub.execute_input":"2022-07-22T10:45:20.288048Z","iopub.status.idle":"2022-07-22T10:45:20.301364Z","shell.execute_reply.started":"2022-07-22T10:45:20.287973Z","shell.execute_reply":"2022-07-22T10:45:20.299938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.set(rc = {'figure.figsize':(10,6)})\nsns.heatmap(train_data.corr(), annot = True, fmt='.2g',cmap= 'YlGnBu')","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:20.303449Z","iopub.execute_input":"2022-07-22T10:45:20.303980Z","iopub.status.idle":"2022-07-22T10:45:21.111715Z","shell.execute_reply.started":"2022-07-22T10:45:20.303936Z","shell.execute_reply":"2022-07-22T10:45:21.110606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ==========================================================================================\n# Feature Selection\n# We will select best 8 features\n# ==========================================================================================\n\n\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_classif\n\nfs = SelectKBest(score_func=f_classif, k=8)\n\nprint(\"Data shape before feature selection:\")\nprint(train_data.shape)\n\n# apply feature selection\nSelected_train_data = fs.fit_transform(train_data.iloc[:,1:], train_data[\"Survived\"])\nprint(\"Data shape After feature selection:\")\nprint(Selected_train_data.shape)","metadata":{"execution":{"iopub.status.busy":"2022-07-22T10:45:21.113314Z","iopub.execute_input":"2022-07-22T10:45:21.113675Z","iopub.status.idle":"2022-07-22T10:45:21.529640Z","shell.execute_reply.started":"2022-07-22T10:45:21.113643Z","shell.execute_reply":"2022-07-22T10:45:21.528402Z"},"trusted":true},"execution_count":null,"outputs":[]}]}