{"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-12-26T14:21:44.494062Z","iopub.execute_input":"2022-12-26T14:21:44.494466Z","iopub.status.idle":"2022-12-26T14:21:44.505508Z","shell.execute_reply.started":"2022-12-26T14:21:44.494434Z","shell.execute_reply":"2022-12-26T14:21:44.503566Z"},"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":"2022-12-26T14:21:44.581626Z","iopub.execute_input":"2022-12-26T14:21:44.582638Z","iopub.status.idle":"2022-12-26T14:21:50.818236Z","shell.execute_reply.started":"2022-12-26T14:21:44.582589Z","shell.execute_reply":"2022-12-26T14:21:50.816138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-12-26T14:21:50.820766Z","iopub.execute_input":"2022-12-26T14:21:50.821181Z","iopub.status.idle":"2022-12-26T14:21:50.850240Z","shell.execute_reply.started":"2022-12-26T14:21:50.821145Z","shell.execute_reply":"2022-12-26T14:21:50.848848Z"},"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":"2022-12-26T14:21:50.852001Z","iopub.execute_input":"2022-12-26T14:21:50.852394Z","iopub.status.idle":"2022-12-26T14:21:50.860127Z","shell.execute_reply.started":"2022-12-26T14:21:50.852365Z","shell.execute_reply":"2022-12-26T14:21:50.857266Z"},"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":"2022-12-26T14:21:50.862912Z","iopub.execute_input":"2022-12-26T14:21:50.863378Z","iopub.status.idle":"2022-12-26T14:21:50.878838Z","shell.execute_reply.started":"2022-12-26T14:21:50.863342Z","shell.execute_reply":"2022-12-26T14:21:50.875941Z"},"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":"2022-12-26T14:21:50.883468Z","iopub.execute_input":"2022-12-26T14:21:50.884903Z","iopub.status.idle":"2022-12-26T14:21:57.719215Z","shell.execute_reply.started":"2022-12-26T14:21:50.884821Z","shell.execute_reply":"2022-12-26T14:21:57.718289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()    # viewing some examples","metadata":{"execution":{"iopub.status.busy":"2022-12-26T14:21:57.720792Z","iopub.execute_input":"2022-12-26T14:21:57.721355Z","iopub.status.idle":"2022-12-26T14:21:57.745078Z","shell.execute_reply.started":"2022-12-26T14:21:57.721313Z","shell.execute_reply":"2022-12-26T14:21:57.743313Z"},"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-26T14:21:57.746950Z","iopub.execute_input":"2022-12-26T14:21:57.747831Z","iopub.status.idle":"2022-12-26T14:21:57.828441Z","shell.execute_reply.started":"2022-12-26T14:21:57.747777Z","shell.execute_reply":"2022-12-26T14:21:57.827016Z"},"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":"2022-12-26T14:21:57.830464Z","iopub.execute_input":"2022-12-26T14:21:57.830924Z","iopub.status.idle":"2022-12-26T14:22:08.509059Z","shell.execute_reply.started":"2022-12-26T14:21:57.830884Z","shell.execute_reply":"2022-12-26T14:22:08.507554Z"},"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-26T14:22:08.510671Z","iopub.execute_input":"2022-12-26T14:22:08.511047Z","iopub.status.idle":"2022-12-26T14:22:08.657292Z","shell.execute_reply.started":"2022-12-26T14:22:08.511018Z","shell.execute_reply":"2022-12-26T14:22:08.655305Z"},"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-26T14:22:08.660233Z","iopub.execute_input":"2022-12-26T14:22:08.660902Z","iopub.status.idle":"2022-12-26T14:22:08.813967Z","shell.execute_reply.started":"2022-12-26T14:22:08.660842Z","shell.execute_reply":"2022-12-26T14:22:08.812996Z"},"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-26T14:22:08.815396Z","iopub.execute_input":"2022-12-26T14:22:08.815769Z","iopub.status.idle":"2022-12-26T14:22:08.911295Z","shell.execute_reply.started":"2022-12-26T14:22:08.815716Z","shell.execute_reply":"2022-12-26T14:22:08.909766Z"},"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-26T14:22:08.912706Z","iopub.execute_input":"2022-12-26T14:22:08.913126Z","iopub.status.idle":"2022-12-26T14:22:11.530628Z","shell.execute_reply.started":"2022-12-26T14:22:08.913090Z","shell.execute_reply":"2022-12-26T14:22:11.528447Z"},"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-26T14:22:11.533131Z","iopub.execute_input":"2022-12-26T14:22:11.533588Z","iopub.status.idle":"2022-12-26T14:22:11.775171Z","shell.execute_reply.started":"2022-12-26T14:22:11.533544Z","shell.execute_reply":"2022-12-26T14:22:11.773596Z"},"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-26T14:22:11.779435Z","iopub.execute_input":"2022-12-26T14:22:11.779843Z","iopub.status.idle":"2022-12-26T14:22:12.677821Z","shell.execute_reply.started":"2022-12-26T14:22:11.779813Z","shell.execute_reply":"2022-12-26T14:22:12.675230Z"},"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-26T14:22:12.679685Z","iopub.execute_input":"2022-12-26T14:22:12.680152Z","iopub.status.idle":"2022-12-26T14:22:14.397087Z","shell.execute_reply.started":"2022-12-26T14:22:12.680122Z","shell.execute_reply":"2022-12-26T14:22:14.396249Z"},"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-26T14:22:14.398491Z","iopub.execute_input":"2022-12-26T14:22:14.398960Z"},"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":{"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":{"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":{"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-26T14:23:34.332505Z","iopub.execute_input":"2022-12-26T14:23:34.332937Z","iopub.status.idle":"2022-12-26T14:23:34.485528Z","shell.execute_reply.started":"2022-12-26T14:23:34.332902Z","shell.execute_reply":"2022-12-26T14:23:34.483226Z"},"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-26T14:24:10.540156Z","iopub.execute_input":"2022-12-26T14:24:10.540598Z","iopub.status.idle":"2022-12-26T14:24:10.715985Z","shell.execute_reply.started":"2022-12-26T14:24:10.540562Z","shell.execute_reply":"2022-12-26T14:24:10.713469Z"},"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-26T14:24:19.995883Z","iopub.execute_input":"2022-12-26T14:24:19.996417Z","iopub.status.idle":"2022-12-26T14:24:21.445032Z","shell.execute_reply.started":"2022-12-26T14:24:19.996373Z","shell.execute_reply":"2022-12-26T14:24:21.444251Z"},"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-26T14:25:20.691967Z","iopub.execute_input":"2022-12-26T14:25:20.692515Z","iopub.status.idle":"2022-12-26T14:25:21.635842Z","shell.execute_reply.started":"2022-12-26T14:25:20.692470Z","shell.execute_reply":"2022-12-26T14:25:21.634875Z"},"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-26T14:25:44.411389Z","iopub.execute_input":"2022-12-26T14:25:44.411923Z","iopub.status.idle":"2022-12-26T14:37:10.467645Z","shell.execute_reply.started":"2022-12-26T14:25:44.411881Z","shell.execute_reply":"2022-12-26T14:37:10.466810Z"},"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-26T14:37:43.157447Z","iopub.execute_input":"2022-12-26T14:37:43.157796Z","iopub.status.idle":"2022-12-26T14:38:12.995836Z","shell.execute_reply.started":"2022-12-26T14:37:43.157765Z","shell.execute_reply":"2022-12-26T14:38:12.995070Z"},"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-26T14:38:43.005166Z","iopub.execute_input":"2022-12-26T14:38:43.006022Z","iopub.status.idle":"2022-12-26T14:39:15.786680Z","shell.execute_reply.started":"2022-12-26T14:38:43.005967Z","shell.execute_reply":"2022-12-26T14:39:15.785989Z"},"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":"2022-12-26T14:46:05.174049Z","iopub.execute_input":"2022-12-26T14:46:05.174508Z","iopub.status.idle":"2022-12-26T14:46:48.105403Z","shell.execute_reply.started":"2022-12-26T14:46:05.174471Z","shell.execute_reply":"2022-12-26T14:46:48.102509Z"},"trusted":true},"execution_count":null,"outputs":[]}]}