{"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":"2023-01-06T01:57:30.162205Z","iopub.execute_input":"2023-01-06T01:57:30.162718Z","iopub.status.idle":"2023-01-06T01:57:30.198992Z","shell.execute_reply.started":"2023-01-06T01:57:30.162604Z","shell.execute_reply":"2023-01-06T01:57:30.197526Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\npd.reset_option('display.max_colwidth', None)\n\ntrain = pd.read_csv('/kaggle/input/emsi-5iir-ds/train.csv')\ntest = pd.read_csv('/kaggle/input/emsi-5iir-ds/test.csv')","metadata":{"execution":{"iopub.status.busy":"2023-01-06T01:58:31.621976Z","iopub.execute_input":"2023-01-06T01:58:31.622405Z","iopub.status.idle":"2023-01-06T01:58:48.101420Z","shell.execute_reply.started":"2023-01-06T01:58:31.622368Z","shell.execute_reply":"2023-01-06T01:58:48.100296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2023-01-06T01:59:10.997641Z","iopub.execute_input":"2023-01-06T01:59:10.998123Z","iopub.status.idle":"2023-01-06T01:59:11.026463Z","shell.execute_reply.started":"2023-01-06T01:59:10.998080Z","shell.execute_reply":"2023-01-06T01:59:11.025170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\n\nfrom fastai.tabular.core import cont_cat_split\n\nfrom yellowbrick.classifier import confusion_matrix\nfrom yellowbrick.classifier.rocauc import roc_auc","metadata":{"execution":{"iopub.status.busy":"2023-01-06T01:59:46.095022Z","iopub.execute_input":"2023-01-06T01:59:46.095609Z","iopub.status.idle":"2023-01-06T01:59:49.227758Z","shell.execute_reply.started":"2023-01-06T01:59:46.095570Z","shell.execute_reply":"2023-01-06T01:59:49.226571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def basic_info(df:pd.DataFrame):\n    s = \"\"\n    count = 1\n    for c in df.columns:\n        s+= f\"{count} - {c}\\n\"\n        s+= f\"    No. of unique values {df[c].nunique()}\\n\"\n        s+= f\"    Sample of unique values {df[c].unique()[0:10]}\\n\"\n        s+= \"\\n\"\n        count += 1\n    return s\ndef expand_feature_27(data):\n    # This function was adapted from the following notebooks:\n    # https://www.kaggle.com/code/paultimothymooney/getting-started-with-tensorflow-decision-forests\n    for df in [data]:\n        # Extract the 10 letters of f_27 into individual features\n        for i in range(10):   # defines a number from 0 to 25 for each letter, for example if ch1 is A then get 0 and so on\n            df[f'ch{i}'] = df.f_27.str.get(i).apply(ord) - ord('A')\n    return data","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:00:39.150709Z","iopub.execute_input":"2023-01-06T02:00:39.151360Z","iopub.status.idle":"2023-01-06T02:00:39.159668Z","shell.execute_reply.started":"2023-01-06T02:00:39.151319Z","shell.execute_reply":"2023-01-06T02:00:39.158382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# loading the data into a pandas DataFrame (for exploratory analysis)\ntrain_df = pd.read_csv('/kaggle/input/emsi-5iir-ds/train.csv')    # reading training file\ntest_df = pd.read_csv('/kaggle/input/emsi-5iir-ds/test.csv')    # reading test file\ntrain_df.shape    # viewing dataframe dimension","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:01:09.650942Z","iopub.execute_input":"2023-01-06T02:01:09.651348Z","iopub.status.idle":"2023-01-06T02:01:18.519678Z","shell.execute_reply.started":"2023-01-06T02:01:09.651316Z","shell.execute_reply":"2023-01-06T02:01:18.518888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()    # viewing some examples","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:01:45.806228Z","iopub.execute_input":"2023-01-06T02:01:45.806659Z","iopub.status.idle":"2023-01-06T02:01:45.836274Z","shell.execute_reply.started":"2023-01-06T02:01:45.806621Z","shell.execute_reply":"2023-01-06T02:01:45.835036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.info()    # information about the data, number of non-null (non-missing) values and the data type","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:02:11.329549Z","iopub.execute_input":"2023-01-06T02:02:11.329977Z","iopub.status.idle":"2023-01-06T02:02:11.451956Z","shell.execute_reply.started":"2023-01-06T02:02:11.329944Z","shell.execute_reply":"2023-01-06T02:02:11.450672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = expand_feature_27(train_df)\ntest_df = expand_feature_27(test_df)\ntrain_df.columns","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:02:36.889106Z","iopub.execute_input":"2023-01-06T02:02:36.889510Z","iopub.status.idle":"2023-01-06T02:02:49.539745Z","shell.execute_reply.started":"2023-01-06T02:02:36.889479Z","shell.execute_reply":"2023-01-06T02:02:49.538793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df[['f_27', 'ch0', 'ch1', 'ch2', 'ch3', 'ch4', 'ch5', 'ch6', 'ch7', 'ch8', 'ch9',]]","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:03:10.010442Z","iopub.execute_input":"2023-01-06T02:03:10.010886Z","iopub.status.idle":"2023-01-06T02:03:10.219186Z","shell.execute_reply.started":"2023-01-06T02:03:10.010850Z","shell.execute_reply":"2023-01-06T02:03:10.217829Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# dropping features that are not needed for training, as feature 27 has been expanded to others with numerical values, \n# it is no longer needed\ntrain_df = train_df.drop(columns=['id', 'f_27'])\ntest_df = test_df.drop(columns=['id', 'f_27'])","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:03:35.365219Z","iopub.execute_input":"2023-01-06T02:03:35.365630Z","iopub.status.idle":"2023-01-06T02:03:35.674679Z","shell.execute_reply.started":"2023-01-06T02:03:35.365594Z","shell.execute_reply":"2023-01-06T02:03:35.673580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# spliting continuous from categorical variables, and displaying their names\ncont_col, cat_col = cont_cat_split(train_df)\nprint(f'Continuous Columns: {cont_col}\\n')\nprint(f'Categorical Columns: {cat_col}')","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:03:55.875149Z","iopub.execute_input":"2023-01-06T02:03:55.875556Z","iopub.status.idle":"2023-01-06T02:03:56.039252Z","shell.execute_reply.started":"2023-01-06T02:03:55.875524Z","shell.execute_reply":"2023-01-06T02:03:56.037315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(basic_info(train_df[cont_col]))    # printing basic information of continuous variables","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:04:32.830446Z","iopub.execute_input":"2023-01-06T02:04:32.831458Z","iopub.status.idle":"2023-01-06T02:04:34.766552Z","shell.execute_reply.started":"2023-01-06T02:04:32.831415Z","shell.execute_reply":"2023-01-06T02:04:34.763760Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(basic_info(train_df[cat_col]))    # printing basic information of categorical variables","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:05:36.324007Z","iopub.execute_input":"2023-01-06T02:05:36.325063Z","iopub.status.idle":"2023-01-06T02:05:36.677079Z","shell.execute_reply.started":"2023-01-06T02:05:36.325013Z","shell.execute_reply":"2023-01-06T02:05:36.675993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.heatmap(abs(train_df[cont_col].corr()))    # visualizing the correlation between the continuous variables","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:06:03.394113Z","iopub.execute_input":"2023-01-06T02:06:03.394547Z","iopub.status.idle":"2023-01-06T02:06:04.649023Z","shell.execute_reply.started":"2023-01-06T02:06:03.394512Z","shell.execute_reply":"2023-01-06T02:06:04.647603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.heatmap(abs(train_df[cat_col].corr()))    # visualizing the correlation between the categorical variables","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:06:29.439843Z","iopub.execute_input":"2023-01-06T02:06:29.440248Z","iopub.status.idle":"2023-01-06T02:06:31.912089Z","shell.execute_reply.started":"2023-01-06T02:06:29.440215Z","shell.execute_reply":"2023-01-06T02:06:31.909582Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plotting boxplot to visualize the distribution of values of continuous variables\ni = 0\n# creating a figure with dimensions equal to the square root of the number of continuous variables\nbox_fig, box_axs = plt.subplots(int(np.sqrt(len(cont_col))), int(np.sqrt(len(cont_col))), figsize=(20, 18))\nfor ax in box_fig.get_axes():    # looping through the axes created for the figure (4x4)\n    sns.boxplot(x=train_df[cont_col[i]], hue=train_df['target'], ax=ax)    # plotting the boxplot for each variable\n    i += 1\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:07:07.533313Z","iopub.execute_input":"2023-01-06T02:07:07.533720Z","iopub.status.idle":"2023-01-06T02:07:10.141886Z","shell.execute_reply.started":"2023-01-06T02:07:07.533673Z","shell.execute_reply":"2023-01-06T02:07:10.138837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plotting bar to visualize the distribution of values of continuous variables\ni = 0\n# creating a figure with dimensions equal to the square root of the number of categorical variables\nbar_fig, bar_axs = plt.subplots(int(np.sqrt(len(cat_col))), int(np.sqrt(len(cat_col))), figsize=(20, 18))\nfor ax in bar_fig.get_axes():    # looping through the axes created for the figure (5x5)\n    train_df[cat_col[i]].value_counts().plot.bar(ax=ax, title=cat_col[i])    # plotting bar graph for each variable\n    i += 1\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:07:31.346671Z","iopub.execute_input":"2023-01-06T02:07:31.347864Z","iopub.status.idle":"2023-01-06T02:07:35.810352Z","shell.execute_reply.started":"2023-01-06T02:07:31.347813Z","shell.execute_reply":"2023-01-06T02:07:35.809217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plotting bar to visualize the distribution of values of continuous variables\ni = 0\n# creating a figure with dimensions equal to the square root of the number of categorical variables\nbar_fig, bar_axs = plt.subplots(int(np.sqrt(len(cat_col))), int(np.sqrt(len(cat_col))), figsize=(20, 18))\nfor ax in bar_fig.get_axes():    # looping through the axes created for the figure (5x5)\n    train_df[cat_col[i]].value_counts().plot.bar(ax=ax, title=cat_col[i])    # plotting bar graph for each variable\n    i += 1\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:08:15.341921Z","iopub.execute_input":"2023-01-06T02:08:15.342463Z","iopub.status.idle":"2023-01-06T02:08:19.941405Z","shell.execute_reply.started":"2023-01-06T02:08:15.342417Z","shell.execute_reply":"2023-01-06T02:08:19.940318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# checking how many percent each value of the categorical variables represents\n# creating a list with the names of the categorical variables that I want to check\nf_cat_col = ['f_07', 'f_08', 'f_09', 'f_10', 'f_11', 'f_12', 'f_13', 'f_14', 'f_15', 'f_16', 'f_17', 'f_18', ]\nfor column in f_cat_col:    # para cada variavel na lista\n    percent = train_df[column].value_counts(normalize=True) * 100    # calculates the relative frequency of unique values in percentage\n    display(percent)\n    print('\\n')","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:08:42.954707Z","iopub.execute_input":"2023-01-06T02:08:42.955104Z","iopub.status.idle":"2023-01-06T02:08:43.123326Z","shell.execute_reply.started":"2023-01-06T02:08:42.955072Z","shell.execute_reply":"2023-01-06T02:08:43.122215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# joining values with the very low percentage in a single\ntrain_df['f_07'] = train_df['f_07'].replace([5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 5)\ntrain_df['f_08'] = train_df['f_08'].replace([5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16], 5)\ntrain_df['f_09'] = train_df['f_09'].replace([5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 5)\ntrain_df['f_10'] = train_df['f_10'].replace([5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 5)\ntrain_df['f_11'] = train_df['f_11'].replace([4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 4)\ntrain_df['f_12'] = train_df['f_12'].replace([6, 7, 8, 9, 10, 11, 12, 13, 14, 16], 6)\ntrain_df['f_13'] = train_df['f_13'].replace([5, 6, 7, 8, 9, 10, 11, 12], 5)\ntrain_df['f_14'] = train_df['f_14'].replace([4, 5, 6, 7, 8, 9, 10, 11, 12, 14], 4)\ntrain_df['f_15'] = train_df['f_15'].replace([5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 5)\ntrain_df['f_16'] = train_df['f_16'].replace([5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 5)\ntrain_df['f_17'] = train_df['f_17'].replace([4, 5, 6, 7, 8, 9, 10, 11, 12, 14], 4)\ntrain_df['f_18'] = train_df['f_15'].replace([5, 6, 7, 8, 9, 10, 11, 12, 13], 5)","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:09:52.418229Z","iopub.execute_input":"2023-01-06T02:09:52.418636Z","iopub.status.idle":"2023-01-06T02:09:52.670624Z","shell.execute_reply.started":"2023-01-06T02:09:52.418604Z","shell.execute_reply":"2023-01-06T02:09:52.669156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# checking again to see if the result is positive\nfor column in f_cat_col:\n    percent = train_df[column].value_counts(normalize=True) * 100\n    display(percent)\n    print('\\n')","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:10:21.582630Z","iopub.execute_input":"2023-01-06T02:10:21.583052Z","iopub.status.idle":"2023-01-06T02:10:21.743585Z","shell.execute_reply.started":"2023-01-06T02:10:21.583017Z","shell.execute_reply":"2023-01-06T02:10:21.742469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"i = 0\nbar2_fig, bar2_axs = plt.subplots(3, 4, figsize=(15, 10))\nfor ax in bar2_fig.get_axes():\n    train_df[f_cat_col[i]].value_counts().plot.bar(ax=ax, title=f_cat_col[i])\n    i += 1\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:10:46.366295Z","iopub.execute_input":"2023-01-06T02:10:46.366800Z","iopub.status.idle":"2023-01-06T02:10:48.026558Z","shell.execute_reply.started":"2023-01-06T02:10:46.366760Z","shell.execute_reply":"2023-01-06T02:10:48.025243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = train_df.drop(columns=['target'])    # input\ny = train_df.target    # output\n\n# split the data into training and testing\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)\n\nprint(f'X_train shape: {X_train.shape}')\nprint(f'y_train shape: {y_train.shape}')\nprint(f'-' * 27)\nprint(f'X_test shape: {X_test.shape}')\nprint(f'y_test shape: {y_test.shape}')","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:11:15.768286Z","iopub.execute_input":"2023-01-06T02:11:15.768651Z","iopub.status.idle":"2023-01-06T02:11:16.693256Z","shell.execute_reply.started":"2023-01-06T02:11:15.768621Z","shell.execute_reply":"2023-01-06T02:11:16.691759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tps_model = RandomForestClassifier(random_state=0)\ntps_model.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:16:07.894010Z","iopub.execute_input":"2023-01-06T02:16:07.894407Z","iopub.status.idle":"2023-01-06T02:25:44.865820Z","shell.execute_reply.started":"2023-01-06T02:16:07.894376Z","shell.execute_reply":"2023-01-06T02:25:44.864785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(6, 6))\nconfusion_matrix(tps_model, X_train, y_train, X_test, y_test, percent=True)\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:26:49.817660Z","iopub.execute_input":"2023-01-06T02:26:49.818293Z","iopub.status.idle":"2023-01-06T02:27:19.489482Z","shell.execute_reply.started":"2023-01-06T02:26:49.818247Z","shell.execute_reply":"2023-01-06T02:27:19.487981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(6, 6))\nroc_auc(tps_model, X_train, y_train, X_test=X_test, y_test=y_test)\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:27:40.523951Z","iopub.execute_input":"2023-01-06T02:27:40.524324Z","iopub.status.idle":"2023-01-06T02:28:10.213244Z","shell.execute_reply.started":"2023-01-06T02:27:40.524296Z","shell.execute_reply":"2023-01-06T02:28:10.212241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_submission_df = pd.read_csv('/kaggle/input/emsi-5iir-ds/sample_submission.csv')\nsample_submission_df['target'] = tps_model.predict(test_df)\nsample_submission_df.to_csv('/kaggle/working/submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-01-06T02:29:24.927746Z","iopub.execute_input":"2023-01-06T02:29:24.928154Z","iopub.status.idle":"2023-01-06T02:30:04.113914Z","shell.execute_reply.started":"2023-01-06T02:29:24.928119Z","shell.execute_reply":"2023-01-06T02:30:04.112673Z"},"trusted":true},"execution_count":null,"outputs":[]}]}