{"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":"markdown","source":"# <  개요  >\n### Football Match Probability Prediction competiton\n### 1. 주제: 축구 경기 승부 결과 예측\n### 2. 목적: 두 팀의 최근 10경기에 대한 데이터를 바탕으로 승부 결과 예측하기\n### 3. 데이터 (columns의 의미)\n#### 2019년부터 2021년까지 150,000개 이상의 전세계 축구 경기가 포함되어 있으며, 860개 이상의 리그와 9,500개 이상의 팀에 대한 데이터가 있다. \n##### 1) 해당 경기 데이터 columns\n* id: 경기 ID\n* target: train 데이터에만 있는 종속 변수인 승부 결과(값-away: 원정팀이 이김, home: 홈팀이 이김, draw: 무승부)\n* home_team_name: 홈 팀의 이름\n* away_team_name: 원정 팀의 이름\n* match_date: 경기 날짜\n* league_name: 리그 이름\n* league_id: 리그 ID(리그 ID가 달라도 리그 이름이 같을 수 있음)\n* is_cup: 컵 대회 여부(값-1:컵대회, 0:컵대회아님)\n* home_team_coach_id: 홈팀 코치의 ID\n* away_team_coach_id: 원정팀 코치의 ID\n\n##### 2) 최근 10경기 데이터 columns(숫자 1 은 가장 최근의 것을 의미하고 10은 가장 오래된 것을 의미)\n* home_team_history_match_date_{i}: 홈팀이 플레이한 마지막 i번째 경기 날짜\n* home_team_history_is_play_home_{i}: 홈팀의 홈경기 여부(값-1:홈 경기, 0:원정경기)\n* home_team_history_is_cup_{i}: 컵 대회 여부(값-1:컵대회, 0:컵대회아님)\n* home_team_history_goal_{i}: 마지막 i번째 경기에서 홈팀이 득점한 골 수\n* home_team_history_opponent_goal_{i}: 마지막 i번째 경기에서 상대팀이 득점한 골 수\n* home_team_history_rating_{i}: 마지막 i번째 경기에서 홈팀의 등급 (프리매치 등급).\n* home_team_history_opponent_rating_{i}: 마지막 i번째 경기에서 상대팀의 등급 (프리매치 등급)\n* home_team_history_coach_{i}: 마지막 i번째 경기에서 홈팀의 코치 ID\n* home_team_history_league_id_{i}: 마지막 i번째 경기에서 홈팀 의 리그 이름 ID\n#### \n* away_team_history_match_date_{i}: 원정팀이 플레이한 마지막 i번째 경기 날짜\n* away_team_history_is_play_home_{i}: 원정팀의 홈경기 여부(값-1:홈 경기, 0:원정경기)\n* away_team_history_is_cup_{i}: 컵 대회 여부(값-1:컵대회, 0:컵대회아님)\n* away_team_history_goal_{i}: 마지막 i번째 경기에서 원정팀이 득점한 골 수\n* away_team_history_opponent_goal_{i}: 마지막 i번째 경기에서 원정팀의 상대팀이 득점한 골 수\n* away_team_history_rating_{i}: 마지막 i번째 경기에서 원정팀의 등급 (프리매치 등급)\n* away_team_history_opponent_rating_{i}: 마지막 i번째 경기에서 상대팀의 등급 (프리매치 등급)\n* away_team_history_coach_{i}: 마지막 i번째 경기에서 원정팀의 코치 ID\n* away_team_history_league_id_{i}: 마지막 i번째 경기에서 원정팀의 리그 이름 ID\n\n### 4. 가설\n1. 홈팀이 원정팀보다 승리할 확률이 높을 것이다. \n2. 이전 경기들 이후 더 오래 쉰 팀이 승리할 확률이 높을 것이다. \n3. 이전 경기들에서 등급 평균이 높은 팀이 승리할 확률이 높을 것이다.\n4. 이전 경기에서 연승한 팀이 승리할 확률이 높을 것이다.\n5. 팀 코치가 바뀐 지 얼마 되지 않았다면 그 팀은 승리할 확률이 낮을 것이다.\n\n### 5. 데이터 분석 방법\n1. EDA, 전처리\n2. 가설 분석 후 유의미한 features 선택\n3. 선형 회귀 분석\n4. 결정 트리 분류 분석\n5. 테스트 데이터 셋 예측 및 제출","metadata":{}},{"cell_type":"markdown","source":"================================","metadata":{}},{"cell_type":"markdown","source":"# 1. 데이터 불러오고 확인, EDA 및 전처리","metadata":{}},{"cell_type":"code","source":"# 라이브러리 불러오기\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn import tree","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:35.280596Z","iopub.execute_input":"2022-12-13T05:15:35.281774Z","iopub.status.idle":"2022-12-13T05:15:36.769615Z","shell.execute_reply.started":"2022-12-13T05:15:35.281647Z","shell.execute_reply":"2022-12-13T05:15:36.768723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 데이터 불러오기\ntrain_df = pd.read_csv(\"/kaggle/input/football-match-probability-prediction/train.csv\")\ntest_df = pd.read_csv('/kaggle/input/football-match-probability-prediction/test.csv')","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:36.771484Z","iopub.execute_input":"2022-12-13T05:15:36.772241Z","iopub.status.idle":"2022-12-13T05:15:46.887777Z","shell.execute_reply.started":"2022-12-13T05:15:36.772196Z","shell.execute_reply":"2022-12-13T05:15:46.886593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:46.888970Z","iopub.execute_input":"2022-12-13T05:15:46.889205Z","iopub.status.idle":"2022-12-13T05:15:46.935711Z","shell.execute_reply.started":"2022-12-13T05:15:46.889178Z","shell.execute_reply":"2022-12-13T05:15:46.934804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 데이터 확인\ntrain_df.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:46.938641Z","iopub.execute_input":"2022-12-13T05:15:46.938979Z","iopub.status.idle":"2022-12-13T05:15:46.944596Z","shell.execute_reply.started":"2022-12-13T05:15:46.938929Z","shell.execute_reply":"2022-12-13T05:15:46.943731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 결측치 확인\ntrain_df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:46.946316Z","iopub.execute_input":"2022-12-13T05:15:46.946627Z","iopub.status.idle":"2022-12-13T05:15:47.117165Z","shell.execute_reply.started":"2022-12-13T05:15:46.946588Z","shell.execute_reply":"2022-12-13T05:15:47.116249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 결측치 제거\ntrain_df = train_df.dropna()","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:47.118489Z","iopub.execute_input":"2022-12-13T05:15:47.119499Z","iopub.status.idle":"2022-12-13T05:15:47.388033Z","shell.execute_reply.started":"2022-12-13T05:15:47.119455Z","shell.execute_reply":"2022-12-13T05:15:47.387087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 결측치 제거 확인\ntrain_df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:47.389296Z","iopub.execute_input":"2022-12-13T05:15:47.389514Z","iopub.status.idle":"2022-12-13T05:15:47.492876Z","shell.execute_reply.started":"2022-12-13T05:15:47.389488Z","shell.execute_reply":"2022-12-13T05:15:47.491926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 결측치 제거 후 남은 데이터 확인\ntrain_df.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:47.494453Z","iopub.execute_input":"2022-12-13T05:15:47.495094Z","iopub.status.idle":"2022-12-13T05:15:47.501862Z","shell.execute_reply.started":"2022-12-13T05:15:47.495052Z","shell.execute_reply":"2022-12-13T05:15:47.501010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2.1.1. 가설 분석\n* 홈팀이 원정팀보다 승리할 확률이 높을 것이다. ","metadata":{}},{"cell_type":"code","source":"# 코드 참고 : https://www.kaggle.com/code/yousseftaoudi/football-match-prediction-eda\n# target을 팀별로 나누어 승리여부 보기(home)\ntrain_df[\"home_target\"] = 'draw'\ntrain_df.loc[train_df['target']=='home','home_target'] = 'win'\ntrain_df.loc[train_df['target']=='away','home_target'] = 'loss'","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:47.503042Z","iopub.execute_input":"2022-12-13T05:15:47.503270Z","iopub.status.idle":"2022-12-13T05:15:47.536765Z","shell.execute_reply.started":"2022-12-13T05:15:47.503244Z","shell.execute_reply":"2022-12-13T05:15:47.535922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# target을 팀별로 나누어 승리여부 보기(away)\ntrain_df[\"away_target\"] = 'draw'\ntrain_df.loc[train_df['target']=='home','away_target'] = 'loss'\ntrain_df.loc[train_df['target']=='away','away_target'] = 'win'","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:47.540315Z","iopub.execute_input":"2022-12-13T05:15:47.540841Z","iopub.status.idle":"2022-12-13T05:15:47.565918Z","shell.execute_reply.started":"2022-12-13T05:15:47.540803Z","shell.execute_reply":"2022-12-13T05:15:47.564612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 코드 참고 : https://www.kaggle.com/code/srijita97/football-eda-and-model\n#target 세기 (홈팀 승리가 가장 많았다.)\ntarget_count = train_df['target'].value_counts()\ntarget_count.plot.bar()\nplt.title('<match result>', fontsize = 15)\nplt.xlabel('target')\nplt.ylabel('count')\nplt.xticks(rotation=0)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:47.567291Z","iopub.execute_input":"2022-12-13T05:15:47.567567Z","iopub.status.idle":"2022-12-13T05:15:47.828117Z","shell.execute_reply.started":"2022-12-13T05:15:47.567531Z","shell.execute_reply":"2022-12-13T05:15:47.827198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#홈팀의 target 세기 (승리가 가장 많았다.)\nhome_target_count = train_df['home_target'].value_counts()\nhome_target_count.plot.bar()\nplt.title('<match result (for home team only)>', fontsize = 15)\nplt.xlabel('target')\nplt.ylabel('count')\nplt.xticks(rotation=0)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:47.829436Z","iopub.execute_input":"2022-12-13T05:15:47.829662Z","iopub.status.idle":"2022-12-13T05:15:48.036913Z","shell.execute_reply.started":"2022-12-13T05:15:47.829635Z","shell.execute_reply":"2022-12-13T05:15:48.036270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#원정팀의 target 세기 (패배가 가장 많았다.)\naway_target_count = train_df['away_target'].value_counts()\naway_target_count.plot.bar()\nplt.title('<match result (for away team only)>', fontsize = 15)\nplt.xlabel('target')\nplt.ylabel('count')\nplt.xticks(rotation=0)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:48.038164Z","iopub.execute_input":"2022-12-13T05:15:48.038563Z","iopub.status.idle":"2022-12-13T05:15:48.247632Z","shell.execute_reply.started":"2022-12-13T05:15:48.038514Z","shell.execute_reply":"2022-12-13T05:15:48.246743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* 홈팀이 원정팀보다 승리할 확률이 높아보인다.","metadata":{}},{"cell_type":"markdown","source":"# 2.1.2. 가설 분석\n* 이전 경기들 이후 더 오래 쉰 팀이 승리할 확률이 높을 것이다. \n* 이전 경기들의 날짜를 바탕으로 휴식 시간의 평균을 계산하였다.","metadata":{}},{"cell_type":"code","source":"# 필요한 데이터 형태 확인 \ntrain_df[['match_date','home_team_history_match_date_1','away_team_history_match_date_1']]","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:48.248751Z","iopub.execute_input":"2022-12-13T05:15:48.248976Z","iopub.status.idle":"2022-12-13T05:15:48.311074Z","shell.execute_reply.started":"2022-12-13T05:15:48.248949Z","shell.execute_reply":"2022-12-13T05:15:48.310246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pd.to_datetime 코드 참고: https://www.kaggle.com/code/henriqueweber/football-results-prediction\n# str을 datatime으로 바꾸기\n\ntrain_df['match_date'] = pd.to_datetime(train_df['match_date'])\nfor i in range(1,11):\n    train_df['home_team_history_match_date_{}'.format(i)] = pd.to_datetime(train_df['home_team_history_match_date_{}'.format(i)])\n    train_df['away_team_history_match_date_{}'.format(i)] = pd.to_datetime(train_df['away_team_history_match_date_{}'.format(i)])","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:48.312200Z","iopub.execute_input":"2022-12-13T05:15:48.312499Z","iopub.status.idle":"2022-12-13T05:15:49.066095Z","shell.execute_reply.started":"2022-12-13T05:15:48.312470Z","shell.execute_reply":"2022-12-13T05:15:49.064982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 휴식 시간의 평균 구해서 새로운 column으로 추가\ntrain_df['home_rest_time_Average'] = ((train_df['match_date']-train_df['home_team_history_match_date_1'])+(train_df['home_team_history_match_date_1']-train_df['home_team_history_match_date_2'])+(train_df['home_team_history_match_date_2']-train_df['home_team_history_match_date_3'])+(train_df['home_team_history_match_date_3']-train_df['home_team_history_match_date_4'])+(train_df['home_team_history_match_date_4']-train_df['home_team_history_match_date_5'])+(train_df['home_team_history_match_date_5']-train_df['home_team_history_match_date_6'])+(train_df['home_team_history_match_date_6']-train_df['home_team_history_match_date_7'])+(train_df['home_team_history_match_date_7']-train_df['home_team_history_match_date_8'])+(train_df['home_team_history_match_date_8']-train_df['home_team_history_match_date_9'])+(train_df['home_team_history_match_date_9']-train_df['home_team_history_match_date_10']))/10\ntrain_df['away_rest_time_Average'] = ((train_df['match_date']-train_df['away_team_history_match_date_1'])+(train_df['away_team_history_match_date_1']-train_df['away_team_history_match_date_2'])+(train_df['away_team_history_match_date_2']-train_df['away_team_history_match_date_3'])+(train_df['away_team_history_match_date_3']-train_df['away_team_history_match_date_4'])+(train_df['away_team_history_match_date_4']-train_df['away_team_history_match_date_5'])+(train_df['away_team_history_match_date_5']-train_df['away_team_history_match_date_6'])+(train_df['away_team_history_match_date_6']-train_df['away_team_history_match_date_7'])+(train_df['away_team_history_match_date_7']-train_df['away_team_history_match_date_8'])+(train_df['away_team_history_match_date_8']-train_df['away_team_history_match_date_9'])+(train_df['away_team_history_match_date_9']-train_df['away_team_history_match_date_10']))/10","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.067325Z","iopub.execute_input":"2022-12-13T05:15:49.067567Z","iopub.status.idle":"2022-12-13T05:15:49.113957Z","shell.execute_reply.started":"2022-12-13T05:15:49.067541Z","shell.execute_reply":"2022-12-13T05:15:49.112827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 휴식 시간 평균의 차이를 홈팀기준, 원정팀 기준 새로운 column으로 추가\ntrain_df['home_rest_time_diff'] = train_df['home_rest_time_Average'] - train_df['away_rest_time_Average']\ntrain_df['away_rest_time_diff'] = train_df['away_rest_time_Average'] - train_df['home_rest_time_Average']","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.115542Z","iopub.execute_input":"2022-12-13T05:15:49.115979Z","iopub.status.idle":"2022-12-13T05:15:49.124375Z","shell.execute_reply.started":"2022-12-13T05:15:49.115925Z","shell.execute_reply":"2022-12-13T05:15:49.123338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 휴식 시간 평균의 차이에서 시간을 버리고 일수만 남겨 새로운 column으로 추가\ntrain_df['home_rest_day_diff'] = train_df['home_rest_time_diff'].dt.days\ntrain_df['away_rest_day_diff'] = train_df['away_rest_time_diff'].dt.days","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.125848Z","iopub.execute_input":"2022-12-13T05:15:49.126369Z","iopub.status.idle":"2022-12-13T05:15:49.145496Z","shell.execute_reply.started":"2022-12-13T05:15:49.126331Z","shell.execute_reply":"2022-12-13T05:15:49.144632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.146796Z","iopub.execute_input":"2022-12-13T05:15:49.147396Z","iopub.status.idle":"2022-12-13T05:15:49.222656Z","shell.execute_reply.started":"2022-12-13T05:15:49.147351Z","shell.execute_reply":"2022-12-13T05:15:49.221763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 홈팀 기준으로 휴식 기간에 따른 승부 결과 boxplot으로 그려보기\nplt.figure(figsize=(15,10))\nsns.boxplot(data=train_df,y='home_rest_day_diff',x='home_target').set(title=\"rest day diff per Result(for home team only)\",ylabel='rest day diff')","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.224514Z","iopub.execute_input":"2022-12-13T05:15:49.225151Z","iopub.status.idle":"2022-12-13T05:15:49.590176Z","shell.execute_reply.started":"2022-12-13T05:15:49.225106Z","shell.execute_reply":"2022-12-13T05:15:49.589190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 원정팀 기준으로 휴식 기간에 따른 승부 결과 boxplot으로 그려보기\nplt.figure(figsize=(15,10))\nsns.boxplot(data=train_df,y='away_rest_day_diff',x='away_target').set(title=\"rest day diff per Result(for away team only)\",ylabel='rest day diff')","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.591270Z","iopub.execute_input":"2022-12-13T05:15:49.591497Z","iopub.status.idle":"2022-12-13T05:15:49.886403Z","shell.execute_reply.started":"2022-12-13T05:15:49.591469Z","shell.execute_reply":"2022-12-13T05:15:49.885318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* 이전 경기들 이후 얼마나 쉬었는지는 승패결과와 관련이 없어 보인다.","metadata":{}},{"cell_type":"markdown","source":"# 2.1.3. 가설 분석\n* 이전 경기들에서 등급 평균이 높은 팀이 승리할 확률이 높을 것이다.","metadata":{}},{"cell_type":"code","source":"# 이전 등급의 평균 구해서 새로운 column으로 추가\ntrain_df['home_history_rating_Average'] = (train_df['home_team_history_rating_1'] + train_df['home_team_history_rating_2'] + train_df['home_team_history_rating_3'] + train_df['home_team_history_rating_4'] + train_df['home_team_history_rating_5'] + train_df['home_team_history_rating_6'] +train_df['home_team_history_rating_7'] + train_df['home_team_history_rating_8'] + train_df['home_team_history_rating_9'] +train_df['home_team_history_rating_10'])/10\ntrain_df['away_history_rating_Average'] = (train_df['away_team_history_rating_1'] + train_df['away_team_history_rating_2'] + train_df['away_team_history_rating_3'] + train_df['away_team_history_rating_4'] + train_df['away_team_history_rating_5'] + train_df['away_team_history_rating_6'] +train_df['away_team_history_rating_7'] + train_df['away_team_history_rating_8'] + train_df['away_team_history_rating_9'] +train_df['away_team_history_rating_10'])/10","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.887907Z","iopub.execute_input":"2022-12-13T05:15:49.888641Z","iopub.status.idle":"2022-12-13T05:15:49.908910Z","shell.execute_reply.started":"2022-12-13T05:15:49.888592Z","shell.execute_reply":"2022-12-13T05:15:49.907542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 등급 평균의 차이를 홈팀기준, 원정팀 기준 새로운 column으로 추가\ntrain_df['home_history_rating_diff'] = train_df['home_history_rating_Average'] - train_df['away_history_rating_Average']\ntrain_df['away_history_rating_diff'] = train_df['away_history_rating_Average'] - train_df['home_history_rating_Average']","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.910389Z","iopub.execute_input":"2022-12-13T05:15:49.910719Z","iopub.status.idle":"2022-12-13T05:15:49.922274Z","shell.execute_reply.started":"2022-12-13T05:15:49.910687Z","shell.execute_reply":"2022-12-13T05:15:49.921237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:49.923620Z","iopub.execute_input":"2022-12-13T05:15:49.923918Z","iopub.status.idle":"2022-12-13T05:15:50.014434Z","shell.execute_reply.started":"2022-12-13T05:15:49.923890Z","shell.execute_reply":"2022-12-13T05:15:50.013623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#홈팀 기준으로 등급 차이에 따른 승부 결과 boxplot으로 그려보기\nplt.figure(figsize=(15,10))\nsns.boxplot(data=train_df,y='home_history_rating_diff',x='home_target').set(title=\"rating diff per Result(for home team only)\",ylabel='rating diff')","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:50.015508Z","iopub.execute_input":"2022-12-13T05:15:50.015735Z","iopub.status.idle":"2022-12-13T05:15:50.282458Z","shell.execute_reply.started":"2022-12-13T05:15:50.015708Z","shell.execute_reply":"2022-12-13T05:15:50.281841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 원정팀 기준으로 등급 차이에 따른 승부 결과 boxplot으로 그려보기\nplt.figure(figsize=(15,10))\nsns.boxplot(data=train_df,y='away_history_rating_diff',x='away_target').set(title=\"rating diff per Result(for away team only)\",ylabel='rating diff')","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:50.283487Z","iopub.execute_input":"2022-12-13T05:15:50.284212Z","iopub.status.idle":"2022-12-13T05:15:50.684623Z","shell.execute_reply.started":"2022-12-13T05:15:50.284173Z","shell.execute_reply":"2022-12-13T05:15:50.683628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* 이전 경기들에서 등급 평균이 높은 팀이 승리할 확률이 높아보인다.","metadata":{}},{"cell_type":"markdown","source":"# 2.1.4. 가설 분석\n* 이전 경기에서 연승한 팀이 승리할 확률이 높을 것이다. \n* 이전 경기에서 우승했는지 직접적인 결과가 없기 때문에 득점 골 수를 비교하여 경기 결과를 판단한다.\n* 경기 결과들의 연속 결과를 구한다.","metadata":{}},{"cell_type":"code","source":"# 코드 참고: https://www.kaggle.com/code/henriqueweber/football-results-prediction\n\n# 과거 경기 결과를 구하기 위한 함수\ndef win_loss_history(row,h_a,hist):\n    goals_scored = row['{}_team_history_goal_{}'.format(h_a,hist)]\n    goals_conceived = row['{}_team_history_opponent_goal_{}'.format(h_a,hist)]\n    \n    if goals_scored==goals_conceived:\n        return 'draw'\n    elif goals_scored>goals_conceived:\n        return 'win'\n    else:\n        return 'loss'\n\n# 과거 연속 결과를 계산하기 위한 함수\ndef win_streak(row,h_a):\n    streak=0\n    for hist in range(1,11):\n        if row['{}_match_result_{}'.format(h_a,hist)]=='win':\n            streak=streak+1\n        else:\n            break\n    return streak\n\ndef loss_streak(row,h_a):\n    streak=0\n    for hist in range(1,11):\n        if row['{}_match_result_{}'.format(h_a,hist)]=='loss':\n            streak=streak+1\n        else:\n            break\n    return streak\n\ndef draw_streak(row,h_a):\n    streak=0\n    for hist in range(1,11):\n        if row['{}_match_result_{}'.format(h_a,hist)]=='draw':\n            streak=streak+1\n        else:\n            break\n    return streak","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:50.686045Z","iopub.execute_input":"2022-12-13T05:15:50.686433Z","iopub.status.idle":"2022-12-13T05:15:50.697119Z","shell.execute_reply.started":"2022-12-13T05:15:50.686371Z","shell.execute_reply":"2022-12-13T05:15:50.696077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 함수에 넣어 결과 도출\nfor h_a in ['home','away']:\n    for time in range(1,11):\n        train_df['{}_match_result_{}'.format(h_a,time)] = train_df.apply(win_loss_history, args=(h_a,time), axis=1)\n    \n    \nfor h_a in ['home','away']:\n    train_df['{}_win_streak'.format(h_a)] = train_df.apply(win_streak,h_a=h_a,axis=1)\n    train_df['{}_loss_streak'.format(h_a)] = train_df.apply(loss_streak,h_a=h_a,axis=1)\n    train_df['{}_draw_streak'.format(h_a)] = train_df.apply(draw_streak,h_a=h_a,axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:15:50.702871Z","iopub.execute_input":"2022-12-13T05:15:50.703165Z","iopub.status.idle":"2022-12-13T05:19:48.362877Z","shell.execute_reply.started":"2022-12-13T05:15:50.703134Z","shell.execute_reply":"2022-12-13T05:19:48.362205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:48.363953Z","iopub.execute_input":"2022-12-13T05:19:48.364767Z","iopub.status.idle":"2022-12-13T05:19:48.436929Z","shell.execute_reply.started":"2022-12-13T05:19:48.364730Z","shell.execute_reply":"2022-12-13T05:19:48.436086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 홈팀 기준 연승, 연패, 연속 무승부가 결과에 미치는 영향 \nf,ax = plt.subplots(3,1, figsize=(12,20))\nsns.countplot('home_win_streak', hue='home_target', data=train_df, ax=ax[0])\nax[0].set_title(\"Win/loss/draw rate depending on win streak  (for home team only)\")\n    \nsns.countplot('home_loss_streak', hue='home_target', data=train_df, ax=ax[1])\nax[1].set_title(\"Win/loss/draw rate depending on loss streak  (for home team only)\")\n\nsns.countplot('home_draw_streak', hue='home_target', data=train_df, ax=ax[2])\nax[2].set_title(\"Win/loss/draw rate depending on draw streak  (for home team only)\")\n\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:48.438292Z","iopub.execute_input":"2022-12-13T05:19:48.439185Z","iopub.status.idle":"2022-12-13T05:19:49.564800Z","shell.execute_reply.started":"2022-12-13T05:19:48.439139Z","shell.execute_reply":"2022-12-13T05:19:49.564170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 홈팀 기준 연승이 결과에 미치는 영향 \ntrain_df['home_win_streak'].groupby(train_df['home_target']).value_counts().sort_index(ascending=True)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:49.565987Z","iopub.execute_input":"2022-12-13T05:19:49.566388Z","iopub.status.idle":"2022-12-13T05:19:49.592842Z","shell.execute_reply.started":"2022-12-13T05:19:49.566360Z","shell.execute_reply":"2022-12-13T05:19:49.592234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 홈팀 기준 연패가 결과에 미치는 영향 \ntrain_df['home_loss_streak'].groupby(train_df['home_target']).value_counts().sort_index(ascending=True)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:49.594776Z","iopub.execute_input":"2022-12-13T05:19:49.595143Z","iopub.status.idle":"2022-12-13T05:19:49.619563Z","shell.execute_reply.started":"2022-12-13T05:19:49.595099Z","shell.execute_reply":"2022-12-13T05:19:49.618715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 홈팀 기준 연속 무승부가 결과에 미치는 영향 \ntrain_df['home_draw_streak'].groupby(train_df['home_target']).value_counts().sort_index(ascending=True)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:49.620692Z","iopub.execute_input":"2022-12-13T05:19:49.620906Z","iopub.status.idle":"2022-12-13T05:19:49.645713Z","shell.execute_reply.started":"2022-12-13T05:19:49.620881Z","shell.execute_reply":"2022-12-13T05:19:49.644773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 원정팀 기준 연승, 연패, 연속 무승부가 결과에 미치는 영향 \nf,ax = plt.subplots(3,1, figsize=(12,20))\nsns.countplot('away_win_streak', hue='away_target', data=train_df, ax=ax[0])\nax[0].set_title(\"Win/loss/draw rate depending on win streak  (for away team only)\")\n    \nsns.countplot('away_loss_streak', hue='away_target', data=train_df, ax=ax[1])\nax[1].set_title(\"Win/loss/draw rate depending on loss streak  (for away team only)\")\n\nsns.countplot('away_draw_streak', hue='away_target', data=train_df, ax=ax[2])\nax[2].set_title(\"Win/loss/draw rate depending on draw streak  (for away team only)\")\n\nplt.tight_layout()","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:49.646920Z","iopub.execute_input":"2022-12-13T05:19:49.647159Z","iopub.status.idle":"2022-12-13T05:19:50.773055Z","shell.execute_reply.started":"2022-12-13T05:19:49.647132Z","shell.execute_reply":"2022-12-13T05:19:50.770082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 원정팀 기준 연승이 결과에 미치는 영향 \ntrain_df['away_win_streak'].groupby(train_df['away_target']).value_counts().sort_index(ascending=True)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:50.774490Z","iopub.execute_input":"2022-12-13T05:19:50.775110Z","iopub.status.idle":"2022-12-13T05:19:50.800831Z","shell.execute_reply.started":"2022-12-13T05:19:50.775049Z","shell.execute_reply":"2022-12-13T05:19:50.799939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 원정팀 기준 연패가 결과에 미치는 영향 \ntrain_df['away_loss_streak'].groupby(train_df['away_target']).value_counts().sort_index(ascending=True)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:50.801886Z","iopub.execute_input":"2022-12-13T05:19:50.802214Z","iopub.status.idle":"2022-12-13T05:19:50.825231Z","shell.execute_reply.started":"2022-12-13T05:19:50.802184Z","shell.execute_reply":"2022-12-13T05:19:50.824518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 원정팀 기준 연속 무승부가 결과에 미치는 영향 \ntrain_df['away_draw_streak'].groupby(train_df['away_target']).value_counts().sort_index(ascending=True)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:50.826619Z","iopub.execute_input":"2022-12-13T05:19:50.826847Z","iopub.status.idle":"2022-12-13T05:19:50.849857Z","shell.execute_reply.started":"2022-12-13T05:19:50.826820Z","shell.execute_reply":"2022-12-13T05:19:50.848938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* 이전 경기에서 연승한 팀이 승리할 확률이 높아 보인다.","metadata":{}},{"cell_type":"markdown","source":"# 2.1.5. 가설 분석\n* 팀 코치가 바뀐 지 얼마 되지 않았다면 그 팀은 승리할 확률이 낮을 것이다.","metadata":{}},{"cell_type":"code","source":"# 코드 참고: https://www.kaggle.com/code/henriqueweber/football-results-prediction\n\n# 이번 경기에서의 코치가 이전 경기에서 코치 여부 횟수 구하기 위한 함수 \ndef time_coach(row,h_a):\n    coach_id = row['{}_team_coach_id'.format(h_a)]\n    time = 1\n    for match in range(1,11):\n        if row['{}_team_history_coach_{}'.format(h_a,match)]==coach_id:\n            time = time+1\n        else:\n            break\n    return time","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:50.851418Z","iopub.execute_input":"2022-12-13T05:19:50.851764Z","iopub.status.idle":"2022-12-13T05:19:50.858582Z","shell.execute_reply.started":"2022-12-13T05:19:50.851716Z","shell.execute_reply":"2022-12-13T05:19:50.857491Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 함수에 넣어 결과 도출\nfor h_a in ['home','away']:\n        train_df['{}_coach_time'.format(h_a)] = train_df.apply(time_coach, h_a=h_a, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:19:50.860164Z","iopub.execute_input":"2022-12-13T05:19:50.860391Z","iopub.status.idle":"2022-12-13T05:20:13.928427Z","shell.execute_reply.started":"2022-12-13T05:19:50.860364Z","shell.execute_reply":"2022-12-13T05:20:13.927190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:20:13.929796Z","iopub.execute_input":"2022-12-13T05:20:13.930104Z","iopub.status.idle":"2022-12-13T05:20:14.013255Z","shell.execute_reply.started":"2022-12-13T05:20:13.930064Z","shell.execute_reply":"2022-12-13T05:20:14.012078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#홈팀 기준으로 코치 횟수 차이에 따른 승부 결과 boxplot으로 그려보기\nplt.figure(figsize=(15,10))\nsns.boxplot(data=train_df,y='home_coach_time',x='home_target').set(title=\"coach time per Result(for home team only)\",ylabel='coach time')","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:20:14.014687Z","iopub.execute_input":"2022-12-13T05:20:14.015291Z","iopub.status.idle":"2022-12-13T05:20:14.361828Z","shell.execute_reply.started":"2022-12-13T05:20:14.015241Z","shell.execute_reply":"2022-12-13T05:20:14.361035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#원정팀 기준으로 코치 횟수 차이에 따른 승부 결과 boxplot으로 그려보기\nplt.figure(figsize=(15,10))\nsns.boxplot(data=train_df,y='away_coach_time',x='away_target').set(title=\"coach time per Result(for away team only)\",ylabel='coach time')","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:20:14.363203Z","iopub.execute_input":"2022-12-13T05:20:14.364160Z","iopub.status.idle":"2022-12-13T05:20:14.710767Z","shell.execute_reply.started":"2022-12-13T05:20:14.364112Z","shell.execute_reply":"2022-12-13T05:20:14.709961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* 팀 코치가 바뀐 지 얼마 되지 않았다면 그 팀은 승리할 확률이 낮아 보인다.","metadata":{}},{"cell_type":"markdown","source":"# 2.1.6. 가설 분석 conclusion\n1. 홈팀이 원정팀보다 승리할 확률이 높을 것이다.  -> O\n2. 이전 경기들 이후 더 오래 쉰 팀이 승리할 확률이 높을 것이다. -> X \n3. 이전 경기들에서 등급 평균이 높은 팀이 승리할 확률이 높을 것이다. -> O\n4. 이전 경기에서 연승한 팀이 승리할 확률이 높을 것이다. -> O\n5. 팀 코치가 바뀐 지 얼마 되지 않았다면 그 팀은 승리할 확률이 낮을 것이다. -> O","metadata":{}},{"cell_type":"markdown","source":"# 2.2. 학습할 features 결정\n* target\n* home_history_rating_Average\n* away_history_rating_Average\n* home_win_streak\n* away_win_streak\n* home_loss_streak\n* away_loss_streak\n* home_draw_streak\n* away_draw_streak\n* home_coach_time\n* away_coach_time","metadata":{}},{"cell_type":"markdown","source":"# 3. 선형 회귀 분석","metadata":{}},{"cell_type":"code","source":"# 위에서 정한 features로 학습하기 위해 준비\nX = train_df[['home_history_rating_Average','away_history_rating_Average','home_win_streak','away_win_streak','home_loss_streak','away_loss_streak','home_draw_streak','away_draw_streak','home_coach_time','away_coach_time']]\ny = train_df['target']","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:01.946225Z","iopub.execute_input":"2022-12-13T05:26:01.947234Z","iopub.status.idle":"2022-12-13T05:26:01.957020Z","shell.execute_reply.started":"2022-12-13T05:26:01.947176Z","shell.execute_reply":"2022-12-13T05:26:01.955641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 정규화\nscaler = StandardScaler()\nX = pd.DataFrame(scaler.fit_transform(X),columns=X.columns)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:02.453942Z","iopub.execute_input":"2022-12-13T05:26:02.454701Z","iopub.status.idle":"2022-12-13T05:26:02.483915Z","shell.execute_reply.started":"2022-12-13T05:26:02.454640Z","shell.execute_reply":"2022-12-13T05:26:02.482565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 데이터 셋 나누기\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:02.629178Z","iopub.execute_input":"2022-12-13T05:26:02.630278Z","iopub.status.idle":"2022-12-13T05:26:02.649967Z","shell.execute_reply.started":"2022-12-13T05:26:02.630222Z","shell.execute_reply":"2022-12-13T05:26:02.649202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 선형 회귀 분석 모델로 학습\nmodel = LogisticRegression(C=0.001,penalty='l2',solver='lbfgs')\nmodel.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:05.928697Z","iopub.execute_input":"2022-12-13T05:26:05.930242Z","iopub.status.idle":"2022-12-13T05:26:06.970342Z","shell.execute_reply.started":"2022-12-13T05:26:05.930179Z","shell.execute_reply":"2022-12-13T05:26:06.966373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 예측\ny_pred = model.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:06.985646Z","iopub.execute_input":"2022-12-13T05:26:06.998719Z","iopub.status.idle":"2022-12-13T05:26:07.038268Z","shell.execute_reply.started":"2022-12-13T05:26:06.998474Z","shell.execute_reply":"2022-12-13T05:26:07.034594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 정확도\nprint(\"prediction accuracy: {:.2f}\".format(np.mean(y_pred == y_test)))","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:13.712428Z","iopub.execute_input":"2022-12-13T05:26:13.712963Z","iopub.status.idle":"2022-12-13T05:26:13.720344Z","shell.execute_reply.started":"2022-12-13T05:26:13.712929Z","shell.execute_reply":"2022-12-13T05:26:13.719186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(confusion_matrix(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:26.311188Z","iopub.execute_input":"2022-12-13T05:26:26.311730Z","iopub.status.idle":"2022-12-13T05:26:26.366395Z","shell.execute_reply.started":"2022-12-13T05:26:26.311668Z","shell.execute_reply":"2022-12-13T05:26:26.365452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 4. 결정 트리 분류 분석","metadata":{}},{"cell_type":"code","source":"# 결정트리로 학습\ntree_model = tree.DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0)\ntree_model.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:55.474066Z","iopub.execute_input":"2022-12-13T05:26:55.474513Z","iopub.status.idle":"2022-12-13T05:26:55.672554Z","shell.execute_reply.started":"2022-12-13T05:26:55.474471Z","shell.execute_reply":"2022-12-13T05:26:55.671475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 예측\ny_pred_tree = tree_model.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:26:58.596632Z","iopub.execute_input":"2022-12-13T05:26:58.597880Z","iopub.status.idle":"2022-12-13T05:26:58.607094Z","shell.execute_reply.started":"2022-12-13T05:26:58.597804Z","shell.execute_reply":"2022-12-13T05:26:58.605939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 정확도\nprint(\"prediction accuracy: {:.2f}\".format(np.mean(y_pred_tree == y_test)))","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:27:19.669218Z","iopub.execute_input":"2022-12-13T05:27:19.669562Z","iopub.status.idle":"2022-12-13T05:27:19.677270Z","shell.execute_reply.started":"2022-12-13T05:27:19.669525Z","shell.execute_reply":"2022-12-13T05:27:19.676167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(confusion_matrix(y_test, y_pred_tree))","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:27:26.227247Z","iopub.execute_input":"2022-12-13T05:27:26.227608Z","iopub.status.idle":"2022-12-13T05:27:26.282952Z","shell.execute_reply.started":"2022-12-13T05:27:26.227566Z","shell.execute_reply":"2022-12-13T05:27:26.281740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 5.1. 테스트 데이터 셋으로 예측","metadata":{}},{"cell_type":"code","source":"# 테스트 데이터 셋에서 필요한 전처리 과정 거치기\n\ntest_df = test_df.fillna(0)\n# 이전 등급의 평균 구해서 새로운 column으로 추가\ntest_df['home_history_rating_Average'] = (test_df['home_team_history_rating_1'] + test_df['home_team_history_rating_2'] + test_df['home_team_history_rating_3'] + test_df['home_team_history_rating_4'] + test_df['home_team_history_rating_5'] + test_df['home_team_history_rating_6'] +test_df['home_team_history_rating_7'] + test_df['home_team_history_rating_8'] + test_df['home_team_history_rating_9'] +test_df['home_team_history_rating_10'])/10\ntest_df['away_history_rating_Average'] = (test_df['away_team_history_rating_1'] + test_df['away_team_history_rating_2'] + test_df['away_team_history_rating_3'] + test_df['away_team_history_rating_4'] + test_df['away_team_history_rating_5'] + test_df['away_team_history_rating_6'] +test_df['away_team_history_rating_7'] + test_df['away_team_history_rating_8'] + test_df['away_team_history_rating_9'] +test_df['away_team_history_rating_10'])/10\n\n# 과거 연속 결과를 계산하여 새로운 column으로 추가\nfor h_a in ['home','away']:\n    for time in range(1,11):\n        test_df['{}_match_result_{}'.format(h_a,time)] = test_df.apply(win_loss_history, args=(h_a,time), axis=1)\n    \nfor h_a in ['home','away']:\n    test_df['{}_win_streak'.format(h_a)] = test_df.apply(win_streak,h_a=h_a,axis=1)\n    test_df['{}_loss_streak'.format(h_a)] = test_df.apply(loss_streak,h_a=h_a,axis=1)\n    test_df['{}_draw_streak'.format(h_a)] = test_df.apply(draw_streak,h_a=h_a,axis=1)\n    \n# 과거 코치 횟수를 계산하여 새로운 column으로 추가 \nfor h_a in ['home','away']:\n        test_df['{}_coach_time'.format(h_a)] = test_df.apply(time_coach, h_a=h_a, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:20:16.631861Z","iopub.execute_input":"2022-12-13T05:20:16.632119Z","iopub.status.idle":"2022-12-13T05:21:19.416451Z","shell.execute_reply.started":"2022-12-13T05:20:16.632089Z","shell.execute_reply":"2022-12-13T05:21:19.415593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 필요한 features 준비\nX = test_df[['home_history_rating_Average','away_history_rating_Average','home_win_streak','away_win_streak','home_loss_streak','away_loss_streak','home_draw_streak','away_draw_streak','home_coach_time','away_coach_time']]","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:21:19.417675Z","iopub.execute_input":"2022-12-13T05:21:19.417990Z","iopub.status.idle":"2022-12-13T05:21:19.427449Z","shell.execute_reply.started":"2022-12-13T05:21:19.417950Z","shell.execute_reply":"2022-12-13T05:21:19.426510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 정규화\nX = pd.DataFrame(scaler.fit_transform(X),columns=X.columns)","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:21:19.428441Z","iopub.execute_input":"2022-12-13T05:21:19.428652Z","iopub.status.idle":"2022-12-13T05:21:19.455086Z","shell.execute_reply.started":"2022-12-13T05:21:19.428625Z","shell.execute_reply":"2022-12-13T05:21:19.454246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 5.2. 제출","metadata":{}},{"cell_type":"code","source":"# 참고 코드 : https://www.kaggle.com/code/henriqueweber/football-results-prediction/notebook\n# 선형 회귀로 예측, 확률\npredictions = model.predict_proba(X)\nsubmission = pd.concat([pd.DataFrame(test_df.id),pd.DataFrame(predictions,columns=['away','draw','home'])[['home', 'draw','away']]],axis=1).set_index('id')\nsubmission.to_csv('submission.csv')","metadata":{"execution":{"iopub.status.busy":"2022-12-13T05:21:19.456100Z","iopub.execute_input":"2022-12-13T05:21:19.456321Z","iopub.status.idle":"2022-12-13T05:21:19.961174Z","shell.execute_reply.started":"2022-12-13T05:21:19.456295Z","shell.execute_reply":"2022-12-13T05:21:19.960272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 참고 코드 출처\n* https://www.kaggle.com/code/yousseftaoudi/football-match-prediction-eda\n* https://www.kaggle.com/code/srijita97/football-eda-and-model\n* https://www.kaggle.com/code/henriqueweber/football-results-prediction\n","metadata":{}}]}