{"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-15T06:02:17.172038Z","iopub.execute_input":"2022-07-15T06:02:17.173462Z","iopub.status.idle":"2022-07-15T06:02:17.208022Z","shell.execute_reply.started":"2022-07-15T06:02:17.173305Z","shell.execute_reply":"2022-07-15T06:02:17.206714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### load dataset","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyarrow as pa\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.model_selection import KFold\nimport scipy.stats as stats\n\nfrom collections import defaultdict","metadata":{"execution":{"iopub.status.busy":"2022-07-15T06:02:17.210488Z","iopub.execute_input":"2022-07-15T06:02:17.211628Z","iopub.status.idle":"2022-07-15T06:02:18.329099Z","shell.execute_reply.started":"2022-07-15T06:02:17.211580Z","shell.execute_reply":"2022-07-15T06:02:18.327830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### read data","metadata":{}},{"cell_type":"code","source":"df_train = pd.read_parquet(\"../input/amex-parquet/train_data.parquet\")\ndf_test = pd.read_parquet(\"../input/amex-parquet/test_data.parquet\")\ndf_train_label = pd.read_csv(\"../input/amex-default-prediction/train_labels.csv\")\ndf_sample_submission = pd.read_csv(\"../input/amex-default-prediction/sample_submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-07-15T06:02:18.330518Z","iopub.execute_input":"2022-07-15T06:02:18.330843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### parameters","metadata":{}},{"cell_type":"code","source":"folds = 7    # number of Kfolds\noutput_path = \"./logistic_Kfold3.csv\"    # output path for submission data","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### process data","metadata":{}},{"cell_type":"code","source":"# join df_train_label to df_train\ndf_train = pd.merge(df_train, df_train_label, how=\"inner\", on=\"customer_ID\")\n# concat df_train and df_test\ndf_all = pd.concat([df_train, df_test])\n# group by customer ID and mean\ndf_all_groupby_customerID = df_all.groupby(\"customer_ID\").mean()\n# drop columns which have any nan data\ndf_all_dropna = df_all_groupby_customerID.dropna(how=\"any\", axis=1)\n# add target column to df_all\ndf_all_dropna = df_all_dropna.assign(target = df_all_groupby_customerID[\"target\"])\n# extract train and test data from all processed data\ndf_train_processed = df_all_dropna[df_all_dropna[\"target\"].notna()]\ndf_test_processed = df_all_dropna[df_all_dropna[\"target\"].isnull()].drop(columns=[\"target\"])\n# drop unnecesar columns\ndf_X = df_train_processed.drop(columns=[\"target\"])\ndf_y = df_train_processed[\"target\"]\n# transform dataframe to numpy array\nX = df_X.values\ny = df_y.values","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Kfold","metadata":{}},{"cell_type":"code","source":"# get index for K cross validation\nkfold = KFold(n_splits=folds)\n# divide data into K by KFold\nlist_train_index = []\nlist_val_index = []\n\nfor train_index, val_index in kfold.split(X):\n    list_train_index.append(train_index)\n    list_val_index.append(val_index)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Logistic regression","metadata":{}},{"cell_type":"code","source":"list_classifiers = []\nfor n in range(folds):\n    print(\"fold: \", n)\n    # create classifier\n    classifier = LogisticRegression()\n    \n    # train classifier\n    classifier.fit(X[list_train_index[n]], y[list_train_index[n]])\n    \n    list_classifiers.append(classifier)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for n in range(folds):\n    print(\"fold: \", n)\n    # prediction\n    y_pred = list_classifiers[n].predict(X[list_val_index[n]])\n    \n    # scores\n    print('confusion matrix = \\n', confusion_matrix(y_true=y[list_val_index[n]], y_pred=y_pred))\n    print('accuracy = ', accuracy_score(y_true=y[list_val_index[n]], y_pred=y_pred))\n    print('precision = ', precision_score(y_true=y[list_val_index[n]], y_pred=y_pred))\n    print('recall = ', recall_score(y_true=y[list_val_index[n]], y_pred=y_pred))\n    print('f1 score = ', f1_score(y_true=y[list_val_index[n]], y_pred=y_pred))\n    \n    y_score = list_classifiers[n].predict_proba(X[list_val_index[n]])[:, 1] # 検証データがクラス1に属する確率\n    fpr, tpr, thresholds = roc_curve(y_true=y[list_val_index[n]], y_score=y_score)\n\n    plt.plot(fpr, tpr, label='roc curve (area = %0.3f)' % auc(fpr, tpr))\n    plt.plot([0, 1], [0, 1], linestyle='--', label='random')\n    plt.plot([0, 0, 1], [0, 1, 1], linestyle='--', label='ideal')\n    plt.legend()\n    plt.xlabel('false positive rate')\n    plt.ylabel('true positive rate')\n    plt.show()\n    print(\"\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# extract columns which used for training\ndf_submit = df_test_processed[df_X.columns]\n\n# transform dataframe to numpy\nX_submit = df_submit.values\n\n# calculate submits\ny_submit_mean = 0.0\nfor n in range(folds):\n    y_submit = list_classifiers[n].predict(X_submit)\n    y_submit_mean += y_submit / folds\n\ndf_sample_submission[\"prediction\"] = np.round(y_submit_mean, 0).astype(np.int)\ndf_sample_submission.to_csv(output_path, index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}