{"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\nimport 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\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","_kg_hide-input":false,"execution":{"iopub.status.busy":"2022-12-29T13:49:13.871796Z","iopub.execute_input":"2022-12-29T13:49:13.872891Z","iopub.status.idle":"2022-12-29T13:49:18.156415Z","shell.execute_reply.started":"2022-12-29T13:49:13.872781Z","shell.execute_reply":"2022-12-29T13:49:18.154901Z"},"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\n\n\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":"2022-12-29T13:49:18.158675Z","iopub.execute_input":"2022-12-29T13:49:18.159304Z","iopub.status.idle":"2022-12-29T13:49:18.169951Z","shell.execute_reply.started":"2022-12-29T13:49:18.159260Z","shell.execute_reply":"2022-12-29T13:49:18.168362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Exploratory data analysis and feature engineering","metadata":{}},{"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":"2022-12-29T13:49:18.171589Z","iopub.execute_input":"2022-12-29T13:49:18.171989Z","iopub.status.idle":"2022-12-29T13:49:36.299034Z","shell.execute_reply.started":"2022-12-29T13:49:18.171933Z","shell.execute_reply":"2022-12-29T13:49:36.297663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()    # viewing some examples","metadata":{"execution":{"iopub.status.busy":"2022-12-29T13:49:36.301799Z","iopub.execute_input":"2022-12-29T13:49:36.302162Z","iopub.status.idle":"2022-12-29T13:49:36.339680Z","shell.execute_reply.started":"2022-12-29T13:49:36.302131Z","shell.execute_reply":"2022-12-29T13:49:36.338357Z"},"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":"2022-12-29T13:49:36.341215Z","iopub.execute_input":"2022-12-29T13:49:36.341578Z","iopub.status.idle":"2022-12-29T13:49:36.464837Z","shell.execute_reply.started":"2022-12-29T13:49:36.341546Z","shell.execute_reply":"2022-12-29T13:49:36.463304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Expanding feature 27 to more features, each additional feature represents a character from feature 27\n# as we know that the strings in feature 27 consist of 10 characters, so we will have 10 new features, each representing\n# a character (ch1, ch2, ch3, etc) containing an integer numeric value representing a letter of the alphabet, from 0 to 25\n# if the character 1 is the letter a, then the feature will receive 0, if it is b, it will receive 1 and so on\ntrain_df = expand_feature_27(train_df)\ntest_df = expand_feature_27(test_df)\ntrain_df.columns","metadata":{"execution":{"iopub.status.busy":"2022-12-29T13:49:36.466130Z","iopub.execute_input":"2022-12-29T13:49:36.466602Z","iopub.status.idle":"2022-12-29T13:49:49.146637Z","shell.execute_reply.started":"2022-12-29T13:49:36.466568Z","shell.execute_reply":"2022-12-29T13:49:49.145335Z"},"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":"2022-12-29T13:49:49.148251Z","iopub.execute_input":"2022-12-29T13:49:49.149663Z","iopub.status.idle":"2022-12-29T13:49:49.366959Z","shell.execute_reply.started":"2022-12-29T13:49:49.149620Z","shell.execute_reply":"2022-12-29T13:49:49.365783Z"},"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":"2022-12-29T13:49:49.368681Z","iopub.execute_input":"2022-12-29T13:49:49.368993Z","iopub.status.idle":"2022-12-29T13:49:49.787448Z","shell.execute_reply.started":"2022-12-29T13:49:49.368965Z","shell.execute_reply":"2022-12-29T13:49:49.786287Z"},"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":"2022-12-29T13:49:49.788756Z","iopub.execute_input":"2022-12-29T13:49:49.789160Z","iopub.status.idle":"2022-12-29T13:49:49.949163Z","shell.execute_reply.started":"2022-12-29T13:49:49.789126Z","shell.execute_reply":"2022-12-29T13:49:49.947794Z"},"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":"2022-12-29T13:49:49.953108Z","iopub.execute_input":"2022-12-29T13:49:49.953505Z","iopub.status.idle":"2022-12-29T13:49:52.179557Z","shell.execute_reply.started":"2022-12-29T13:49:49.953460Z","shell.execute_reply":"2022-12-29T13:49:52.178130Z"},"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":"2022-12-29T13:49:52.181979Z","iopub.execute_input":"2022-12-29T13:49:52.182508Z","iopub.status.idle":"2022-12-29T13:49:52.560924Z","shell.execute_reply.started":"2022-12-29T13:49:52.182422Z","shell.execute_reply":"2022-12-29T13:49:52.559620Z"},"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":"2022-12-29T13:49:52.563066Z","iopub.execute_input":"2022-12-29T13:49:52.563719Z","iopub.status.idle":"2022-12-29T13:49:53.851834Z","shell.execute_reply.started":"2022-12-29T13:49:52.563667Z","shell.execute_reply":"2022-12-29T13:49:53.850591Z"},"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":"2022-12-29T13:49:53.853811Z","iopub.execute_input":"2022-12-29T13:49:53.854410Z","iopub.status.idle":"2022-12-29T13:49:56.555355Z","shell.execute_reply.started":"2022-12-29T13:49:53.854376Z","shell.execute_reply":"2022-12-29T13:49:56.554523Z"},"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":"2022-12-29T13:49:56.556867Z","iopub.execute_input":"2022-12-29T13:49:56.557212Z","iopub.status.idle":"2022-12-29T13:49:59.194165Z","shell.execute_reply.started":"2022-12-29T13:49:56.557181Z","shell.execute_reply":"2022-12-29T13:49:59.192751Z"},"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":"2022-12-29T13:49:59.195974Z","iopub.execute_input":"2022-12-29T13:49:59.196453Z","iopub.status.idle":"2022-12-29T13:50:03.858078Z","shell.execute_reply.started":"2022-12-29T13:49:59.196407Z","shell.execute_reply":"2022-12-29T13:50:03.857033Z"},"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":"2022-12-29T13:50:03.859088Z","iopub.execute_input":"2022-12-29T13:50:03.859439Z","iopub.status.idle":"2022-12-29T13:50:04.028377Z","shell.execute_reply.started":"2022-12-29T13:50:03.859408Z","shell.execute_reply":"2022-12-29T13:50:04.027234Z"},"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":"2022-12-29T13:50:04.032387Z","iopub.execute_input":"2022-12-29T13:50:04.032783Z","iopub.status.idle":"2022-12-29T13:50:04.356667Z","shell.execute_reply.started":"2022-12-29T13:50:04.032749Z","shell.execute_reply":"2022-12-29T13:50:04.355622Z"},"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":"2022-12-29T13:50:04.357948Z","iopub.execute_input":"2022-12-29T13:50:04.358323Z","iopub.status.idle":"2022-12-29T13:50:04.526651Z","shell.execute_reply.started":"2022-12-29T13:50:04.358288Z","shell.execute_reply":"2022-12-29T13:50:04.525243Z"},"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":"2022-12-29T13:50:04.528167Z","iopub.execute_input":"2022-12-29T13:50:04.528648Z","iopub.status.idle":"2022-12-29T13:50:06.448145Z","shell.execute_reply.started":"2022-12-29T13:50:04.528603Z","shell.execute_reply":"2022-12-29T13:50:06.447010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"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":"2022-12-29T13:50:06.449441Z","iopub.execute_input":"2022-12-29T13:50:06.449810Z","iopub.status.idle":"2022-12-29T13:50:07.587468Z","shell.execute_reply.started":"2022-12-29T13:50:06.449777Z","shell.execute_reply":"2022-12-29T13:50:07.586240Z"},"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":"2022-12-29T13:50:07.590629Z","iopub.execute_input":"2022-12-29T13:50:07.591968Z","iopub.status.idle":"2022-12-29T14:01:45.340865Z","shell.execute_reply.started":"2022-12-29T13:50:07.591916Z","shell.execute_reply":"2022-12-29T14:01:45.339478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Metrics","metadata":{}},{"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":"2022-12-29T14:01:45.342804Z","iopub.execute_input":"2022-12-29T14:01:45.343276Z","iopub.status.idle":"2022-12-29T14:02:20.706229Z","shell.execute_reply.started":"2022-12-29T14:01:45.343232Z","shell.execute_reply":"2022-12-29T14:02:20.704369Z"},"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":"2022-12-29T14:02:20.708944Z","iopub.execute_input":"2022-12-29T14:02:20.711107Z","iopub.status.idle":"2022-12-29T14:02:57.148781Z","shell.execute_reply.started":"2022-12-29T14:02:20.711021Z","shell.execute_reply":"2022-12-29T14:02:57.147522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"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":"2022-12-29T14:02:57.150486Z","iopub.execute_input":"2022-12-29T14:02:57.151404Z","iopub.status.idle":"2022-12-29T14:03:42.965662Z","shell.execute_reply.started":"2022-12-29T14:02:57.151368Z","shell.execute_reply":"2022-12-29T14:03:42.964384Z"},"trusted":true},"execution_count":null,"outputs":[]}]}