# -*- coding: utf-8 -*-
"""IPL_543.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1AENNkIdInLqwHbaO_D0LrOGfW9208KCv
"""

from google.colab import files
uploaded = files.upload()

# Commented out IPython magic to ensure Python compatibility.
import numpy as np 
import pandas as pd 
import os
import matplotlib.pyplot as plt 
# %matplotlib inline
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression

deliv = pd.read_csv("deliveries.csv")deliv = pd.read_csv("deliveries.csv")
mat  = pd.read_csv("matches.csv")

"""## **Cleaning and Transformtion**"""

mat.drop('umpire3',axis=1,inplace=True)
mat=mat.replace('Rising Pune Supergiants','Rising Pune Supergiant')
deliv.fillna(0,inplace=True)
mat['winner'].fillna('Draw',inplace=True)
mat['city'].fillna('Mumbai',inplace=True)
mat['player_of_match'].fillna('No one',inplace=True)
mat['umpire2'].fillna('SJA Taufel',inplace=True)
mat['umpire1'].fillna('HDPK Dharmasena',inplace=True)
#mat.columns = mat.columns.str.strip()
deliv.rename(columns={'match_id': 'id'}, inplace=True)

"""## Plot the following graph

**Maximum Toss Winners**
"""

plt.subplots(figsize=(8,5))
ax=mat['toss_winner'].value_counts().plot.bar(width=0.5)
for p in ax.patches:
    ax.annotate(format(p.get_height()), (p.get_x()+0.15, p.get_height()+1))
plt.show()

"""**Toss Decision wrt Season**"""

plt.subplots(figsize=(10,6))
sns.countplot(x='season',hue='toss_decision',data=mat)
plt.show()

"""**Toss Decision wrt Team**"""

plt.subplots(figsize=(30,6))
sns.countplot(x='team1',hue='toss_decision',data=mat)
plt.show()

"""**Maximum Wins**"""

'''
mat['winner'].value_counts().plot.bar()
plt.title('Maximum WInners')
plt.xlabel('Teams')
plt.ylabel('Count')
'''
plt.subplots(figsize=(8,6))
wnrs = mat['winner'].value_counts().plot.bar(width=0.5)
for x in wnrs.patches:
  wnrs.annotate(format(x.get_height()),(x.get_x()+0.1,x.get_height()+1))
plt.show()

"""**Total Matches vs Wins for Teams**"""

plt.subplots(figsize=(30,6))
sns.countplot(x='toss_winner',hue='winner',data=mat)
plt.show()

"""**Is Toss Winner Also the Match Winner?**"""

'''
c2 = mat[(mat.winner == mat.toss_winner)]
c2['winner'].value_counts().plot.bar()
plt.title('Percentage of Winning a match if toss is won')
plt.xlabel('Teams')
plt.ylabel('Percentage')
'''
#plt.subplots(figsize=(8,6))
c2 = mat[(mat.winner == mat.toss_winner)]
sall = len(mat.index)
sm=len(c2.index)
print("percentage of winning match if toss is won:-",(sm/sall)*100)
'''
wnrs = c2['winner'].value_counts().plot.bar(width=0.5)
for x in wnrs.patches:
  wnrs.annotate(format(x.get_height()),(x.get_x()+0.1,x.get_height()+1))
plt.show()
'''

d2mat = mat[['id','season']]
d2deliv = deliv[['id','batsman_runs']]
d2 = pd.merge(d2mat,d2deliv,on='id',how='inner')

"""**Sixes and Fours Across the Season**"""

d24 = d2[d2.batsman_runs == 4]
d26 = d2[d2.batsman_runs == 6]

plt.subplots(figsize=(9,6))
d4 = d24['season'].value_counts().plot.bar(width=0.5)
for x in d4.patches:
  d4.annotate(format(x.get_height()),(x.get_x()+0.01,x.get_height()+1.05))
plt.show()
'''
plt.title('Fours in a season')
plt.xlabel('seasons')
plt.ylabel('Count')
'''

plt.subplots(figsize=(9,6))
d6 = d26['season'].value_counts().plot.bar(width=0.5)
for x in d6.patches:
  d6.annotate(format(x.get_height()),(x.get_x()+0.01,x.get_height()+1.5))
plt.title('Sixes in a season')
plt.xlabel('seasons')
plt.ylabel('Count')

"""**Runs Per Over By Teams Across Seasons**"""

rpo = deliv.pivot_table(index=['over'],columns='batting_team',values='total_runs',aggfunc=sum)
mpbt=pd.concat([mat['team1'],mat['team2']])
mpbt=mpbt.value_counts().reset_index()
mpbt.columns=['Team','Total Matches']
mpbt['wins']=mat['winner'].value_counts().reset_index()['winner']
mpbt.set_index('Team',inplace=True)
rpo[(mpbt[mpbt['Total Matches']>50].index)].plot(color=["b", "r", "#Ffb6b2", "g",'brown','y','#6666ff','black','#FFA500']) 
x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
plt.xticks(x)
plt.ylabel('total runs scored')
fig=plt.gcf()
fig.set_size_inches(16,10)
plt.show()

"""**Maximum Man Of Matches**"""

f2 = mat['player_of_match'].value_counts().head().plot.bar()
#ax = matches['player_of_match'].value_counts().head(10).plot.bar(width=.8, color=sns.color_palette('inferno',10))
plt.title("Maximum man of the matches")
plt.xlabel('player of match') 
plt.ylabel('count')

"""### Create a table with the following data also visualize if possible:

**Team Comparator**
"""

a = 'Mumbai Indians'
b = 'Chennai Super Kings'
mt1=mat[(((mat['team1']==a)&(mat['team2']==b))|((mat['team1']==b)&(mat['team2']==a)))]
mt1 = mt1[['team1','team2','winner']]
tc = mt1.groupby(['team1','team2','winner']).size().reset_index().rename(columns={0:'count'})
tc.loc[0,'count'] = tc.loc[0,'count'] + tc.loc[2,'count']
tc.loc[1,'count'] = tc.loc[1,'count'] + tc.loc[3,'count']
tc.loc[0,'team1_wins'] = tc.loc[0,'count']
tc.loc[0,'team2_wins'] = tc.loc[1,'count']
tc.drop(['winner','count'],axis=1,inplace=True)
tc = tc[:1]
tc

"""**Matches Won By A Team Against Other Teams**"""

'''
def matwonagt(a):
  team_l = ['Sunrisers Hyderabad','Mumbai Indians','Gujarat Lions','Rising Pune Supergiants','Royal Challengers Bangalore','Kolkata Knight Riders','Delhi Daredevils','Kings XI Punjab','Chennai Super Kings','Rajasthan Royals','Deccan Chargers','Kochi Tuskers Kerala','Pune Warriors']
  team_l.remove(a)
  teams = team_l.copy()
  mt1=mat[((mat['team1']==a)|(mat['team2']==a))]
  mt1 = mt1[['team1','team2','winner']]
  mtag = mt1.groupby(['team1','team2','winner']).size().reset_index().rename(columns={0:'count'})
  mtag
  for i in range(0,len(mtag)):
    if mtag.loc[i,'team1'] != a:
      t = mtag.loc[i,'team1']
      mtag.loc[i,'team1'] = mtag.loc[i,'team2']
      mtag.loc[i,'team2'] = t
  mtagg = mtag.groupby(['team1','team2'])['count'].sum().reset_index()
  for i in range(0, len(mtagg),2):
    mtagg.loc[i,'looses'] = mtagg.loc[i+1,'count']
  #mtagg = mtagg.iloc[::2]
  mtagg.rename(columns={'count':'wins'},inplace=True)
  print(mtagg)
matwonagt('Chennai Super Kings')
'''

a = 'Chennai Super Kings'
team_l = ['Sunrisers Hyderabad','Mumbai Indians','Gujarat Lions','Rising Pune Supergiants','Royal Challengers Bangalore','Kolkata Knight Riders','Delhi Daredevils','Kings XI Punjab','Chennai Super Kings','Rajasthan Royals','Deccan Chargers','Kochi Tuskers Kerala','Pune Warriors']
team_l.remove(a)
teams = team_l.copy()
mt1=mat[((mat['team1']==a)|(mat['team2']==a))]
mt1 = mt1[['team1','team2','winner']]
mtag = mt1.groupby(['team1','team2','winner']).size().reset_index().rename(columns={0:'count'})
mtag
for i in range(0,len(mtag)):
  if mtag.loc[i,'team1'] != a:
    t = mtag.loc[i,'team1']
    mtag.loc[i,'team1'] = mtag.loc[i,'team2']
    mtag.loc[i,'team2'] = t
mtagg = mtag.groupby(['team1','team2','winner'])['count'].sum().reset_index()
for i in range(0, len(mtagg),2):
  mtagg.loc[i,'looses'] = mtagg.loc[i+1,'count']
mtagg = mtagg.iloc[::2]
mtagg

"""**200+ Scores**"""

sc = deliv.groupby(['id','batting_team'])['total_runs'].sum().reset_index()
plus = sc[sc['total_runs']>200]
plus200 = plus.sort_values(by='total_runs',ascending = False)
plus200.head()

plus2=deliv.groupby(['id', 'inning','batting_team','bowling_team'])['total_runs'].sum().reset_index()
plus2.set_index(['id'],inplace=True)
#plus2['total_runs'].max()
plus2=plus2.rename(columns={'total_runs':'count'})
plus2=plus2[plus2['count']>=200].groupby(['inning','batting_team','bowling_team']).count()
plus2

"""**Chances of chasing 200+ target**"""

d3 = deliv.groupby(['id','inning','batting_team','bowling_team'])['total_runs'].sum().reset_index()
d33 = pd.DataFrame(columns=['id','inning','batting_team','bowling_team','total_runs'])
bb = cc = 0
for i in range(0, len(d3),2):
  a = d3.loc[i,'total_runs']
  b = d3.loc[i+1,'total_runs']
  if a>200:
    bb = bb+1
    if b>a:
      d33 = d33.append(d3[d3['id'] == d3.loc[i,'id']])
      cc = cc +1
d33
print((cc/bb)*100,"%")

"""### **Batsman Comparator**"""

hsr=deliv.groupby(['batsman','batsman_runs'])['total_runs'].count().reset_index()
hsr=hsr.pivot('batsman','batsman_runs','total_runs')

"""**Create a function that compares 2 batsman based on their respective stats like runs or strike rate etc**"""

cmpBats = pd.DataFrame(columns=['batsman','dots','singles','Twos','Threes','Fours','Sixes','total_runs','Average','Strike_rate'])

dfc=deliv.groupby(['batsman'])['ball'].count().reset_index()
runs=deliv.groupby(['batsman'])['batsman_runs'].sum().reset_index()
ones=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==1).sum()).reset_index()
twos=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==2).sum()).reset_index()
threes=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==3).sum()).reset_index()
dots=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==0).sum()).reset_index()
sixes=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==4).sum()).reset_index()
fours=deliv.groupby(['batsman'])['batsman_runs'].agg(lambda x: (x==6).sum()).reset_index()
dfc=dfc.merge(dots,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'dots'},inplace=True)
dfc=dfc.merge(ones,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'ones'},inplace=True)
dfc=dfc.merge(twos,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'twos'},inplace=True)
dfc=dfc.merge(threes,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'threes'},inplace=True)
dfc=dfc.merge(sixes,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'Fours'},inplace=True)
dfc=dfc.merge(fours,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'sixes'},inplace=True)
dfc=dfc.merge(runs,on='batsman',how='outer')
runs=deliv.groupby(['batsman'])['batsman_runs'].sum().reset_index()
dfc.rename({'ball':'balls_faced','batsman_runs':'runs_scored'},axis=1,inplace=True)
dfc['strike_rate']=dfc['runs_scored']/dfc['balls_faced']*100
dfc.head()

"""**Create a dataframe from where you will be taking all that values for comparison**"""

dfc

"""**Compare Rohit Sharma and Virat Kohli on runs scored and strike rate**"""

cmp = pd.DataFrame()
cmp = cmp.append(dfc[dfc['batsman']=='V Kohli'])
cmp = cmp.append(dfc[dfc['batsman']=='RG Sharma'])
cmp

"""## **Top Batsman**"""

hsr=deliv.groupby(['batsman','batsman_runs'])['total_runs'].count().reset_index()
hsr=hsr.pivot('batsman','batsman_runs','total_runs')

"""**Top 10 Batsman**"""

top = deliv.groupby(['batsman'])['batsman_runs'].sum()
top10=top.sort_values(ascending=False)[:10]
top10.plot.bar()

"""**Top Batsman's with 1's, 2's, 3's, 4's**"""

hsr[1].sort_values(ascending=False).head().reset_index()

hsr[2].sort_values(ascending=False).head().reset_index()

hsr[3].sort_values(ascending=False).head().reset_index()

hsr[4].sort_values(ascending=False).head().reset_index()

hsr[6].sort_values(ascending=False).head().reset_index()

"""**Top Individual Scores**"""

tis = deliv.groupby(["id",'inning', "batsman"])["batsman_runs"].sum().reset_index()
tis.sort_values('batsman_runs', ascending=0).head()

"""**Highest score in each inning**"""

tisi = deliv.groupby(["id",'inning', "batsman"])["batsman_runs"].sum().reset_index()
tisi.sort_values('batsman_runs', ascending=0).head()
tisi['high_scorer']=""
tisi['high_scorer']=tisi.groupby(['id','inning'])['batsman_runs'].transform(max)
tisi = tisi[tisi['batsman_runs']==tisi['high_scorer']]
tisi

"""**Individual Scores By Top Batsman each Inning**"""

btsmn=['CH Gayle','V Kohli','G Gambhir','SK Raina','YK Pathan','MS Dhoni','AB de Villiers','DA Warner']
scores = deliv.groupby(["id", "batsman","batting_team"])["batsman_runs"].sum().reset_index()
scores=scores[tis['batsman'].isin(btsmn)]
scores

"""### **Top Bowlers**

**Highest Wicket Taker**
"""

outs = ["bowled", "stumped", "caught", "lbw", "caught and bowled","hit wicket"]
hwt=deliv[deliv["dismissal_kind"].isin(outs)]
hwtaker=hwt['bowler'].value_counts()
hwtaker.head().plot.bar()

"""**Maximum Overs**"""

maxo=deliv.groupby(['bowler']).sum()
maxo['balls_count']=deliv['bowler'].value_counts()
maxo['overs_count']=(maxo['balls_count']//6)
maxo.sort_values(by='overs_count')['overs_count'].tail(5).reset_index()

"""**Most Economical Bowlers with 300+ overs**"""

maxo['economy']=(maxo['total_runs']/(maxo['overs_count']))
maxe = maxo[(maxo['overs_count']>300)]
maxe = maxe.sort_values('economy').head().economy.reset_index()
maxe

"""**Highest Dismissals for a Batsman by a Bowler**"""

hd = hwt[['batsman','bowler']]
hd = hd.groupby(['batsman','bowler']).size().reset_index().rename(columns={0:'count'})
hdbb = hd.sort_values(by='count',ascending = False)
hdbb = hdbb.drop_duplicates('batsman').reset_index()
hdbb

"""# Dream11"""

squad = []
mtd11 = mat[['id','season']]
mtd11 = mtd11.loc[mtd11['season']>=2015]
deld11 = deliv[['id','batsman','batsman_runs','bowler','dismissal_kind','fielder']]
mdd11 = pd.merge(mtd11,deld11,on='id',how='inner')
stumps = mdd11.groupby('fielder')['dismissal_kind'].agg(lambda x: (x=='stumped').sum()).reset_index()
stumps = stumps.sort_values(by='dismissal_kind',ascending=False).head().reset_index()
stumps = stumps.head()
wk = stumps['fielder'].unique()
wk = wk.tolist()

scrs = mdd11.groupby(["batsman"])["batsman_runs"].sum().reset_index()
scrs = scrs.sort_values(by='batsman_runs',ascending=False)
wt = scrs[scrs['batsman'].isin(wk)]
wkt = wt.iloc[0]['batsman']
bkpwkt = wt.iloc[1]['batsman']
scrs = scrs[scrs.batsman!=wkt]
scrs = scrs[scrs.batsman!=bkpwkt]
WicketKeeper = wt[:1]['batsman'].tolist()
bkpWicketKeeper = wt[1:2]['batsman'].tolist()
WicketKeeper,bkpWicketKeeper

fielders = mdd11.groupby('fielder')['dismissal_kind'].agg(lambda x: (x=='caught').sum()).reset_index()
fielders = fielders.sort_values(by='dismissal_kind',ascending=False).reset_index()
best_fielders = fielders.head(100)
bf = best_fielders['fielder'].unique()
bf = bf.tolist()

btsms = scrs[scrs['batsman'].isin(bf)]
Batsmans = btsms[:4]['batsman'].tolist()
bkpBatsmans = btsms[4:6]['batsman'].tolist()
Batsmans,bkpBatsmans

saa=mdd11[mdd11["dismissal_kind"].isin(outs)]
blwr=saa['bowler'].value_counts().reset_index()
btsms = scrs[scrs['batsman'].isin(bf)]
wktsmean = blwr["bowler"].mean()
scrmean = btsms['batsman_runs'].mean()

allr = btsms.loc[btsms['batsman_runs']>500]
allr = allr[6:]
allrr = blwr.loc[blwr['bowler']>18]
allrr = allrr[6:]
allr1 = allrr['index'].unique()
allr1 = allr1.tolist()
alr = allr[allr['batsman'].isin(allr1)]
Allrounders = alr[:2]['batsman'].tolist()
bkpAllrounders = alr[2:]['batsman'].tolist()
Allrounders,bkpAllrounders

Bowlers = blwr[:4]['index'].tolist()
bkpBowlers = blwr[4:6]['index'].tolist()
Bowlers,bkpBowlers

Team11 = WicketKeeper + Batsmans +Allrounders + Bowlers
BackupPlayers = bkpWicketKeeper + bkpBatsmans + bkpAllrounders + bkpBowlers
Squad = Team11 + BackupPlayers

Team11

Squad

BackupPlayers

"""**Algorithms and their Accuracy**"""

mat.replace(['Mumbai Indians','Kolkata Knight Riders','Royal Challengers Bangalore','Deccan Chargers','Chennai Super Kings',
                 'Rajasthan Royals','Delhi Daredevils','Gujarat Lions','Kings XI Punjab',
                 'Sunrisers Hyderabad','Rising Pune Supergiant','Kochi Tuskers Kerala','Pune Warriors']
                ,['MI','KKR','RCB','DC','CSK','RR','DD','GL','KXIP','SRH','RPS','KTK','PW'],inplace=True)
encode = {'team1': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DD':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'team2': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DD':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'toss_winner': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DD':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'winner': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DD':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13,'Draw':14}}
mat.replace(encode, inplace=True)
mat.head(2)

from sklearn.preprocessing import LabelEncoder
var_mod = ['city','toss_decision','venue']
le = LabelEncoder()
for i in var_mod:
    mat[i] = le.fit_transform(mat[i])
mat.dtypes

x=mat.drop(['id','season','date','result','dl_applied','winner','player_of_match','umpire1','umpire2'],axis=1)
y=mat['winner']

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0) 
print(x_train,x_test,y_train,y_test)

"""**Random Forest**"""

random_forest=RandomForestClassifier(n_estimators=17,max_depth=5)
random_forest.fit(x_train,y_train)

y_pred=random_forest.predict(x_test)
y_pred_train=random_forest.predict(x_train)

acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

"""**KNN Classifier**"""

knn=KNeighborsClassifier(n_neighbors=11)
knn.fit(x_train,y_train)

y_pred=knn.predict(x_test)
acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

y_pred=knn.predict(x_train)
acc_score=metrics.accuracy_score(y_train,y_pred) #gives the accuracy of the model
print("Accuracy of Train:", acc_score)

"""**Decision Tree**"""

dtree=DecisionTreeClassifier(criterion='entropy',max_depth=16)
dtree.fit(x_train,y_train)

y_pred=dtree.predict(x_test)
acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

y_pred=dtree.predict(x_train)
acc_score = metrics.accuracy_score(y_train,y_pred)
print("Accuracy of Train:", acc_score)

"""**Logistic Regression**"""

logreg = LogisticRegression()
logreg.fit(x_train, y_train)

y_pred=logreg.predict(x_test)
acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

y_pred=logreg.predict(x_train)
acc_score = metrics.accuracy_score(y_train,y_pred)
print("Accuracy of Train:", acc_score)

"""**SVM**"""

svm=SVC(kernel='linear')  
svm.fit(x_train,y_train)`
y_pred=svm.predict(x_test)
y_pred_train=svm.predict(x_train) #y_pred is prediction of test data
acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

acc_score = metrics.accuracy_score(y_train,y_pred_train)
print("Accuracy of Train:", acc_score)

x.head(52).tail(1)

"""## **Winner Prediction**"""

dictVal = encode['winner']

input=['8','10','10','1','0','10','0','8']
input = np.array(input).reshape((1, -1))
output=dtree.predict(input)
print(list(dictVal.keys())[list(dictVal.values()).index(output)])


9ace8f70bdc6b070247e6b8c8902969494bca281
# -*- coding: utf-8 -*-
"""IPL_543.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1AENNkIdInLqwHbaO_D0LrOGfW9208KCv
"""

from google.colab import files
uploaded = files.upload()

# Commented out IPython magic to ensure Python compatibility.
import numpy as np 
import pandas as pd 
import os
import matplotlib.pyplot as plt 
# %matplotlib inline
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression

deliv = pd.read_csv("deliveries.csv")deliv = pd.read_csv("deliveries.csv")
mat  = pd.read_csv("matches.csv")

"""## **Cleaning and Transformtion**"""

mat.drop('umpire3',axis=1,inplace=True)
mat=mat.replace('Rising Pune Supergiants','Rising Pune Supergiant')
deliv.fillna(0,inplace=True)
mat['winner'].fillna('Draw',inplace=True)
mat['city'].fillna('Mumbai',inplace=True)
mat['player_of_match'].fillna('No one',inplace=True)
mat['umpire2'].fillna('SJA Taufel',inplace=True)
mat['umpire1'].fillna('HDPK Dharmasena',inplace=True)
#mat.columns = mat.columns.str.strip()
deliv.rename(columns={'match_id': 'id'}, inplace=True)

"""## Plot the following graph

**Maximum Toss Winners**
"""

plt.subplots(figsize=(8,5))
ax=mat['toss_winner'].value_counts().plot.bar(width=0.5)
for p in ax.patches:
    ax.annotate(format(p.get_height()), (p.get_x()+0.15, p.get_height()+1))
plt.show()

"""**Toss Decision wrt Season**"""

plt.subplots(figsize=(10,6))
sns.countplot(x='season',hue='toss_decision',data=mat)
plt.show()

"""**Toss Decision wrt Team**"""

plt.subplots(figsize=(30,6))
sns.countplot(x='team1',hue='toss_decision',data=mat)
plt.show()

"""**Maximum Wins**"""

'''
mat['winner'].value_counts().plot.bar()
plt.title('Maximum WInners')
plt.xlabel('Teams')
plt.ylabel('Count')
'''
plt.subplots(figsize=(8,6))
wnrs = mat['winner'].value_counts().plot.bar(width=0.5)
for x in wnrs.patches:
  wnrs.annotate(format(x.get_height()),(x.get_x()+0.1,x.get_height()+1))
plt.show()

"""**Total Matches vs Wins for Teams**"""

plt.subplots(figsize=(30,6))
sns.countplot(x='toss_winner',hue='winner',data=mat)
plt.show()

"""**Is Toss Winner Also the Match Winner?**"""

'''
c2 = mat[(mat.winner == mat.toss_winner)]
c2['winner'].value_counts().plot.bar()
plt.title('Percentage of Winning a match if toss is won')
plt.xlabel('Teams')
plt.ylabel('Percentage')
'''
#plt.subplots(figsize=(8,6))
c2 = mat[(mat.winner == mat.toss_winner)]
sall = len(mat.index)
sm=len(c2.index)
print("percentage of winning match if toss is won:-",(sm/sall)*100)
'''
wnrs = c2['winner'].value_counts().plot.bar(width=0.5)
for x in wnrs.patches:
  wnrs.annotate(format(x.get_height()),(x.get_x()+0.1,x.get_height()+1))
plt.show()
'''

d2mat = mat[['id','season']]
d2deliv = deliv[['id','batsman_runs']]
d2 = pd.merge(d2mat,d2deliv,on='id',how='inner')

"""**Sixes and Fours Across the Season**"""

d24 = d2[d2.batsman_runs == 4]
d26 = d2[d2.batsman_runs == 6]

plt.subplots(figsize=(9,6))
d4 = d24['season'].value_counts().plot.bar(width=0.5)
for x in d4.patches:
  d4.annotate(format(x.get_height()),(x.get_x()+0.01,x.get_height()+1.05))
plt.show()
'''
plt.title('Fours in a season')
plt.xlabel('seasons')
plt.ylabel('Count')
'''

plt.subplots(figsize=(9,6))
d6 = d26['season'].value_counts().plot.bar(width=0.5)
for x in d6.patches:
  d6.annotate(format(x.get_height()),(x.get_x()+0.01,x.get_height()+1.5))
plt.title('Sixes in a season')
plt.xlabel('seasons')
plt.ylabel('Count')

"""**Runs Per Over By Teams Across Seasons**"""

rpo = deliv.pivot_table(index=['over'],columns='batting_team',values='total_runs',aggfunc=sum)
mpbt=pd.concat([mat['team1'],mat['team2']])
mpbt=mpbt.value_counts().reset_index()
mpbt.columns=['Team','Total Matches']
mpbt['wins']=mat['winner'].value_counts().reset_index()['winner']
mpbt.set_index('Team',inplace=True)
rpo[(mpbt[mpbt['Total Matches']>50].index)].plot(color=["b", "r", "#Ffb6b2", "g",'brown','y','#6666ff','black','#FFA500']) 
x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
plt.xticks(x)
plt.ylabel('total runs scored')
fig=plt.gcf()
fig.set_size_inches(16,10)
plt.show()

"""**Maximum Man Of Matches**"""

f2 = mat['player_of_match'].value_counts().head().plot.bar()
#ax = matches['player_of_match'].value_counts().head(10).plot.bar(width=.8, color=sns.color_palette('inferno',10))
plt.title("Maximum man of the matches")
plt.xlabel('player of match') 
plt.ylabel('count')

"""### Create a table with the following data also visualize if possible:

**Team Comparator**
"""

a = 'Mumbai Indians'
b = 'Chennai Super Kings'
mt1=mat[(((mat['team1']==a)&(mat['team2']==b))|((mat['team1']==b)&(mat['team2']==a)))]
mt1 = mt1[['team1','team2','winner']]
tc = mt1.groupby(['team1','team2','winner']).size().reset_index().rename(columns={0:'count'})
tc.loc[0,'count'] = tc.loc[0,'count'] + tc.loc[2,'count']
tc.loc[1,'count'] = tc.loc[1,'count'] + tc.loc[3,'count']
tc.loc[0,'team1_wins'] = tc.loc[0,'count']
tc.loc[0,'team2_wins'] = tc.loc[1,'count']
tc.drop(['winner','count'],axis=1,inplace=True)
tc = tc[:1]
tc

"""**Matches Won By A Team Against Other Teams**"""

'''
def matwonagt(a):
  team_l = ['Sunrisers Hyderabad','Mumbai Indians','Gujarat Lions','Rising Pune Supergiants','Royal Challengers Bangalore','Kolkata Knight Riders','Delhi Daredevils','Kings XI Punjab','Chennai Super Kings','Rajasthan Royals','Deccan Chargers','Kochi Tuskers Kerala','Pune Warriors']
  team_l.remove(a)
  teams = team_l.copy()
  mt1=mat[((mat['team1']==a)|(mat['team2']==a))]
  mt1 = mt1[['team1','team2','winner']]
  mtag = mt1.groupby(['team1','team2','winner']).size().reset_index().rename(columns={0:'count'})
  mtag
  for i in range(0,len(mtag)):
    if mtag.loc[i,'team1'] != a:
      t = mtag.loc[i,'team1']
      mtag.loc[i,'team1'] = mtag.loc[i,'team2']
      mtag.loc[i,'team2'] = t
  mtagg = mtag.groupby(['team1','team2'])['count'].sum().reset_index()
  for i in range(0, len(mtagg),2):
    mtagg.loc[i,'looses'] = mtagg.loc[i+1,'count']
  #mtagg = mtagg.iloc[::2]
  mtagg.rename(columns={'count':'wins'},inplace=True)
  print(mtagg)
matwonagt('Chennai Super Kings')
'''

a = 'Chennai Super Kings'
team_l = ['Sunrisers Hyderabad','Mumbai Indians','Gujarat Lions','Rising Pune Supergiants','Royal Challengers Bangalore','Kolkata Knight Riders','Delhi Daredevils','Kings XI Punjab','Chennai Super Kings','Rajasthan Royals','Deccan Chargers','Kochi Tuskers Kerala','Pune Warriors']
team_l.remove(a)
teams = team_l.copy()
mt1=mat[((mat['team1']==a)|(mat['team2']==a))]
mt1 = mt1[['team1','team2','winner']]
mtag = mt1.groupby(['team1','team2','winner']).size().reset_index().rename(columns={0:'count'})
mtag
for i in range(0,len(mtag)):
  if mtag.loc[i,'team1'] != a:
    t = mtag.loc[i,'team1']
    mtag.loc[i,'team1'] = mtag.loc[i,'team2']
    mtag.loc[i,'team2'] = t
mtagg = mtag.groupby(['team1','team2','winner'])['count'].sum().reset_index()
for i in range(0, len(mtagg),2):
  mtagg.loc[i,'looses'] = mtagg.loc[i+1,'count']
mtagg = mtagg.iloc[::2]
mtagg

"""**200+ Scores**"""

sc = deliv.groupby(['id','batting_team'])['total_runs'].sum().reset_index()
plus = sc[sc['total_runs']>200]
plus200 = plus.sort_values(by='total_runs',ascending = False)
plus200.head()

plus2=deliv.groupby(['id', 'inning','batting_team','bowling_team'])['total_runs'].sum().reset_index()
plus2.set_index(['id'],inplace=True)
#plus2['total_runs'].max()
plus2=plus2.rename(columns={'total_runs':'count'})
plus2=plus2[plus2['count']>=200].groupby(['inning','batting_team','bowling_team']).count()
plus2

"""**Chances of chasing 200+ target**"""

d3 = deliv.groupby(['id','inning','batting_team','bowling_team'])['total_runs'].sum().reset_index()
d33 = pd.DataFrame(columns=['id','inning','batting_team','bowling_team','total_runs'])
bb = cc = 0
for i in range(0, len(d3),2):
  a = d3.loc[i,'total_runs']
  b = d3.loc[i+1,'total_runs']
  if a>200:
    bb = bb+1
    if b>a:
      d33 = d33.append(d3[d3['id'] == d3.loc[i,'id']])
      cc = cc +1
d33
print((cc/bb)*100,"%")

"""### **Batsman Comparator**"""

hsr=deliv.groupby(['batsman','batsman_runs'])['total_runs'].count().reset_index()
hsr=hsr.pivot('batsman','batsman_runs','total_runs')

"""**Create a function that compares 2 batsman based on their respective stats like runs or strike rate etc**"""

cmpBats = pd.DataFrame(columns=['batsman','dots','singles','Twos','Threes','Fours','Sixes','total_runs','Average','Strike_rate'])

dfc=deliv.groupby(['batsman'])['ball'].count().reset_index()
runs=deliv.groupby(['batsman'])['batsman_runs'].sum().reset_index()
ones=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==1).sum()).reset_index()
twos=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==2).sum()).reset_index()
threes=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==3).sum()).reset_index()
dots=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==0).sum()).reset_index()
sixes=deliv.groupby('batsman')['batsman_runs'].agg(lambda x: (x==4).sum()).reset_index()
fours=deliv.groupby(['batsman'])['batsman_runs'].agg(lambda x: (x==6).sum()).reset_index()
dfc=dfc.merge(dots,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'dots'},inplace=True)
dfc=dfc.merge(ones,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'ones'},inplace=True)
dfc=dfc.merge(twos,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'twos'},inplace=True)
dfc=dfc.merge(threes,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'threes'},inplace=True)
dfc=dfc.merge(sixes,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'Fours'},inplace=True)
dfc=dfc.merge(fours,on='batsman',how='outer')
dfc.rename(columns={'batsman_runs':'sixes'},inplace=True)
dfc=dfc.merge(runs,on='batsman',how='outer')
runs=deliv.groupby(['batsman'])['batsman_runs'].sum().reset_index()
dfc.rename({'ball':'balls_faced','batsman_runs':'runs_scored'},axis=1,inplace=True)
dfc['strike_rate']=dfc['runs_scored']/dfc['balls_faced']*100
dfc.head()

"""**Create a dataframe from where you will be taking all that values for comparison**"""

dfc

"""**Compare Rohit Sharma and Virat Kohli on runs scored and strike rate**"""

cmp = pd.DataFrame()
cmp = cmp.append(dfc[dfc['batsman']=='V Kohli'])
cmp = cmp.append(dfc[dfc['batsman']=='RG Sharma'])
cmp

"""## **Top Batsman**"""

hsr=deliv.groupby(['batsman','batsman_runs'])['total_runs'].count().reset_index()
hsr=hsr.pivot('batsman','batsman_runs','total_runs')

"""**Top 10 Batsman**"""

top = deliv.groupby(['batsman'])['batsman_runs'].sum()
top10=top.sort_values(ascending=False)[:10]
top10.plot.bar()

"""**Top Batsman's with 1's, 2's, 3's, 4's**"""

hsr[1].sort_values(ascending=False).head().reset_index()

hsr[2].sort_values(ascending=False).head().reset_index()

hsr[3].sort_values(ascending=False).head().reset_index()

hsr[4].sort_values(ascending=False).head().reset_index()

hsr[6].sort_values(ascending=False).head().reset_index()

"""**Top Individual Scores**"""

tis = deliv.groupby(["id",'inning', "batsman"])["batsman_runs"].sum().reset_index()
tis.sort_values('batsman_runs', ascending=0).head()

"""**Highest score in each inning**"""

tisi = deliv.groupby(["id",'inning', "batsman"])["batsman_runs"].sum().reset_index()
tisi.sort_values('batsman_runs', ascending=0).head()
tisi['high_scorer']=""
tisi['high_scorer']=tisi.groupby(['id','inning'])['batsman_runs'].transform(max)
tisi = tisi[tisi['batsman_runs']==tisi['high_scorer']]
tisi

"""**Individual Scores By Top Batsman each Inning**"""

btsmn=['CH Gayle','V Kohli','G Gambhir','SK Raina','YK Pathan','MS Dhoni','AB de Villiers','DA Warner']
scores = deliv.groupby(["id", "batsman","batting_team"])["batsman_runs"].sum().reset_index()
scores=scores[tis['batsman'].isin(btsmn)]
scores

"""### **Top Bowlers**

**Highest Wicket Taker**
"""

outs = ["bowled", "stumped", "caught", "lbw", "caught and bowled","hit wicket"]
hwt=deliv[deliv["dismissal_kind"].isin(outs)]
hwtaker=hwt['bowler'].value_counts()
hwtaker.head().plot.bar()

"""**Maximum Overs**"""

maxo=deliv.groupby(['bowler']).sum()
maxo['balls_count']=deliv['bowler'].value_counts()
maxo['overs_count']=(maxo['balls_count']//6)
maxo.sort_values(by='overs_count')['overs_count'].tail(5).reset_index()

"""**Most Economical Bowlers with 300+ overs**"""

maxo['economy']=(maxo['total_runs']/(maxo['overs_count']))
maxe = maxo[(maxo['overs_count']>300)]
maxe = maxe.sort_values('economy').head().economy.reset_index()
maxe

"""**Highest Dismissals for a Batsman by a Bowler**"""

hd = hwt[['batsman','bowler']]
hd = hd.groupby(['batsman','bowler']).size().reset_index().rename(columns={0:'count'})
hdbb = hd.sort_values(by='count',ascending = False)
hdbb = hdbb.drop_duplicates('batsman').reset_index()
hdbb

"""# Dream11"""

squad = []
mtd11 = mat[['id','season']]
mtd11 = mtd11.loc[mtd11['season']>=2015]
deld11 = deliv[['id','batsman','batsman_runs','bowler','dismissal_kind','fielder']]
mdd11 = pd.merge(mtd11,deld11,on='id',how='inner')
stumps = mdd11.groupby('fielder')['dismissal_kind'].agg(lambda x: (x=='stumped').sum()).reset_index()
stumps = stumps.sort_values(by='dismissal_kind',ascending=False).head().reset_index()
stumps = stumps.head()
wk = stumps['fielder'].unique()
wk = wk.tolist()

scrs = mdd11.groupby(["batsman"])["batsman_runs"].sum().reset_index()
scrs = scrs.sort_values(by='batsman_runs',ascending=False)
wt = scrs[scrs['batsman'].isin(wk)]
wkt = wt.iloc[0]['batsman']
bkpwkt = wt.iloc[1]['batsman']
scrs = scrs[scrs.batsman!=wkt]
scrs = scrs[scrs.batsman!=bkpwkt]
WicketKeeper = wt[:1]['batsman'].tolist()
bkpWicketKeeper = wt[1:2]['batsman'].tolist()
WicketKeeper,bkpWicketKeeper

fielders = mdd11.groupby('fielder')['dismissal_kind'].agg(lambda x: (x=='caught').sum()).reset_index()
fielders = fielders.sort_values(by='dismissal_kind',ascending=False).reset_index()
best_fielders = fielders.head(100)
bf = best_fielders['fielder'].unique()
bf = bf.tolist()

btsms = scrs[scrs['batsman'].isin(bf)]
Batsmans = btsms[:4]['batsman'].tolist()
bkpBatsmans = btsms[4:6]['batsman'].tolist()
Batsmans,bkpBatsmans

saa=mdd11[mdd11["dismissal_kind"].isin(outs)]
blwr=saa['bowler'].value_counts().reset_index()
btsms = scrs[scrs['batsman'].isin(bf)]
wktsmean = blwr["bowler"].mean()
scrmean = btsms['batsman_runs'].mean()

allr = btsms.loc[btsms['batsman_runs']>500]
allr = allr[6:]
allrr = blwr.loc[blwr['bowler']>18]
allrr = allrr[6:]
allr1 = allrr['index'].unique()
allr1 = allr1.tolist()
alr = allr[allr['batsman'].isin(allr1)]
Allrounders = alr[:2]['batsman'].tolist()
bkpAllrounders = alr[2:]['batsman'].tolist()
Allrounders,bkpAllrounders

Bowlers = blwr[:4]['index'].tolist()
bkpBowlers = blwr[4:6]['index'].tolist()
Bowlers,bkpBowlers

Team11 = WicketKeeper + Batsmans +Allrounders + Bowlers
BackupPlayers = bkpWicketKeeper + bkpBatsmans + bkpAllrounders + bkpBowlers
Squad = Team11 + BackupPlayers

Team11

Squad

BackupPlayers

"""**Algorithms and their Accuracy**"""

mat.replace(['Mumbai Indians','Kolkata Knight Riders','Royal Challengers Bangalore','Deccan Chargers','Chennai Super Kings',
                 'Rajasthan Royals','Delhi Daredevils','Gujarat Lions','Kings XI Punjab',
                 'Sunrisers Hyderabad','Rising Pune Supergiant','Kochi Tuskers Kerala','Pune Warriors']
                ,['MI','KKR','RCB','DC','CSK','RR','DD','GL','KXIP','SRH','RPS','KTK','PW'],inplace=True)
encode = {'team1': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DD':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'team2': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DD':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'toss_winner': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DD':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'winner': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DD':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13,'Draw':14}}
mat.replace(encode, inplace=True)
mat.head(2)

from sklearn.preprocessing import LabelEncoder
var_mod = ['city','toss_decision','venue']
le = LabelEncoder()
for i in var_mod:
    mat[i] = le.fit_transform(mat[i])
mat.dtypes

x=mat.drop(['id','season','date','result','dl_applied','winner','player_of_match','umpire1','umpire2'],axis=1)
y=mat['winner']

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0) 
print(x_train,x_test,y_train,y_test)

"""**Random Forest**"""

random_forest=RandomForestClassifier(n_estimators=17,max_depth=5)
random_forest.fit(x_train,y_train)

y_pred=random_forest.predict(x_test)
y_pred_train=random_forest.predict(x_train)

acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

"""**KNN Classifier**"""

knn=KNeighborsClassifier(n_neighbors=11)
knn.fit(x_train,y_train)

y_pred=knn.predict(x_test)
acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

y_pred=knn.predict(x_train)
acc_score=metrics.accuracy_score(y_train,y_pred) #gives the accuracy of the model
print("Accuracy of Train:", acc_score)

"""**Decision Tree**"""

dtree=DecisionTreeClassifier(criterion='entropy',max_depth=16)
dtree.fit(x_train,y_train)

y_pred=dtree.predict(x_test)
acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

y_pred=dtree.predict(x_train)
acc_score = metrics.accuracy_score(y_train,y_pred)
print("Accuracy of Train:", acc_score)

"""**Logistic Regression**"""

logreg = LogisticRegression()
logreg.fit(x_train, y_train)

y_pred=logreg.predict(x_test)
acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

y_pred=logreg.predict(x_train)
acc_score = metrics.accuracy_score(y_train,y_pred)
print("Accuracy of Train:", acc_score)

"""**SVM**"""

svm=SVC(kernel='linear')  
svm.fit(x_train,y_train)`
y_pred=svm.predict(x_test)
y_pred_train=svm.predict(x_train) #y_pred is prediction of test data
acc_score=metrics.accuracy_score(y_test,y_pred) #gives the accuracy of the model
print("Accuracy of Test:", acc_score)

acc_score = metrics.accuracy_score(y_train,y_pred_train)
print("Accuracy of Train:", acc_score)

x.head(52).tail(1)

"""## **Winner Prediction**"""

dictVal = encode['winner']

input=['8','10','10','1','0','10','0','8']
input = np.array(input).reshape((1, -1))
output=dtree.predict(input)
print(list(dictVal.keys())[list(dictVal.values()).index(output)])

