Cricketr analyzes Ind-Aus faceoff in WTC 2023!!

“The unexamined life is not worth living.” – Socrates

“There is no easy way from the earth to the stars.” – Seneca

“If you want to go fast, go alone. If you want to go far, go together.” – African Proverb

1. Introduction

In this post, I put my R package cricketr to analyze the Indian and Australia World Test Championship (WTC) final squad ahead of the World Test Championship 2023.My R package cricketr had its birth on Jul 4, 2015. Cricketr uses data from Cricinfo.

You can download the latest PDF version of the book  at  ‘Cricket analytics with cricketr and cricpy: Analytics harmony with R and Python-6th edition

Indian squad

Rohit Sharma (Captain), Shubman Gill, Cheteshwar Pujara, Virat Kohli, Ajinkya Rahane, Ravindra Jadeja, Shardul Thakur, Mohd. Shami, Mohd. Siraj, Ishan Kishan (wk).

According to me, Ishan Kishan has more experience than KS Bharat, though Rishabh Pant would have been the ideal wicket keeper/left-handed batsman. I think Shardul Thakur would be handful in the English conditions. For a spinner it either Ashwin or Jadeja. Maybe the balance shifts in favor of Jadeja

Australian squad

Pat Cummins (capt), Alex Carey (wk), Cameron Green, Josh Hazlewood, Usman Khawaja, Marnus Labuschagne, Nathan Lyon, Todd Murphy, Steven Smith (vice-capt), Mitchell Starc, David Warner.

Not sure if Scott Boland would fill in, instead of Todd Murphy 1

Let me give you a lay-of-the-land (post) below

The post below is organized into the following parts

  1. Analysis of Indian WTC batsmen from Jan 2016 – May 2023
  2. Analysis of Indian WTC batsmen against Australia from Jan 2016 -May 2023
  3. Analysis of Australian WTC batsmen from Jan 2016 – May 2023
  4. Analysis of Australian WTC batsmen against India from Jan 2016 -May 2023
  5. Analysis of Indian WTC bowlers from Jan 2016 – May 2023
  6. Analysis of Indian WTC bowlers against Australia from Jan 2016 -May 2023
  7. Analysis of Australian WTC bowlers from Jan 2016 – May 2023
  8. Analysis of Australian WTC bowlers gainst India from Jan 2016 -May 2023
  9. Team analysis of India and Australia

All the above analysis use data from ESPN Statsguru and use my R pakage cricketr

The data for the different players have been obtained using calls such as the ones below.

# Get Shubman Gill's batting data
#shubman <-getPlayerData(1070173,dir=".",file="shubman.csv",type="batting",homeOrAway=c(1,2), result=c(1,2,4))
#shubmansp <- getPlayerDataSp(1070173,tdir=".",tfile="shubmansp.csv",ttype="batting")

#Get Shubman Gill's data from Jan 2016 - May 2023
#df <-getPlayerDataHA(1070173,tfile="shubman1.csv",type="batting", matchType="Test")
#df1=getPlayerDataOppnHA(infile="shubman1.csv",outfile="shubmanTestAus.csv",startDate="2016-01-01",endDate="2023-05-01")

#Get Shubman Gills data from Jan 2016 - May 2023, against Australia
#df <-getPlayerDataHA(1070173,tfile="shubman1.csv",type="batting", matchType="Test")
#df1=getPlayerDataOppnHA(infile="shubman1.csv",outfile="shubmanTestAus.csv",opposition="Australia",startDate="2016-01-01",endDate="2023-05-01")

Note: To get data for bowlers we need to use the corresponding profile no and use type =‘bowling’. Details in my posts below

To do similar analysis please go through the following posts

  1. Re-introducing cricketr! : An R package to analyze performances of cricketers
  2. Cricketr learns new tricks : Performs fine-grained analysis of players
  3. Cricketr adds team analytics to its repertoire!!!

Note 1: I will not be analysing each and every chart as the charts are quite self-explanatory 

Note 2: I have had to tile charts together otherwise this will become a very, very long post. You are free to use my R package cricketr and check out for yourself ##3. Analysis of India WTC batsmen from Jan 2016 – May 2023

Findings

  1. Kohli has the best average of 48+. India has won when Rohit and Rahane played well
  2. Kohli’s tops the list in cumulative average runs, followed by Pujara and Rohit is 3rd. Gill is on the upswing.
  3. Against Australia Pujara has the best cumulative average runs record followed by Rahane, with Gill in hot pursuit. In the strike rate department Gill tops followed by Rohit and Rahane
  4. Since 2016 Smith, Labuschagne has an average of 53+ since 2016!! Warner & Khwaja are at ~46
  5. Australia has won matches when Smith, Warner and Khwaja have played well.
  6. Labuschagne, Smith and C Green have good records against India. Indian bowlers will need to contain them
  7. Ashwin has the highest wickets followed by Jadeja against all teams. Ashwin’s performance has dropped over the years, while Siraj has been becoming better
  8. Jadeja has the best economy rate followed by Ashwin
  9. Against Australia specifically Jadeja has the best record followed by Ashwin. Jadeja has the best economy against Australia, followed by Siraj, then Ashwin
  10. Cummins, Starc and Lyons are the best performers for Australia. Hazzlewood, Cummins have the best economy against all opposition
  11. Against India Lyon, Cummins and Hazzlewood have performed well
  12. Hazzlewood, Lyon have a good economy rate against India
  13. Against Australia India has won 17 times, lost 60 and drawn 22 in Australia. At home India won 42, tied 2, lost 28 and drawn 24
  14. At the Oval where the World Test Championship is going to be held India has won 4, lost 10 and drawn 10.

Note 3: You can also read this post at Rpubs at ind-aus-WTC!! The formatting will be nicer!

Note 4: You can download this post as PDF to read at your leisure ind-aus-WTC.pdf

2. Install the cricketr package

if (!require("cricketr")){
    install.packages("cricketr",lib = "c:/test")
}
library(cricketr)

3a. Basic analysis

The analyses below include – Runs frequency plot – Mean strike rate – Run Ranges

Kohli’s strike rate increases with increasing runs, while Gill’s seems to drop. So it is with Pujara & Rahane

par(mfrow=c(3,3))
par(mar=c(4,4,2,2))
batsmanRunsFreqPerf("kohliTest.csv","Kohli")
batsmanMeanStrikeRate("kohliTest.csv","Kohli")
batsmanRunsRanges("kohliTest.csv","Kohli")

batsmanRunsFreqPerf("rohitTest.csv","Rohit")
batsmanMeanStrikeRate("rohitTest.csv","Rohit")
batsmanRunsRanges("rohitTest.csv","Rohit")

batsmanRunsFreqPerf("shubmanTest.csv","S Gill")
batsmanMeanStrikeRate("shubmanTest.csv","S Gill")
batsmanRunsRanges("shubmanTest.csv","S Gill")
par(mfrow=c(2,3))
par(mar=c(4,4,2,2))
batsmanRunsFreqPerf("rahaneTest.csv","Rahane")
batsmanMeanStrikeRate("rahaneTest.csv","Rahane")
batsmanRunsRanges("rahaneTest.csv","Rahane")

batsmanRunsFreqPerf("pujaraTest.csv","Pujara")
batsmanMeanStrikeRate("pujaraTest.csv","Pujara")
batsmanRunsRanges("pujaraTest.csv","Pujara")

3b. More analyses

Kohli hits roughly 5 4s in his 50 versus Gill,Pujara who is able to smash 6 4s.

par(mfrow=c(3,3))
par(mar=c(4,4,2,2))

batsman4s("kohliTest.csv","Kohli")
batsman6s("kohliTest.csv","Kohli")
batsmanMeanStrikeRate("kohliTest.csv","Kohli")

batsman4s("rohitTest.csv","Rohit")
batsman6s("rohitTest.csv","Rohit")
batsmanMeanStrikeRate("rohitTest.csv","Rohit")

batsman4s("shubmanTest.csv","S Gill")
batsman6s("shubmanTest.csv","S Gill")
batsmanMeanStrikeRate("shubmanTest.csv","S Gill")
par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

batsman4s("rahaneTest.csv","Rahane")
batsman6s("rahaneTest.csv","Rahane")
batsmanMeanStrikeRate("rahane.csv","Rahane")

batsman4s("pujaraTest.csv","Pujara")
batsman6s("pujaraTest.csv","Pujara")
batsmanMeanStrikeRate("pujaraTest.csv","Pujara")

3c.Boxplot histogram plot

This plot shows a combined boxplot of the Runs ranges and a histog2ram of the Runs Frequency Kohli’s average is 48, while Rohit,Pujara is 40 with Rahane and Gill around 33.

batsmanPerfBoxHist("kohliTest.csv","Kohli")
batsmanPerfBoxHist("rohitTest.csv","Rohit")
batsmanPerfBoxHist("shubmanTest.csv","S Gill")
batsmanPerfBoxHist("rahaneTest.csv","Rahane")
batsmanPerfBoxHist("pujaraTest.csv","Pujara")

3d. Contribution to won and lost matches

For the functions below you will have to use the getPlayerDataSp() function. When Rohit Sharma and Pujara have played well India have tended to win more often

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanContributionWonLost("kohlisp.csv","Kohli")
batsmanContributionWonLost("rohitsp.csv","Rohit")
batsmanContributionWonLost("rahanesp.csv","Rahane")
batsmanContributionWonLost("pujarasp.csv","Pujara")

3e. Performance at home and overseas

This function also requires the use of getPlayerDataSp() as shown above. This can only be used for Test matches

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanPerfHomeAway("kohlisp.csv","Kohli")
batsmanPerfHomeAway("rohitsp.csv","Rohit")
batsmanPerfHomeAway("rahanesp.csv","Rahane")
batsmanPerfHomeAway("pujarasp.csv","Pujara")

3f. Batsman average at different venues

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanAvgRunsGround("kohliTest.csv","Kohli")
batsmanAvgRunsGround("rohitTest.csv","Rohit")
batsmanAvgRunsGround("rahaneTest.csv","Rahane")
batsmanAvgRunsGround("pujaraTest.csv","Pujara")

3g. Batsman average against different opposition

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanAvgRunsOpposition("kohliTest.csv","Kohli")
batsmanAvgRunsOpposition("rohitTest.csv","Rohit")
batsmanAvgRunsOpposition("rahaneTest.csv","Rahane")
batsmanAvgRunsOpposition("pujaraTest.csv","Pujara")

3h. Runs Likelihood of batsman

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanRunsLikelihood("kohli.csv","Kohli")
## Summary of  Kohli 's runs scoring likelihood
## **************************************************
## 
## There is a 52.91 % likelihood that Kohli  will make  12 Runs in  26 balls over 35  Minutes 
## There is a 30.81 % likelihood that Kohli  will make  52 Runs in  100 balls over  139  Minutes 
## There is a 16.28 % likelihood that Kohli  will make  142 Runs in  237 balls over 335  Minutes
batsmanRunsLikelihood("rohit.csv","Rohit")
## Summary of  Rohit 's runs scoring likelihood
## **************************************************
## 
## There is a 43.24 % likelihood that Rohit  will make  10 Runs in  21 balls over 32  Minutes 
## There is a 45.95 % likelihood that Rohit  will make  46 Runs in  85 balls over  124  Minutes 
## There is a 10.81 % likelihood that Rohit  will make  110 Runs in  199 balls over 282  Minutes
batsmanRunsLikelihood("rahane.csv","Rahane")
## Summary of  Rahane 's runs scoring likelihood
## **************************************************
## 
## There is a 7.75 % likelihood that Rahane  will make  124 Runs in  224 balls over 318  Minutes 
## There is a 62.02 % likelihood that Rahane  will make  12 Runs in  26 balls over  37  Minutes 
## There is a 30.23 % likelihood that Rahane  will make  55 Runs in  113 balls over 162  Minutes
batsmanRunsLikelihood("pujara.csv","Pujara")
## Summary of  Pujara 's runs scoring likelihood
## **************************************************
## 
## There is a 60.49 % likelihood that Pujara  will make  15 Runs in  38 balls over 55  Minutes 
## There is a 31.48 % likelihood that Pujara  will make  62 Runs in  142 balls over  204  Minutes 
## There is a 8.02 % likelihood that Pujara  will make  153 Runs in  319 balls over 445  Minutes

3h1. Moving average of batsman

Kohli’s moving average in tests seem to havw dropped after a peak in 2017, 2018. So it is with Rahane

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanMovingAverage("kohli.csv","Kohli")
batsmanMovingAverage("rohit.csv","Rohit")
batsmanMovingAverage("rahane.csv","Rahane")
batsmanMovingAverage("pujara.csv","Pujara")

3i. Cumulative Average runs of batsman in career

Kohli’s cumulative average averages to ~48. Shubman Gill’s cumulative average is on the rise.

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanCumulativeAverageRuns("kohliTest.csv","Kohli")
batsmanCumulativeAverageRuns("rohitTest.csv","Rohit")
batsmanCumulativeAverageRuns("rahaneTest.csv","Rahane")
batsmanCumulativeAverageRuns("pujaraTest.csv","Pujara")
batsmanCumulativeAverageRuns("shubmanTest.csv","S Gill")

3j Cumulative Average strike rate of batsman in career

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanCumulativeStrikeRate("kohliTest.csv","Kohli")
batsmanCumulativeStrikeRate("rohitTest.csv","Rohit")
batsmanCumulativeStrikeRate("rahaneTest.csv","Rahane")
batsmanCumulativeStrikeRate("pujaraTest.csv","Pujara")
batsmanCumulativeStrikeRate("shubmanTest.csv","S Gill")

3k. Future Runs forecast

Here are plots that forecast how the batsman will perform in future. In this case 90% of the career runs trend is uses as the training set. the remaining 10% is the test set.

A Holt-Winters forecating model is used to forecast future performance based on the 90% training set. The forecated runs trend is plotted. The test set is also plotted to see how close the forecast and the actual matches

Take a look at the runs forecasted for the batsman below.

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanPerfForecast("kohli.csv","Kohli")
batsmanPerfForecast("rohit.csv","Rohit")
batsmanPerfForecast("rahane.csv","Rahane")
batsmanPerfForecast("pujara.csv","Pujara")

3l. Relative Mean Strike Rate plot

The plot below compares the Mean Strike Rate of the batsman for each of the runs ranges of 10 and plots them. The plot indicate the following

frames <- list("kohliTest.csv","rohitTest.csv","pujaraTest.csv","rahaneTest.csv","shubmanTest.csv")
names <- list("Kohli","Rohit","Pujara","Rahane","S Gill")
relativeBatsmanSR(frames,names)

3m. Relative Runs Frequency plot

The plot below gives the relative Runs Frequency Percetages for each 10 run bucket. The plot below show

frames <- list("kohliTest.csv","rohitTest.csv","pujaraTest.csv","rahaneTest.csv","shubmanTest.csv")
names <- list("Kohli","Rohit","Pujara","Rahane","S Gill")
relativeRunsFreqPerf(frames,names)

3n. Relative cumulative average runs in career

Kohli’s tops the list, followed by Pujara and Rohit is 3rd. Gill is on the upswing. Hope he performs well.

frames <- list("kohliTest.csv","rohitTest.csv","pujaraTest.csv","rahaneTest.csv","shubmanTest.csv")
names <- list("Kohli","Rohit","Pujara","Rahane","S Gill")
relativeBatsmanCumulativeAvgRuns(frames,names)

3o. Relative cumulative average strike rate in career

ROhit has the best strike rate followed by Kohli, with Shubman Gill ctaching up fast

frames <- list("kohliTest.csv","rohitTest.csv","pujaraTest.csv","rahaneTest.csv","shubmanTest.csv")
names <- list("Kohli","Rohit","Pujara","Rahane","S Gill")
relativeBatsmanCumulativeStrikeRate(frames,names)

3p. Check Batsman In-Form or Out-of-Form

The below computation uses Null Hypothesis testing and p-value to determine if the batsman is in-form or out-of-form. For this 90% of the career runs is chosen as the population and the mean computed. The last 10% is chosen to be the sample set and the sample Mean and the sample Standard Deviation are caculated.

The Null Hypothesis (H0) assumes that the batsman continues to stay in-form where the sample mean is within 95% confidence interval of population mean The Alternative (Ha) assumes that the batsman is out of form the sample mean is beyond the 95% confidence interval of the population mean.

A significance value of 0.05 is chosen and p-value us computed If p-value >= .05 – Batsman In-Form If p-value < 0.05 – Batsman Out-of-Form

Note Ideally the p-value should be done for a population that follows the Normal Distribution. But the runs population is usually left skewed. So some correction may be needed. I will revisit this later

This is done for the Top 4 batsman

checkBatsmanInForm("kohli.csv","Kohli")
## [1] "**************************** Form status of Kohli ****************************\n\n Population size: 154  Mean of population: 47.03 \n Sample size: 18  Mean of sample: 32.22 SD of sample: 42.45 \n\n Null hypothesis H0 : Kohli 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : Kohli 's sample average is below the 95% confidence interval of population average\n\n Kohli 's Form Status: In-Form because the p value: 0.078058  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBatsmanInForm("rohit.csv","Rohit")
## [1] "**************************** Form status of Rohit ****************************\n\n Population size: 66  Mean of population: 37.03 \n Sample size: 8  Mean of sample: 37.88 SD of sample: 35.38 \n\n Null hypothesis H0 : Rohit 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : Rohit 's sample average is below the 95% confidence interval of population average\n\n Rohit 's Form Status: In-Form because the p value: 0.526254  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBatsmanInForm("rahane.csv","Rahane")
## [1] "**************************** Form status of Rahane ****************************\n\n Population size: 116  Mean of population: 34.78 \n Sample size: 13  Mean of sample: 21.38 SD of sample: 21.96 \n\n Null hypothesis H0 : Rahane 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : Rahane 's sample average is below the 95% confidence interval of population average\n\n Rahane 's Form Status: Out-of-Form because the p value: 0.023244  is less than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBatsmanInForm("pujara.csv","Pujara")
## [1] "**************************** Form status of Pujara ****************************\n\n Population size: 145  Mean of population: 41.93 \n Sample size: 17  Mean of sample: 33.24 SD of sample: 31.74 \n\n Null hypothesis H0 : Pujara 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : Pujara 's sample average is below the 95% confidence interval of population average\n\n Pujara 's Form Status: In-Form because the p value: 0.137319  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBatsmanInForm("shubman.csv","S Gill")
## [1] "**************************** Form status of S Gill ****************************\n\n Population size: 23  Mean of population: 30.43 \n Sample size: 3  Mean of sample: 51.33 SD of sample: 66.88 \n\n Null hypothesis H0 : S Gill 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : S Gill 's sample average is below the 95% confidence interval of population average\n\n S Gill 's Form Status: In-Form because the p value: 0.687033  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"

3q. Predicting Runs given Balls Faced and Minutes at Crease

A multi-variate regression plane is fitted between Runs and Balls faced +Minutes at crease.

BF <- seq( 10, 400,length=15)
Mins <- seq(30,600,length=15)
newDF <- data.frame(BF,Mins)
kohli1 <- batsmanRunsPredict("kohli.csv","Kohli",newdataframe=newDF)
rohit1 <- batsmanRunsPredict("rohit.csv","Rohit",newdataframe=newDF)
pujara1 <- batsmanRunsPredict("pujara.csv","Pujara",newdataframe=newDF)
rahane1 <- batsmanRunsPredict("rahane.csv","Rahane",newdataframe=newDF)
sgill1 <- batsmanRunsPredict("shubman.csv","S Gill",newdataframe=newDF)
batsmen <-cbind(round(kohli1$Runs),round(rohit1$Runs),round(pujara1$Runs),round(rahane1$Runs),round(sgill1$Runs))
colnames(batsmen) <- c("Kohli","Rohit","Pujara","Rahane","S Gill")
newDF <- data.frame(round(newDF$BF),round(newDF$Mins))
colnames(newDF) <- c("BallsFaced","MinsAtCrease")
predictedRuns <- cbind(newDF,batsmen)
predictedRuns
##    BallsFaced MinsAtCrease Kohli Rohit Pujara Rahane S Gill
## 1          10           30     6     3      3      2      7
## 2          38           71    24    19     16     17     24
## 3          66          111    41    35     29     31     40
## 4          94          152    58    51     42     45     56
## 5         121          193    76    66     55     59     73
## 6         149          234    93    82     68     74     89
## 7         177          274   110    98     80     88    106
## 8         205          315   128   114     93    102    122
## 9         233          356   145   129    106    116    139
## 10        261          396   163   145    119    130    155
## 11        289          437   180   161    132    145    171
## 12        316          478   197   177    144    159    188
## 13        344          519   215   192    157    173    204
## 14        372          559   232   208    170    187    221
## 15        400          600   249   224    183    202    237

4. Analysis of India WTC batsmen from Jan 2016 – May 2023 against Australia

4a. Relative cumulative average

Against Australia specifically between 2016 – 2023, Pujara has the best record followed by Rahane, with Gill in hot pursuit. Kohli and Rohit trail behind

frames <- list("kohliTestAus.csv","rohitTestAus.csv","pujaraTestAus.csv","rahaneTestAus.csv","shubmanTestAus.csv")
names <- list("Kohli","Rohit","Pujara","Rahane","S Gill")
relativeBatsmanCumulativeAvgRuns(frames,names)

4b. Relative cumulative average strike rate in career

In the Strike Rate department Gill tops followed by Rohit and Rahane

frames <- list("kohliTestAus.csv","rohitTestAus.csv","pujaraTestAus.csv","rahaneTestAus.csv","shubmanTestAus.csv")
names <- list("Kohli","Rohit","Pujara","Rahane","S Gill")
relativeBatsmanCumulativeStrikeRate(frames,names)

5. Analysis of Australia WTC batsmen from Jan 2016 – May 2023

5a Basic analyses

par(mfrow=c(3,3))
par(mar=c(4,4,2,2))
batsmanRunsFreqPerf("stevesmithTest.csv","S Smith")
batsmanMeanStrikeRate("stevesmithTest.csv","S Smith")
batsmanRunsRanges("stevesmithTest.csv","S Smith")

batsmanRunsFreqPerf("warnerTest.csv","Warner")
batsmanMeanStrikeRate("warnerTest.csv","Warner")
batsmanRunsRanges("warnerTest.csv","Warner")

batsmanRunsFreqPerf("labuschagneTest.csv","M Labuschagne")
batsmanMeanStrikeRate("labuschagneTest.csv","M Labuschagne")
batsmanRunsRanges("labuschagneTest.csv","M Labuschagne")
par(mfrow=c(2,3))
par(mar=c(4,4,2,2))
batsmanRunsFreqPerf("cgreenTest.csv","C Green")
batsmanMeanStrikeRate("cgreenTest.csv","C Green")
batsmanRunsRanges("cgreenTest.csv","C Green")

batsmanRunsFreqPerf("khwajaTest.csv","Khwaja")
batsmanMeanStrikeRate("khwajaTest.csv","Khwaja")
batsmanRunsRanges("khwajaTest.csv","Khwaja")

5b. More analyses

par(mfrow=c(3,3))
par(mar=c(4,4,2,2))
batsman4s("stevesmithTest.csv","S Smith")
batsman6s("stevesmithTest.csv","S Smith")
batsmanMeanStrikeRate("stevesmithTest.csv","S Smith")

batsman4s("warnerTest.csv","Warner")
batsman6s("warnerTest.csv","Warner")
batsmanMeanStrikeRate("warnerTest.csv","Warner")

batsman4s("labuschagneTest.csv","M Labuschagne")
batsman6s("labuschagneTest.csv","M Labuschagne")
batsmanMeanStrikeRate("labuschagneTest.csv","M Labuschagne")
par(mfrow=c(2,3))
par(mar=c(4,4,2,2))
batsman4s("cgreenTest.csv","C Green")
batsman6s("cgreenTest.csv","C Green")
batsmanMeanStrikeRate("cgreenTest.csv","C Green")

batsman4s("khwajaTest.csv","Khwaja")
batsman6s("khwajaTest.csv","Khwaja")
batsmanMeanStrikeRate("khwajaTest.csv","Khwaja")

5c.Boxplot histogram plot

This plot shows a combined boxplot of the Runs ranges and a histog2ram of the Runs Frequency

Smith, Labuschagne has an average of 53+ since 2016!! Warner & Khwaja are at ~46

batsmanPerfBoxHist("stevesmithTest.csv","S Smith")
batsmanPerfBoxHist("warnerTest.csv","Warner")
batsmanPerfBoxHist("labuschagneTest.csv","M Labuschagne")
batsmanPerfBoxHist("cgreenTest.csv","C Green")
batsmanPerfBoxHist("khwajaTest.csv","Khwaja")

5d. Contribution to won and lost matches

For the 2 functions below you will have to use the getPlayerDataSp() function. Australia has won matches when Smith, Warner and Khwaja have played well.

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))
batsmanContributionWonLost("stevesmithsp.csv","S Smith")
batsmanContributionWonLost("warnersp.csv","Warner")
batsmanContributionWonLost("labuschagnesp.csv","M Labuschagne")
batsmanContributionWonLost("cgreensp.csv","C Green")
batsmanContributionWonLost("khwajasp.csv","Khwaja")

5e. Performance at home and overseas

This function also requires the use of getPlayerDataSp() as shown above. This can only be used for Test matches

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanPerfHomeAway("stevesmithsp.csv","S Smith")
batsmanPerfHomeAway("warnersp.csv","Warner")
batsmanPerfHomeAway("labuschagnesp.csv","M Labuschagne")
batsmanPerfHomeAway("cgreensp.csv","C Green")
batsmanPerfHomeAway("khwajasp.csv","Khwaja")

5f. Batsman average at different venues

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanAvgRunsGround("stevesmithTest.csv","S Smith")
batsmanAvgRunsGround("warnerTest.csv","Warner")
batsmanAvgRunsGround("labuschagneTest.csv","M Labuschagne")
batsmanAvgRunsGround("cgreenTest.csv","C Green")
batsmanAvgRunsGround("khwajaTest.csv","Khwaja")

5g. Batsman average against different opposition

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanAvgRunsOpposition("stevesmithTest.csv","S Smith")
batsmanAvgRunsOpposition("warnerTest.csv","Warner")
batsmanAvgRunsOpposition("labuschagneTest.csv","M Labuschagne")
batsmanAvgRunsOpposition("khwajaTest.csv","Khwaja")

5h. Runs Likelihood of batsman

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanRunsLikelihood("stevesmithTest.csv","S Smith")
## Summary of  S Smith 's runs scoring likelihood
## **************************************************
## 
## There is a 58.76 % likelihood that S Smith  will make  21 Runs in  38 balls over 56  Minutes 
## There is a 24.74 % likelihood that S Smith  will make  70 Runs in  148 balls over  210  Minutes 
## There is a 16.49 % likelihood that S Smith  will make  148 Runs in  268 balls over 398  Minutes
batsmanRunsLikelihood("warnerTest.csv","Warner")
## Summary of  Warner 's runs scoring likelihood
## **************************************************
## 
## There is a 7.22 % likelihood that Warner  will make  155 Runs in  253 balls over 372  Minutes 
## There is a 62.89 % likelihood that Warner  will make  14 Runs in  21 balls over  32  Minutes 
## There is a 29.9 % likelihood that Warner  will make  65 Runs in  94 balls over 135  Minutes
batsmanRunsLikelihood("labuschagneTest.csv","M Labuschagne")
## Summary of  M Labuschagne 's runs scoring likelihood
## **************************************************
## 
## There is a 32.76 % likelihood that M Labuschagne  will make  74 Runs in  144 balls over 206  Minutes 
## There is a 55.17 % likelihood that M Labuschagne  will make  22 Runs in  37 balls over  54  Minutes 
## There is a 12.07 % likelihood that M Labuschagne  will make  168 Runs in  297 balls over 420  Minutes
batsmanRunsLikelihood("khwajaTest.csv","Khwaja")
## Summary of  Khwaja 's runs scoring likelihood
## **************************************************
## 
## There is a 64.94 % likelihood that Khwaja  will make  14 Runs in  29 balls over 42  Minutes 
## There is a 27.27 % likelihood that Khwaja  will make  79 Runs in  148 balls over  210  Minutes 
## There is a 7.79 % likelihood that Khwaja  will make  165 Runs in  351 balls over 515  Minutes

5i. Moving average of batsman

Smith and Warner’s moving average has been on a downward trend lately. Khwaja is playing well

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanMovingAverage("stevesmith.csv","S Smith")
batsmanMovingAverage("warner.csv","Warner")
batsmanMovingAverage("labuschagne.csv","M Labuschagne")
batsmanMovingAverage("khwaja.csv","Khwaja")

5j. Cumulative Average runs of batsman in career

Labuschagne, SMith and Warner havwe very good cumulative average

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanCumulativeAverageRuns("stevesmithTest.csv","S Smith")
batsmanCumulativeAverageRuns("warnerTest.csv","Warner")
batsmanCumulativeAverageRuns("labuschagneTest.csv","M Labuschagne")
batsmanCumulativeAverageRuns("khwajaTest.csv","Khwaja")

5k. Cumulative Average strike rate of batsman in career

Warner towers over the others in the cumulative strike rate, followed by Labuschagne and Smith

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanCumulativeStrikeRate("stevesmithTest.csv","S Smith")
batsmanCumulativeStrikeRate("warnerTest.csv","Warner")
batsmanCumulativeStrikeRate("labuschagneTest.csv","M Labuschagne")
batsmanCumulativeStrikeRate("khwajaTest.csv","Khwaja")

5l. Future Runs forecast

Here are plots that forecast how the batsman will perform in future. In this case 90% of the career runs trend is uses as the training set. the remaining 10% is the test set.

A Holt-Winters forecating model is used to forecast future performance based on the 90% training set. The forecated runs trend is plotted. The test set is also plotted to see how close the forecast and the actual matches

Take a look at the runs forecasted for the batsman below.

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

batsmanPerfForecast("stevesmithTest.csv","S Smith")
batsmanPerfForecast("warnerTest.csv","Warner")
batsmanPerfForecast("labuschagneTest.csv","M Labuschagne")
batsmanPerfForecast("khwajaTest.csv","Khwaja")

5m. Relative Mean Strike Rate plot

The plot below compares the Mean Strike Rate of the batsman for each of the runs ranges of 10 and plots them. The plot indicate the following

frames <- list("stevesmithTest.csv","warnerTest.csv","khwajaTest.csv","labuschagneTest.csv","cgreenTest.csv")
names <- list("S Smith","Warner","Khwaja","Labuschagne","C Green")
relativeBatsmanSR(frames,names)

5n. Relative Runs Frequency plot

The plot below gives the relative Runs Frequency Percetages for each 10 run bucket. The plot below show

frames <- list("stevesmithTest.csv","warnerTest.csv","khwajaTest.csv","labuschagneTest.csv","cgreenTest.csv")
names <- list("S Smith","Warner","Khwaja","Labuschagne","C Green")
relativeRunsFreqPerf(frames,names)

5o. Relative cumulative average runs in career

frames <- list("stevesmithTest.csv","warnerTest.csv","khwajaTest.csv","labuschagneTest.csv","cgreenTest.csv")
names <- list("S Smith","Warner","Khwaja","Labuschagne","C Green")
relativeBatsmanCumulativeAvgRuns(frames,names)

5p. Relative cumulative average strike rate in career

frames <- list("stevesmithTest.csv","warnerTest.csv","khwajaTest.csv","labuschagneTest.csv","cgreenTest.csv")
names <- list("S Smith","Warner","Khwaja","Labuschagne","C Green")
relativeBatsmanCumulativeStrikeRate(frames,names)

5q. Check Batsman In-Form or Out-of-Form

The below computation uses Null Hypothesis testing and p-value to determine if the batsman is in-form or out-of-form. For this 90% of the career runs is chosen as the population and the mean computed. The last 10% is chosen to be the sample set and the sample Mean and the sample Standard Deviation are caculated.

The Null Hypothesis (H0) assumes that the batsman continues to stay in-form where the sample mean is within 95% confidence interval of population mean The Alternative (Ha) assumes that the batsman is out of form the sample mean is beyond the 95% confidence interval of the population mean.

A significance value of 0.05 is chosen and p-value us computed If p-value >= .05 – Batsman In-Form If p-value < 0.05 – Batsman Out-of-Form

Note Ideally the p-value should be done for a population that follows the Normal Distribution. But the runs population is usually left skewed. So some correction may be needed. I will revisit this later

This is done for the Top 4 batsman

checkBatsmanInForm("stevesmith.csv","S Smith")
## [1] "**************************** Form status of S Smith ****************************\n\n Population size: 144  Mean of population: 53.76 \n Sample size: 17  Mean of sample: 45.65 SD of sample: 56.4 \n\n Null hypothesis H0 : S Smith 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : S Smith 's sample average is below the 95% confidence interval of population average\n\n S Smith 's Form Status: In-Form because the p value: 0.280533  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBatsmanInForm("warner.csv","Warner")
## [1] "**************************** Form status of Warner ****************************\n\n Population size: 164  Mean of population: 45.2 \n Sample size: 19  Mean of sample: 26.63 SD of sample: 44.62 \n\n Null hypothesis H0 : Warner 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : Warner 's sample average is below the 95% confidence interval of population average\n\n Warner 's Form Status: Out-of-Form because the p value: 0.042744  is less than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBatsmanInForm("labuschagne.csv","M Labuschagne")
## [1] "**************************** Form status of M Labuschagne ****************************\n\n Population size: 52  Mean of population: 59.56 \n Sample size: 6  Mean of sample: 29.67 SD of sample: 19.96 \n\n Null hypothesis H0 : M Labuschagne 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : M Labuschagne 's sample average is below the 95% confidence interval of population average\n\n M Labuschagne 's Form Status: Out-of-Form because the p value: 0.005239  is less than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBatsmanInForm("khwaja.csv","Khwaja")
## [1] "**************************** Form status of Khwaja ****************************\n\n Population size: 89  Mean of population: 41.62 \n Sample size: 10  Mean of sample: 53.1 SD of sample: 76.34 \n\n Null hypothesis H0 : Khwaja 's sample average is within 95% confidence interval of population average\n Alternative hypothesis Ha : Khwaja 's sample average is below the 95% confidence interval of population average\n\n Khwaja 's Form Status: In-Form because the p value: 0.677691  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"

5r. Predicting Runs given Balls Faced and Minutes at Crease

A multi-variate regression plane is fitted between Runs and Balls faced +Minutes at crease.

BF <- seq( 10, 400,length=15)
Mins <- seq(30,600,length=15)
newDF <- data.frame(BF,Mins)
ssmith1 <- batsmanRunsPredict("stevesmith.csv","S Smith",newdataframe=newDF)
warner1 <- batsmanRunsPredict("warner.csv","Warner",newdataframe=newDF)
khwaja1 <- batsmanRunsPredict("khwaja.csv","Khwaja",newdataframe=newDF)
labuschagne1 <- batsmanRunsPredict("labuschagne.csv","Labuschagne",newdataframe=newDF)
cgreen1 <- batsmanRunsPredict("cgreen.csv","C Green",newdataframe=newDF)
batsmen <-cbind(round(ssmith1$Runs),round(warner1$Runs),round(khwaja1$Runs),round(labuschagne1$Runs),round(cgreen1$Runs))
colnames(batsmen) <- c("S Smith","Warner","Khwaja","Labuschagne","C Green")
newDF <- data.frame(round(newDF$BF),round(newDF$Mins))
colnames(newDF) <- c("BallsFaced","MinsAtCrease")
predictedRuns <- cbind(newDF,batsmen)
predictedRuns
##    BallsFaced MinsAtCrease S Smith Warner Khwaja Labuschagne C Green
## 1          10           30       7     10     10           9      13
## 2          38           71      23     30     24          24      29
## 3          66          111      38     50     38          40      44
## 4          94          152      53     70     53          55      60
## 5         121          193      69     90     67          70      75
## 6         149          234      84    110     81          85      91
## 7         177          274     100    130     95         100     106
## 8         205          315     115    150    109         116     122
## 9         233          356     130    170    123         131     137
## 10        261          396     146    190    137         146     153
## 11        289          437     161    210    151         161     168
## 12        316          478     177    230    165         176     184
## 13        344          519     192    250    179         192     199
## 14        372          559     207    270    193         207     215
## 15        400          600     223    290    207         222     230

6. Analysis of Australia WTC batsmen from Jan 2016 – May 2023 against India

6a. Relative cumulative average runs in career

Labuschagne, Smith and C Green have good records against India

frames <- list("stevesmithTestInd.csv","warnerTestInd.csv","khwajaTestInd.csv","labuschagneTestInd.csv","cgreenTestInd.csv")
names <- list("S Smith","Warner","Khwaja","Labuschagne","C Green")
relativeBatsmanCumulativeAvgRuns(frames,names)

6b. Relative cumulative average strike rate in career

Warner, Labuschagne and Smith have a good strike rate against India

frames <- list("stevesmithTestInd.csv","warnerTestInd.csv","khwajaTestInd.csv","labuschagneTestInd.csv","cgreenTestInd.csv")
names <- list("S Smith","Warner","Khwaja","Labuschagne","C Green")
relativeBatsmanCumulativeStrikeRate(frames,names)

7. Analysis of India WTC bowlers from Jan 2016 – May 2023

7a Wickets frequency chart

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))
bowlerWktsFreqPercent("shamiTest.csv","Shami")
bowlerWktsFreqPercent("sirajTest.csv","Siraj")
bowlerWktsFreqPercent("ashwinTest.csv","Ashwin")
bowlerWktsFreqPercent("jadejaTest.csv","Jadeja")
bowlerWktsFreqPercent("shardulTest.csv","Shardul")

7b Wickets Runs chart

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerWktsRunsPlot("shamiTest.csv","Shami")
bowlerWktsRunsPlot("sirajTest.csv","Siraj")
bowlerWktsRunsPlot("ashwinTest.csv","Ashwin")
bowlerWktsRunsPlot("jadejaTest.csv","Jadeja")
bowlerWktsRunsPlot("shardulTest.csv","Shardul")

7c. Average wickets at different venues

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerAvgWktsGround("shamiTest.csv","Shami")
bowlerAvgWktsGround("sirajTest.csv","Siraj")
bowlerAvgWktsGround("ashwinTest.csv","Ashwin")
bowlerAvgWktsGround("jadejaTest.csv","Jadeja")
bowlerAvgWktsGround("shardulTest.csv","Shardul")

7d Average wickets against different opposition

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerAvgWktsOpposition("shamiTest.csv","Shami")
bowlerAvgWktsOpposition("sirajTest.csv","Siraj")
bowlerAvgWktsOpposition("ashwinTest.csv","Ashwin")
bowlerAvgWktsOpposition("jadejaTest.csv","Jadeja")
bowlerAvgWktsOpposition("shardulTest.csv","Shardul")

7e Cumulative average wickets taken

Ashwin’s performance has dropped over the years, while Siraj has been becoming better

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

bowlerCumulativeAvgWickets("shamiTest.csv","Shami")
bowlerCumulativeAvgWickets("sirajTest.csv","Siraj")
bowlerCumulativeAvgWickets("ashwinTest.csv","Ashwin")
bowlerCumulativeAvgWickets("jadejaTest.csv","Jadeja")
bowlerCumulativeAvgWickets("shardulTest.csv","Shardul")

7g Cumulative average economy rate

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerCumulativeAvgEconRate("shamiTest.csv","Shami")
bowlerCumulativeAvgEconRate("sirajTest.csv","Siraj")
bowlerCumulativeAvgEconRate("ashwinTest.csv","Ashwin")
bowlerCumulativeAvgEconRate("jadejaTest.csv","Jadeja")
bowlerCumulativeAvgEconRate("shardulTest.csv","Shardul")

7h Wicket forecast

Here are plots that forecast how the bowler will perform in future. In this case 90% of the career wickets trend is used as the training set. the remaining 10% is the test set.

A Holt-Winters forecasting model is used to forecast future performance based on the 90% training set. The forecasted wickets trend is plotted. The test set is also plotted to see how close the forecast and the actual matches

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerPerfForecast("shamiTest.csv","Shami")
#bowlerPerfForecast("sirajTest.csv","Siraj")
bowlerPerfForecast("ashwinTest.csv","Ashwin")
bowlerPerfForecast("jadejaTest.csv","Jadeja")
bowlerPerfForecast("shardulTest.csv","Shardul")

7i Relative Wickets Frequency Percentage

frames <- list("shamiTest.csv","sirajTest.csv","ashwinTest.csv","jadejaTest.csv","shardulTest.csv")
names <- list("Shami","Siraj","Ashwin","Jadeja","Shardul")
relativeBowlingPerf(frames,names)

7j Relative Economy Rate against wickets taken

frames <- list("shamiTest.csv","sirajTest.csv","ashwinTest.csv","jadejaTest.csv","shardulTest.csv")
names <- list("Shami","Siraj","Ashwin","Jadeja","Shardul")
relativeBowlingER(frames,names)

7k Relative cumulative average wickets of bowlers in career

Ashwin has the highest wickets followed by Jadeja against all teams

frames <- list("shamiTest.csv","sirajTest.csv","ashwinTest.csv","jadejaTest.csv","shardulTest.csv")
names <- list("Shami","Siraj","Ashwin","Jadeja","Shardul")
relativeBowlerCumulativeAvgWickets(frames,names)

7l Relative cumulative average economy rate of bowlers

Jadeja has the best economy rate followed by Ashwin

frames <- list("shamiTest.csv","sirajTest.csv","ashwinTest.csv","jadejaTest.csv","shardulTest.csv")
names <- list("Shami","Siraj","Ashwin","Jadeja","Shardul")
relativeBowlerCumulativeAvgEconRate(frames,names)

7m Check for bowler in-form/out-of-form

The below computation uses Null Hypothesis testing and p-value to determine if the bowler is in-form or out-of-form. For this 90% of the career wickets is chosen as the population and the mean computed. The last 10% is chosen to be the sample set and the sample Mean and the sample Standard Deviation are caculated.

The Null Hypothesis (H0) assumes that the bowler continues to stay in-form where the sample mean is within 95% confidence interval of population mean The Alternative (Ha) assumes that the bowler is out of form the sample mean is beyond the 95% confidence interval of the population mean.

A significance value of 0.05 is chosen and p-value us computed If p-value >= .05 – Batsman In-Form If p-value < 0.05 – Batsman Out-of-Form

Note Ideally the p-value should be done for a population that follows the Normal Distribution. But the runs population is usually left skewed. So some correction may be needed. I will revisit this later

Note: The check for the form status of the bowlers indicate

checkBowlerInForm("shami.csv","Shami")
## [1] "**************************** Form status of Shami ****************************\n\n Population size: 106  Mean of population: 1.93 \n Sample size: 12  Mean of sample: 1.33 SD of sample: 1.23 \n\n Null hypothesis H0 : Shami 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : Shami 's sample average is below the 95% confidence\n        interval of population average\n\n Shami 's Form Status: In-Form because the p value: 0.058427  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBowlerInForm("siraj.csv","Siraj")
## [1] "**************************** Form status of Siraj ****************************\n\n Population size: 29  Mean of population: 1.59 \n Sample size: 4  Mean of sample: 0.25 SD of sample: 0.5 \n\n Null hypothesis H0 : Siraj 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : Siraj 's sample average is below the 95% confidence\n        interval of population average\n\n Siraj 's Form Status: Out-of-Form because the p value: 0.002923  is less than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBowlerInForm("ashwin.csv","Ashwin")
## [1] "**************************** Form status of Ashwin ****************************\n\n Population size: 154  Mean of population: 2.77 \n Sample size: 18  Mean of sample: 2.44 SD of sample: 1.76 \n\n Null hypothesis H0 : Ashwin 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : Ashwin 's sample average is below the 95% confidence\n        interval of population average\n\n Ashwin 's Form Status: In-Form because the p value: 0.218345  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBowlerInForm("jadeja.csv","Jadeja")
## [1] "**************************** Form status of Jadeja ****************************\n\n Population size: 108  Mean of population: 2.22 \n Sample size: 12  Mean of sample: 1.92 SD of sample: 2.35 \n\n Null hypothesis H0 : Jadeja 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : Jadeja 's sample average is below the 95% confidence\n        interval of population average\n\n Jadeja 's Form Status: In-Form because the p value: 0.333095  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBowlerInForm("shardul.csv","Shardul")
## [1] "**************************** Form status of Shardul ****************************\n\n Population size: 13  Mean of population: 2 \n Sample size: 2  Mean of sample: 0.5 SD of sample: 0.71 \n\n Null hypothesis H0 : Shardul 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : Shardul 's sample average is below the 95% confidence\n        interval of population average\n\n Shardul 's Form Status: Out-of-Form because the p value: 0.04807  is less than alpha=  0.05 \n *******************************************************************************************\n\n"

8. Analysis of India WTC bowlers from Jan 2016 – May 2023 against Australia

8a Relative cumulative average wickets of bowlers in career

Against Australia specifically Jadeja has the best record followed by Ashwin

frames <- list("shamiTestAus.csv","sirajTestAus.csv","ashwinTestAus.csv","jadejaTestAus.csv","shardulTestAus.csv")
names <- list("Shami","Siraj","Ashwin","Jadeja","Shardul")
relativeBowlerCumulativeAvgWickets(frames,names)

8b Relative cumulative average economy rate of bowlers

Jadeja has the best economy followed by Siraj, then Ashwin

frames <- list("shamiTestAus.csv","sirajTestAus.csv","ashwinTestAus.csv","jadejaTestAus.csv","shardulTestAus.csv")
names <- list("Shami","Siraj","Ashwin","Jadeja","Shardul")
relativeBowlerCumulativeAvgEconRate(frames,names)

8. Analysis of India WTC bowlers from Jan 2016 – May 2023

8a. Wickets frequency chart

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))
bowlerWktsFreqPercent("cumminsTest.csv","Cummins")
bowlerWktsFreqPercent("starcTest.csv","Starc")
bowlerWktsFreqPercent("hazzlewoodTest.csv","Hazzlewood")
bowlerWktsFreqPercent("todd.csv","Todd")
bowlerWktsFreqPercent("lyonTest.csv","N Lyon")

 8b. Wickets frequency chart

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerWktsRunsPlot("cumminsTest.csv","Cummins")
bowlerWktsRunsPlot("starcTest.csv","Starc")
bowlerWktsRunsPlot("hazzlewoodTest.csv","Hazzlewood")
bowlerWktsRunsPlot("todd.csv","Todd")
bowlerWktsRunsPlot("lyonTest.csv","N Lyon")

8c. Average wickets at different venues

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerAvgWktsGround("cumminsTest.csv","Cummins")
bowlerAvgWktsGround("starcTest.csv","Starc")
bowlerAvgWktsGround("hazzlewoodTest.csv","Hazzlewood")
bowlerAvgWktsGround("todd.csv","Todd")
bowlerAvgWktsGround("lyonTest.csv","N Lyon")

8d Average wickets against different opposition

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerAvgWktsOpposition("cumminsTest.csv","Cummins")
bowlerAvgWktsOpposition("starcTest.csv","Starc")
bowlerAvgWktsOpposition("hazzlewoodTest.csv","Hazzlewood")
bowlerAvgWktsOpposition("todd.csv","Todd")
bowlerAvgWktsOpposition("lyonTest.csv","N Lyon")

8e Cumulative average wickets taken

par(mfrow=c(2,2))
par(mar=c(4,4,2,2))

bowlerCumulativeAvgWickets("cumminsTest.csv","Cummins")
bowlerCumulativeAvgWickets("starcTest.csv","Starc")
bowlerCumulativeAvgWickets("hazzlewoodTest.csv","Hazzlewood")
bowlerCumulativeAvgWickets("todd.csv","Todd")
bowlerCumulativeAvgWickets("lyonTest.csv","N Lyon")

8g Cumulative average economy rate

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerCumulativeAvgEconRate("cumminsTest.csv","Cummins")
bowlerCumulativeAvgEconRate("starcTest.csv","Starc")
bowlerCumulativeAvgEconRate("hazzlewoodTest.csv","Hazzlewood")
bowlerCumulativeAvgEconRate("todd.csv","Todd")
bowlerCumulativeAvgEconRate("lyonTest.csv","N Lyon")

8f. Future Wickets forecast

Here are plots that forecast how the bowler will perform in future. In this case 90% of the career wickets trend is used as the training set. the remaining 10% is the test set.

A Holt-Winters forecasting model is used to forecast future performance based on the 90% training set. The forecated wickets trend is plotted. The test set is also plotted to see how close the forecast and the actual matches

par(mfrow=c(2,3))
par(mar=c(4,4,2,2))

bowlerPerfForecast("cumminsTest.csv","Cummins")
bowlerPerfForecast("starcTest.csv","Starc")
bowlerPerfForecast("hazzlewoodTest.csv","Hazzlewood")
bowlerPerfForecast("lyonTest.csv","N Lyon")

8i. Relative Wickets Frequency Percentage

frames <- list("cumminsTest.csv","starcTest.csv","hazzlewoodTest.csv","todd.csv","lyonTest.csv")
names <- list("Cummins","Starc","Hazzlewood","Todd","N Lyon")
relativeBowlingPerf(frames,names)

8j Relative Economy Rate against wickets taken

frames <- list("cumminsTest.csv","starcTest.csv","hazzlewoodTest.csv","todd.csv","lyonTest.csv")
names <- list("Cummins","Starc","Hazzlewood","Todd","N Lyon")
relativeBowlingER(frames,names)

8k Relative cumulative average wickets of bowlers in career

Cummins, Starc and Lyons are the best performers

frames <- list("cumminsTest.csv","starcTest.csv","hazzlewoodTest.csv","todd.csv","lyonTest.csv")
names <- list("Cummins","Starc","Hazzlewood","Todd","N Lyon")
relativeBowlerCumulativeAvgWickets(frames,names)

8l Relative cumulative average economy rate of bowlers

Hazzlewood, Cummins have the best economy against all oppostion

frames <- list("cumminsTest.csv","starcTest.csv","hazzlewoodTest.csv","todd.csv","lyonTest.csv")
names <- list("Cummins","Starc","Hazzlewood","Todd","N Lyon")
relativeBowlerCumulativeAvgEconRate(frames,names)

8o Check for bowler in-form/out-of-form

The below computation uses Null Hypothesis testing and p-value to determine if the bowler is in-form or out-of-form. For this 90% of the career wickets is chosen as the population and the mean computed. The last 10% is chosen to be the sample set and the sample Mean and the sample Standard Deviation are calculated.

The Null Hypothesis (H0) assumes that the bowler continues to stay in-form where the sample mean is within 95% confidence interval of population mean The Alternative (Ha) assumes that the bowler is out of form the sample mean is beyond the 95% confidence interval of the population mean.

A significance value of 0.05 is chosen and p-value us computed If p-value >= .05 – Batsman In-Form If p-value < 0.05 – Batsman Out-of-Form

Note Ideally the p-value should be done for a population that follows the Normal Distribution. But the runs population is usually left skewed. So some correction may be needed. I will revisit this later

Note: The check for the form status of the bowlers indicate

checkBowlerInForm("cummins.csv","Cummins")
## [1] "**************************** Form status of Cummins ****************************\n\n Population size: 81  Mean of population: 2.46 \n Sample size: 9  Mean of sample: 2 SD of sample: 1.5 \n\n Null hypothesis H0 : Cummins 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : Cummins 's sample average is below the 95% confidence\n        interval of population average\n\n Cummins 's Form Status: In-Form because the p value: 0.190785  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBowlerInForm("starc.csv","Starc")
## [1] "**************************** Form status of Starc ****************************\n\n Population size: 126  Mean of population: 2.18 \n Sample size: 15  Mean of sample: 1.67 SD of sample: 1.18 \n\n Null hypothesis H0 : Starc 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : Starc 's sample average is below the 95% confidence\n        interval of population average\n\n Starc 's Form Status: In-Form because the p value: 0.057433  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBowlerInForm("hazzlewood.csv","Hazzlewood")
## [1] "**************************** Form status of Hazzlewood ****************************\n\n Population size: 99  Mean of population: 2.04 \n Sample size: 12  Mean of sample: 1.67 SD of sample: 1.5 \n\n Null hypothesis H0 : Hazzlewood 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : Hazzlewood 's sample average is below the 95% confidence\n        interval of population average\n\n Hazzlewood 's Form Status: In-Form because the p value: 0.204787  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"
checkBowlerInForm("lyon.csv","N Lyon")
## [1] "**************************** Form status of N Lyon ****************************\n\n Population size: 193  Mean of population: 2.08 \n Sample size: 22  Mean of sample: 2.95 SD of sample: 1.96 \n\n Null hypothesis H0 : N Lyon 's sample average is within 95% confidence interval \n        of population average\n Alternative hypothesis Ha : N Lyon 's sample average is below the 95% confidence\n        interval of population average\n\n N Lyon 's Form Status: In-Form because the p value: 0.975407  is greater than alpha=  0.05 \n *******************************************************************************************\n\n"

9. Analysis of Australia WTC bowlers from Jan 2016 – May 2023 against India

9a Relative cumulative average wickets of bowlers in career

Against India Lyon, Cummins and Hazzlewood have performed well

frames <- list("cumminsTestInd.csv","starcTestInd.csv","hazzlewoodTestInd.csv","lyonTestInd.csv")
names <- list("Cummins","Starc","Hazzlewood","N Lyon")
relativeBowlerCumulativeAvgWickets(frames,names)

9b Relative cumulative average economy rate of bowlers

Hazzlewood, Lyon have a good economy rate against India

frames <- list("cumminsTestInd.csv","starcTestInd.csv","hazzlewoodTestInd.csv","lyonTestInd.csv")
names <- list("Cummins","Starc","Hazzlewood","N Lyon")
relativeBowlerCumulativeAvgEconRate(frames,names)

10 Analysis of teams – India, Australia

#The data for India & Australia teams were obtained with the following calls

#indiaTest <-getTeamDataHomeAway(dir=".",teamView="bat",matchType="Test",file="indiaTest.csv",save=TRUE,teamName="India")
#australiaTest <- getTeamDataHomeAway(matchType="Test",file="australiaTest.csv",save=TRUE,teamName="Australia")

10a. Win-loss of India against all oppositions in Test cricket

Against Australia India has won 17 times, lost 60 and drawn 22 in Australia. At home India won 42, tied 2, lost 28 and drawn 24

teamWinLossStatusVsOpposition("indiaTest.csv",teamName="India",opposition=c("all"),homeOrAway=c("all"),matchType="Test",plot=TRUE)

10b. Win-loss of Australia against all oppositions in Test cricket

teamWinLossStatusVsOpposition("australiaTest.csv",teamName="Australia",opposition=c("all"),homeOrAway=c("all"),matchType="Test",plot=TRUE)

10c. Win-loss of India against Australia in Test cricket

Against Australia India has won 17 times, lost 60 and drawn 22 in Australia. At home India won 42, tied 2, lost 28 and drawn 24

teamWinLossStatusVsOpposition("indiaTest.csv",teamName="India",opposition=c("Australia"),homeOrAway=c("all"),matchType="Test",plot=TRUE)

10d. Win-loss of India at all away venues

At the Oval where WTC is going to be held India has won 4, lost 10 and drawn 10.

teamWinLossStatusAtGrounds("indiaTest.csv",teamName="India",opposition=c("all"),homeOrAway=c("away"),matchType="Test",plot=TRUE)

10d. Timeline of win-loss of India against Australia in Test cricket

plotTimelineofWinsLosses("indiaTest.csv",team="India",opposition=c("Australia"),
                         homeOrAway=c("away","neutral"), startDate="2016-01-01",endDate="2023-05-01")

11. Conclusion

The above analysis performs various analysis of India and Australia in home and away matches. While we know the performance of the player at India or Australia, we cannot judge how the match will progress in the neutral, swinging conditions of the Oval. Let us hope for a good match!

Feel free to try out your own analysis with cricketr. Have fun with cricketr!!

Also see

  1. GooglyPlusPlus: Win Probability using Deep Learning and player embeddings
  2. The common alphabet of programming languages
  3. Practical Machine Learning with R and Python – Part 5
  4. Deep Learning from first principles in Python, R and Octave – Part 4
  5. Big Data-4: Webserver log analysis with RDDs, Pyspark, SparkR and SparklyR
  6. Cricpy takes guard for the Twenty20s
  7. Using Reinforcement Learning to solve Gridworld
  8. Exploring Quantum Gate operations with QCSimulator

To see all posts click Index of posts

IPL 2023:GooglyPlusPlus now with by AI/ML models, near real-time analytics!

It is carnival time again as IPL 2023 is underway!! The new GooglyPlusPlus now includes AI/ML models for computing ball-by-ball Win Probability of matches and each individual player’s Win Probability Contribution (WPC). GooglyPlusPlus uses 2 ML models

  • Deep Learning (Tensorflow) – accuracy : 0.8584
  • Logistic Regression (glmnet-tidymodels) : 0.728

Besides, as before, GooglyPlusPlus will also include the usual near real-time analytics with the Shiny app being automatically updated with the previous day’s match data.

Note: The Win Probability Computation can also be done on a live feed of streaming data. Since, I don’t have access to live feeds, the app will show how Win Probability changed during the course of completed matches. For more details on Win Probability and Win Probability Contribution see my posts

GooglyPlusPlus has been also updated with all the latest T20 league’s match data. It includes data from BBL 2022, NTB 2022, CPL 2022, PSL 2023, ICC T20 2022 and now IPL 2023.

GooglyPlusPlus has the following functionality

  • Batsman tab: For detailed analysis of batsmen
  • Bowler tab: For detailed analysis of bowlers
  • Match tab: Analysis of individual matches, plot of Runs vs SR, Wickets vs ER in power play, middle and death overs, Win Probability Analysis of teams and Win Probability Contribution of players
  • Head-to-head tab: Detailed analysis of team-vs-team batting/bowling scorecard, batting, bowling performances, performances in power play, middle and death overs
  • Team performance tab: Analysis of team-vs-all other teams with batting /bowling scorecard, batting, bowling performances, performances in power play, middle and death overs
  • Optimisation tab: Allows one to pit batsmen vs bowlers and vice-versa. This tab also uses integer programming to optimise batting and bowling lineup
  • Batting analysis tab: Ranks batsmen using Runs or SR. Also plots performances of batsmen in power play, middle and death overs and plots them in a 4×4 grid
  • Bowling analysis tab: Ranks bowlers based on Wickets or ER. Also plots performances of bowlers in power play, middle and death overs and plots them in a 4×4 grid

Also note all these tabs and features are available for all T20 formats namely IPL, Intl. T20 (men, women), BBL, NTB, PSL, CPL, SSM.

Important note: It is possible, that at times, the Win Probability (Deep Learning) for some recent IPL matches will give an error. This is because I need to rebuild the models on a daily basis as the matches use player embeddings and there are new players. While I will definitely rebuild the models on weekends and whenever I find time, you may have to bear with this error occasionally.

Note: All charts are interactive, which means that you can hover, zoom-in, zoom-out, pan etc on the charts

The latest avatar of GooglyPlusPlus2023 is based on my R package yorkr with data from Cricsheet.

Check out the latest version of GooglyPlusPlus

Follow me on twitter for daily highlights @tvganesh_85

GooglyPlusPlus can analyse players, matches, teams, rank, compute win probability and much more.

Included below are some random analyses of IPL 2023 matches so far

A) Chennai Super Kings vs Gujarat Titans – 31 Mar 2023

GT won by 5 wickets ( 4 balls remaining)

a) Worm Wicket Chart

b) Ball-by-ball Win Probability (Logistic Regression) (side-by-side)

This model shows that CSK had the upper hand in the 2nd last over, before it changed to GT. More details on Win Probability and Win Probability Contribution in the posts given by the links above.

c) b) Ball-by-ball Win Probability (Logistic Regression) (overlapping)

Here the ball-by-ball win probability is overlapped. CSK and GT both had nearly the same probability of winning in the 2nd last over before GT edges CSK out

B) Punjab Kings vs Rajasthan Royals – 05 Apr 2023

This was a another closely fought match. PBKS won by 5 runs

a) Worm wicket chart

b) Batting partnerships

Shikhar Dhawan scored 86 runs

c) Ball-by-ball Win Probability using Deep Learning (overlapping)

PBKS was generally ahead in the win probability race

d) Batsman Win Probability Contribution

This plot shows how the different batsmen contributed to the Win Probability. We can see that Shikhar Dhawan has a highest win probability. He played a very sensible innings. Also it appears that there is no difference between Prabhsimran Singh and others, though he score 60 runs. This computation is based on when they come to bat and how the win probability changes when they get dismissed, as seen in the 2nd chart

C) Delhi Capitals vs Gujarat Titans – 4 Apr 2023

GT won by 6 wickets (11 balls remaining)

a) Worm wicket chart

b) Runs scored across 20 overs

c) Runs vs SR plot

d) Batting scorecard (Gujarat Titans)

e) Batsman Win Probability Contribution (Gujarat Titans)

Miller has a higher percentage in the Win Contribution than Sai Sudershan who held the innings together.Strange are the ways of the ML models!!

D) Sunrisers Hyderabad vs Lucknow Supergiants ( 7 Apr 2023)

LSG won by 5 wickets (24 balls left). SRH were bamboozled by the pitch while LSG was able to cruise along

a) Worm wicket chart

b) Wickets vs ER plot

c) Wickets across 20 overs

d) Ball-by-ball win probability using Deep Learning (overlapping)

e) Bowler Win Probability Contribution (LSG)

Bishnoi has a higher win probability contribution than Krunal, though he just took 1 wicket to Krunal’s 3 wickets. This is based on how the Win Probability changed at that point in the game.

The above set of plots are just a random sample.

Note: There are 8 tabs each for 9 T20 leagues (BBL, CPL, T20 (men), T20 (women), IPL, PSL, NTB, SSM, WBB). So there are a lot more detailed charts/analses.

Do take GooglyPlusPlus for a test drive!!!

Follow me on twitter @tvganesh_85 for daily highlights of previous day matches

Take a look at some of my other posts

  1. Using Reinforcement Learning to solve Gridworld
  2. Deep Learning from first principles in Python, R and Octave – Part 6
  3. Big Data-4: Webserver log analysis with RDDs, Pyspark, SparkR and SparklyR
  4. Experiments with deblurring using OpenCV
  5. Singularity
  6. Practical Machine Learning with R and Python – Part 6
  7. Pitching yorkpy … short of good length to IPL – Part 1
  8. Analyzing performances of cricketers using cricketr template
  9. Cricpy takes guard for the Twenty20s
  10. Simulating an Edge Shape in Android

To see all posts click Index of posts

Boosting Win Probability accuracy with player embeddings

In my previous post Computing Win Probability of T20 matches I had discussed various approaches on computing Win Probability of T20 matches. I had created ML models with glmnet and random forest using TidyModels. This was what I had achieved

  • glmnet : accuracy – 0.67 and sensitivity/specificity – 0.68/0.65
  • random forest : accuracy – 0.737 and roc_auc- 0.834
  • DL model with Keras in Python : accuracy – 0.73

I wanted to see if the performance of the models could be further improved. I got a suggestion from a AI/DL whizkid, who is close to me, to include embeddings for batsmen and bowlers. He felt that win percentage is influenced by which batsman faces which bowler.

So, I started to explore this idea. Embeddings can be used to convert categorical variables to a vector of continuous floating point numbers.Fortunately R’s Tidymodels, has a convenient functionality to create embeddings. By including embeddings for batsman, bowler the performance of my ML models improved vastly. Now the performance is

  • glmnet : accuracy – 0.728 and roc_auc – 0.81
  • random forest : accuracy – 0.927 and roc_auc – 0.98
  • mlp-dnn :accuracy – 0.762 and roc_auc – 0.854

As can be seem there is almost a 20% increase in accuracy with random forests with embeddings over the model without embeddings. Moreover, the feature importance which is plotted below shows that the bowler and batsman embeddings have a significant influence on the Win Probability

Note: The data for this analysis is taken from Cricsheet and has been processed with my R package yorkr.

A. Win Probability using GLM with penalty and player embeddings

Here Generalised Linear Model (GLMNET) for Logistic Regression is used. In the GLMNET the regularisation path is computed for the lasso or elastic net penalty at a grid of values for the regularisation parameter lambda. glmnet is extremely fast and gave an accuracy of 0.72 for an roc_auc of 0.81 with batsman, bowler embeddings. This was good improvement over my earlier implementation with glmnet without the batsman & bowler embeddings which had a

  1. Read the data

a) Read the data from 9 T20 leagues (BBL, CPL, IPL, NTB, PSL, SSM, T20 Men, T20 Women, WBB) and create a single data frame of ball-by-ball data. Display the data frame

library(dplyr)
library(caret)
library(e1071)
library(ggplot2)
library(tidymodels)  
library(embed)

# Helper packages
library(readr)       # for importing data
library(vip) 

df1=read.csv("output3/matchesBBL3.csv")
df2=read.csv("output3/matchesCPL3.csv")
df3=read.csv("output3/matchesIPL3.csv")
df4=read.csv("output3/matchesNTB3.csv")
df5=read.csv("output3/matchesPSL3.csv")
df6=read.csv("output3/matchesSSM3.csv")
df7=read.csv("output3/matchesT20M3.csv")
df8=read.csv("output3/matchesT20W3.csv")
df9=read.csv("output3/matchesWBB3.csv")

#Bind all dataframes together
df=rbind(df1,df2,df3,df4,df5,df6,df7,df8,df9)
glimpse(df)
Rows: 1,199,115
Columns: 10
$ batsman        <chr> "JD Smith", "M Klinger", "M Klinger", "M Klinger", "JD …
$ bowler         <chr> "NM Hauritz", "NM Hauritz", "NM Hauritz", "NM Hauritz",…

$ ballNum        <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, …
$ ballsRemaining <int> 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, …
$ runs           <int> 1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 13, 14, 16, 18, 18,…

$ runRate        <dbl> 1.0000000, 0.5000000, 0.6666667, 0.7500000, 0.6000000, …
$ numWickets     <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
$ runsMomentum   <dbl> 0.08800000, 0.08870968, 0.08943089, 0.09016393, 0.09090…
$ perfIndex      <dbl> 11.000000, 5.500000, 7.333333, 8.250000, 6.600000, 5.50…
$ isWinner       <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…


df %>% 
  count(isWinner) %>% 
  mutate(prop = n/sum(n))
  isWinner      n      prop
1        
0 614237 0.5122419
2        
1 584878 0.4877581

2) Create training.validation and test sets

b) Split to training, validation and test sets. The dataset is initially split into training and test in the ratio 80%:20%. The training data is again split into training and validation in the ratio 80:20

set.seed(123)
splits      <- initial_split(df,prop = 0.80)
splits
<Training/Testing/Total>
<959292/239823/1199115>
df_other <- training(splits)
df_test  <- testing(splits)

set.seed(234)
val_set <- validation_split(df_other,prop = 0.80)
val_set
# A tibble: 1 × 2
  splits                  
id        
  <list>                  <chr>     
1 <split [767433/191859]> validation

3) Create pre-processing recipe

a) Normalise the following predictors

  • ballNum
  • ballsRemaining
  • runs
  • runRate
  • numWickets
  • runsMomentum
  • perfIndex

b) Create floating point embeddings for

  • batsman
  • bowler

4) Create a Logistic Regression Workflow by adding the GLM model and the recipe

5) Create grid of elastic penalty values for regularisation

6) Train all 30 models

7) Plot the ROC of the model against the penalty

# Use all 12 cores
cores <- parallel::detectCores()
cores
# Create a Logistic Regression model with penalty
lr_mod <- 
  logistic_reg(penalty = tune(), mixture = 1) %>% 
  set_engine("glmnet",num.threads = cores)

# Create pre-processing recipe
lr_recipe <- 
  recipe(isWinner ~ ., data = df_other) %>%
  step_embed(batsman,bowler, outcome = vars(isWinner)) %>%  step_normalize(ballNum,ballsRemaining,runs,runRate,numWickets,runsMomentum,perfIndex) 

# Set the workflow by adding the GLM model with the recipe
lr_workflow <- 
  workflow() %>% 
  add_model(lr_mod) %>% 
  add_recipe(lr_recipe)

# Create a grid for the elastic net penalty
lr_reg_grid <- tibble(penalty = 10^seq(-4, -1, length.out = 30))
lr_reg_grid %>% top_n(-5) 
# A tibble: 5 × 1
   penalty
     
<dbl>
1 0.0001  
2 0.000127
3 0.000161
4 0.000204
5 0.000259

lr_reg_grid %>% top_n(5)  # highest penalty values
# A tibble: 5 × 1
  penalty
    <dbl>
1  0.0386
2  0.0489
3  0.0621
4  0.0788
5  0.1

# Train 30 penalized models
lr_res <- 
  lr_workflow %>% 
  tune_grid(val_set,
            grid = lr_reg_grid,
            control = control_grid(save_pred = TRUE),
            metrics = metric_set(accuracy,roc_auc))

# Plot the penalty versus ROC
lr_plot <- 
  lr_res %>% 
  collect_metrics() %>% 
  ggplot(aes(x = penalty, y = mean)) + 
  geom_point() + 
  geom_line() + 
  ylab("Area under the ROC Curve") +
  scale_x_log10(labels = scales::label_number())

lr_plot

The Penalty vs ROC plot is shown below

8) Display the ROC_AUC of the top models with the penalty

9) Select the model with the best ROC_AUC and the associated penalty. It can be seen the best mean ROC_AUC is 0.81 and the associated penalty is 0.000530

top_models <-
  lr_res %>% 
  show_best("roc_auc", n = 15) %>% 
  arrange(penalty) 
top_models

# A tibble: 15 × 7
    penalty .metric .estimator  mean     n std_err .config              
      <dbl> <chr>   <chr>      <dbl> <int>   <dbl> <chr>                
 1 0.0001   roc_auc binary     0.810     1      NA Preprocessor1_Model01
 2 0.000127 roc_auc binary     0.810     1      NA Preprocessor1_Model02
 3 0.000161 roc_auc binary     0.810     1      NA Preprocessor1_Model03
 4 0.000204 roc_auc binary     0.810     1      NA Preprocessor1_Model04
 5 0.000259 roc_auc binary     0.810     1      NA Preprocessor1_Model05
 6 0.000329 roc_auc binary     0.810     1      NA Preprocessor1_Model06
 7 0.000418 roc_auc binary     0.810     1      NA Preprocessor1_Model07
 8 0.000530 roc_auc binary     0.810     1      NA Preprocessor1_Model08
 9 0.000672 roc_auc binary     0.810     1      NA Preprocessor1_Model09
10 0.000853 roc_auc binary     0.810     1      NA Preprocessor1_Model10
11 0.00108  roc_auc binary     0.810     1      NA Preprocessor1_Model11
12 0.00137  roc_auc binary     0.810     1      NA Preprocessor1_Model12
13 0.00174  roc_auc binary     0.809     1      NA Preprocessor1_Model13
14 0.00221  roc_auc binary     0.809     1      NA Preprocessor1_Model14
15 0.00281  roc_auc binary     0.809     1      NA Preprocessor1_Model15

#Picking the best model and the corresponding penalty
lr_best <- 
  lr_res %>% 
  collect_metrics() %>% 
  arrange(penalty) %>% 
  slice(8)
lr_best
# A tibble: 1 × 7
   
   penalty .metric .estimator  mean     n std_err .config              
     <dbl> <chr>   <chr>      <dbl> <int>   <dbl> <chr>                

1 0.000530 roc_auc binary     0.810     1      NA Preprocessor1_Model08

# Collect predictions and generate the AUC curve
lr_auc <- 
  lr_res %>% 
  collect_predictions(parameters = lr_best) %>% 
  roc_curve(isWinner, .pred_0) %>% 
  mutate(model = "Logistic Regression")

autoplot(lr_auc)

7) Plot the Area under the Curve (AUC).

10) Build the final model with the best LR parameters value as found in lr_best

a) The best performance was for a penalty of 0.000530

b) The accuracy achieved is 0.72. Clearly using the embeddings for batsman, bowlers improves on the performance of the GLM model without the embeddings. The accuracy achieved was 0.72 whereas previously it was 0.67 see (Computing Win Probability of T20 Matches)

c) Create a fit with the best parameters

d) The accuracy is 72.8% and the ROC_AUC is 0.813

# Create a model with the penalty for best ROC_AUC
last_lr_mod <- 
  logistic_reg(penalty = 0.000530, mixture = 1) %>% 
  set_engine("glmnet",num.threads = cores,importance = "impurity")

#Update the workflow with this model
last_lr_workflow <- 
  lr_workflow %>% 
  update_model(last_lr_mod)

#Create a fit
set.seed(345)
last_lr_fit <- 
  last_lr_workflow %>% 
  last_fit(splits)

#Generate accuracy, roc_auc
last_lr_fit %>% 
  collect_metrics()
# A tibble: 2 × 4
  .metric  .estimator .estimate .config             
  
<chr>    <chr>          <dbl> <chr>               
1 accuracy binary         0.728 Preprocessor1_Model1

2 roc_auc  binary         0.813 Preprocessor1_Model1

11) Plot the feature importance

It can be seen that bowler and batsman embeddings are the most significant for the prediction followed by runRate.

runRate –

  • runRate in 1st innings
  • requiredRunRate in 2nd innings

12) Plot the ROC characteristics

last_lr_fit %>% 
  collect_predictions() %>% 
  roc_curve(isWinner, .pred_0) %>% 
  autoplot()

13) Generate a confusion matrix

14) Create a final Generalised Linear Model for Logistic Regression with the penalty of 0.000530

15) Save the model

# generate predictions from the test set
test_predictions <- last_lr_fit %>% collect_predictions()
test_predictions

# generate a confusion matrix
test_predictions %>% 
  conf_mat(truth = isWinner, estimate = .pred_class)

Truth
Prediction     0     1
         
0                  90105 32658
         
1                  32572 84488

final_lr_model <- fit(last_lr_workflow, df_other)

final_lr_model

obj_size(final_lr_model)
146.51 MB


butcher::weigh(final_lr_model)
A tibble: 305 × 2
object                                  size
<chr>                                  <dbl>
  1 pre.actions.recipe.recipe.steps.terms1  57.9
2 pre.actions.recipe.recipe.steps.terms2  57.9
3 pre.actions.recipe.recipe.steps.terms3  57.9


cleaned_lm <- butcher::axe_env(final_lr_model, verbose = TRUE)
#✔ Memory released: "1.04 kB"
#✔ Memory released: "1.62 kB"

saveRDS(cleaned_lm, "cleanedLR.rds")
  

16) Compute Ball-by-ball Win Probability

  • Chennai Super Kings-Lucknow Super Giants-2022-03-31

16a) The corresponding Worm-wicket graph for this match is as below

  • Chennai Super Kings-Lucknow Super Giants-2022-03-31

B) Win Probability using Random Forest with player embeddings

In the 2nd approach I use Random Forest with batsman and bowler embeddings. The performance of the model with embeddings is quantum jump from the earlier performance without embeddings. However, the random forest is also computationally intensive.

1) Read the data

a) Read the data from 9 T20 leagues (BBL, CPL, IPL, NTB, PSL, SSM, T20 Men, T20 Women, WBB) and create a single data frame of ball-by-ball data. Display the data frame

2) Create training.validation and test sets

b) Split to training, validation and test sets. The dataset is initially split into training and test in the ratio 80%:20%. The training data is again split into training and validation in the ratio 80:20

library(dplyr)
library(caret)
library(e1071)
library(ggplot2)
library(tidymodels)  
library(tidymodels)  
library(embed)

# Helper packages
library(readr)       # for importing data
library(vip) 
library(ranger)

# Read all the 9 T20 leagues
df1=read.csv("output3/matchesBBL3.csv")
df2=read.csv("output3/matchesCPL3.csv")
df3=read.csv("output3/matchesIPL3.csv")
df4=read.csv("output3/matchesNTB3.csv")
df5=read.csv("output3/matchesPSL3.csv")
df6=read.csv("output3/matchesSSM3.csv")
df7=read.csv("output3/matchesT20M3.csv")
df8=read.csv("output3/matchesT20W3.csv")
df9=read.csv("output3/matchesWBB3.csv")

# Bind into a single dataframe
df=rbind(df1,df2,df3,df4,df5,df6,df7,df8,df9)

set.seed(123)
df$isWinner = as.factor(df$isWinner)

#Split data into training, validation and test sets
splits      <- initial_split(df,prop = 0.80)
df_other <- training(splits)
df_test  <- testing(splits)
set.seed(234)
val_set <- validation_split(df_other, prop = 0.80)
val_set

2) Create a Random Forest model tuning for number of predictor nodes at each decision node (mtry) and minimum number of predictor nodes (min_n)

3) Use the ranger engine and set up for classification

4) Set up the recipe and include batsman and bowler embeddings

5) Create a workflow and add the recipe and the random forest model with the tuning parameters

# Use all 12 cores parallely
cores <- parallel::detectCores()
cores
[1] 12

# Create the random forest model with mtry and min as tuning parameters
rf_mod <- 
  rand_forest(mtry = tune(), min_n = tune(), trees = 1000) %>% 
  set_engine("ranger", num.threads = cores) %>% 
  set_mode("classification")

# Setup the recipe with batsman and bowler embeddings
rf_recipe <- 
  recipe(isWinner ~ ., data = df_other) %>% 
  step_embed(batsman,bowler, outcome = vars(isWinner)) 

# Create the random forest workflow
rf_workflow <- 
  workflow() %>% 
  add_model(rf_mod) %>% 
  add_recipe(rf_recipe)

rf_mod
# show what will be tuned
extract_parameter_set_dials(rf_mod)

set.seed(345)
# specify which values meant to tune

# Build the model
rf_res <- 
  rf_workflow %>% 
  tune_grid(val_set,
            grid = 10,
            control = control_grid(save_pred = TRUE),
            metrics = metric_set(accuracy,roc_auc))

# Pick the best  roc_auc and the associated tuning parameters
rf_res %>% 
  show_best(metric = "roc_auc")
# A tibble: 5 × 8
   mtry min_n .metric .estimator  mean     n std_err .config              
  <int> <int> <chr>   <chr>      <dbl> <int>   <dbl> <chr>                
1     4     4 roc_auc binary     0.980     1      NA Preprocessor1_Model08
2     9     8 roc_auc binary     0.979     1      NA Preprocessor1_Model03

3     8    16 roc_auc binary     0.974     1      NA Preprocessor1_Model10
4     7    22 roc_auc binary     0.969     1      NA Preprocessor1_Model09

5     5    19 roc_auc binary     0.969     1      NA Preprocessor1_Model06

rf_res %>% 
  show_best(metric = "accuracy")
# A tibble: 5 × 8
   
mtry min_n .metric  .estimator  mean     n std_err .config              
  <int> <int> <chr>    <chr>      <dbl> <int>   <dbl> <chr>                
1  4     4 accuracy binary    0.927     1      NA Preprocessor1_Model08

2  9     8 accuracy binary    0.926     1      NA Preprocessor1_Model03
3  8    16 accuracy binary    0.915     1      NA Preprocessor1_Model10
4  7    22 accuracy binary    0.906     1      NA Preprocessor1_Model09

5  5    19 accuracy binary    0.904     1      NA Preprocessor1_Model0

6) Select all models with the best roc_auc. It can be seen that the best roc_auc is 0.980 for mtry=4 and min_n=4

7) Get the model with the highest accuracy. The highest accuracy achieved is 0.927 or 92.7. This accuracy is also for mtry=4 and min_n=4

# Pick the best  roc_auc and the associated tuning parameters
rf_res %>% 
  show_best(metric = "roc_auc")
# A tibble: 5 × 8
   mtry min_n .metric .estimator  mean     n std_err .config              
  <int> <int> <chr>   <chr>      <dbl> <int>   <dbl> <chr>                
1     4     4 roc_auc binary     0.980     1      NA Preprocessor1_Model08
2     9     8 roc_auc binary     0.979     1      NA Preprocessor1_Model03

3     8    16 roc_auc binary     0.974     1      NA Preprocessor1_Model10
4     7    22 roc_auc binary     0.969     1      NA Preprocessor1_Model09

5     5    19 roc_auc binary     0.969     1      NA Preprocessor1_Model06

# Display the accuracy of the models in descending order and the parameters
rf_res %>% 
  show_best(metric = "accuracy")
# A tibble: 5 × 8
   
mtry min_n .metric  .estimator  mean     n std_err .config              
  <int> <int> <chr>    <chr>      <dbl> <int>   <dbl> <chr>                
1  4     4 accuracy binary    0.927     1      NA Preprocessor1_Model08

2  9     8 accuracy binary    0.926     1      NA Preprocessor1_Model03
3  8    16 accuracy binary    0.915     1      NA Preprocessor1_Model10
4  7    22 accuracy binary    0.906     1      NA Preprocessor1_Model09

5  5    19 accuracy binary    0.904     1      NA Preprocessor1_Model0

8) Select the model with the best parameters for accuracy mtry=4 and min_n=4. For this the accuracy is 0.927. For this configuration the roc_auc is also the best at 0.980

9) Plot the Area Under the Curve (AUC). It can be seen that this model performs really well and it hugs the top left.

# Pick the best model
rf_best <- 
  rf_res %>% 
  select_best(metric = "accuracy")

# The best model has mtry=4 and min=4
rf_best
     mtry min_n .config              
  <int> <int> <chr>                
1     4     4      Preprocessor1_Model08

#Plot AUC
rf_auc <- 
  rf_res %>% 
  collect_predictions(parameters = rf_best) %>% 
  roc_curve(isWinner, .pred_0) %>% 
  mutate(model = "Random Forest")

autoplot(rf_auc)

10) Create the final model with the best parameters

11) Execute the final fit

12) Plot feature importance, The bowler and batsman embedding followed by perfIndex and runRate are features that contribute the most to the Win Probability

last_rf_mod <- 
  rand_forest(mtry = 4, min_n = 4, trees = 1000) %>% 
  set_engine("ranger", num.threads = cores, importance = "impurity") %>% 
  set_mode("classification")

# the last workflow
last_rf_workflow <- 
  rf_workflow %>% 
  update_model(last_rf_mod)

set.seed(345)
last_rf_fit <- 
  last_rf_workflow %>% 
  last_fit(splits)

last_rf_fit %>% 
  collect_metrics()

  .metric  .estimator .estimate .config             
  <chr>    <chr>          <dbl> <chr>               

1 accuracy binary         0.944 Preprocessor1_Model1
2 roc_auc  binary         0.988 Preprocessor1_Model1

last_rf_fit %>% 
  extract_fit_parsnip() %>% 
  vip(num_features = 9)

13) Plot the ROC curve for the best fit

# Plot the ROC for the final model
last_rf_fit %>% 
  collect_predictions() %>% 
  roc_curve(isWinner, .pred_0) %>% 
  autoplot()

14) Create a confusion matrix

We can see that the number of false positives and false negatives is very low

15) Create the final fit with the Random Forest Model

# generate predictions from the test set
test_predictions <- last_rf_fit %>% collect_predictions()
test_predictions

   id               .pred_0 .pred_1  .row .pred_class isWinner .config          
   <chr>              <dbl>   <dbl> <int> <fct>       <fct>    <chr>            
 1 train/test split   0.838  0.162      1 0           0       Preprocessor1_Mo…
 2 
train/test split   0.463  0.537     11 1           0        Preprocessor1_Mo…
 3 
train/test split   0.846  0.154     14 0           0        Preprocessor1_Mo…
 4 
train/test split   0.839  0.161     22 0           0        Preprocessor1_Mo…
 5 
train/test split   0.846  0.154     36 0           0        Preprocessor1_Mo…
 6 
train/test split   0.848  0.152     37 0           0        Preprocessor1_Mo…
 7 
train/test split   0.731  0.269     39 0           0        Preprocessor1_Mo…
 8 
train/test split   0.972  0.0281    40 0           0        Preprocessor1_Mo…
 9 
train/test split   0.655  0.345     42 0           0        Preprocessor1_Mo…
10 
train/test split   0.662  0.338     43 0           0        Preprocessor1_Mo…

# generate a confusion matrix
test_predictions %>% 
  conf_mat(truth = isWinner, estimate = .pred_class)

          Truth
Prediction      0      1
         
          0 116576   7096
         
          1   6391 109760

# Create the final model
final_model <- fit(last_rf_workflow, df_other)

16) Computing Win Probability with Random Forest Model for match

  • Pakistan-India-2022-10-23

17) Worm -wicket graph of match

  • Pakistan-India-2022-10-23

C) Win Probability using MLP – Deep Neural Network (DNN) with player embeddings

In this approach the MLP package of Tidymodels was used. Multi-layer perceptron (MLP) with Deep Neural Network (DNN) was used to compute the Win Probability using player embeddings. An accuracy of 0.76 was obtained

1) Read the data

a) Read the data from 9 T20 leagues (BBL, CPL, IPL, NTB, PSL, SSM, T20 Men, T20 Women, WBB) and create a single data frame of ball-by-ball data. Display the data frame

2) Create training.validation and test sets

b) Split to training, validation and test sets. The dataset is initially split into training and test in the ratio 80%:20%. The training data is again split into training and validation in the ratio 80:20

library(dplyr)
library(caret)
library(e1071)
library(ggplot2)
library(tidymodels)    
library(embed)

# Helper packages
library(readr)       # for importing data
library(vip) 
library(ranger)

df1=read.csv("output3/matchesBBL3.csv")
df2=read.csv("output3/matchesCPL3.csv")
df3=read.csv("output3/matchesIPL3.csv")
df4=read.csv("output3/matchesNTB3.csv")
df5=read.csv("output3/matchesPSL3.csv")
df6=read.csv("output3/matchesSSM3.csv")
df7=read.csv("output3/matchesT20M3.csv")
df8=read.csv("output3/matchesT20W3.csv")
df9=read.csv("output3/matchesWBB3.csv")

df=rbind(df1,df2,df3,df4,df5,df6,df7,df8,df9)


set.seed(123)
df$isWinner = as.factor(df$isWinner)
splits      <- initial_split(df,prop = 0.80)
df_other <- training(splits)
df_test  <- testing(splits)
set.seed(234)
val_set <- validation_split(df_other, 
                            prop = 0.80)
val_set

3) Create a Deep Neural Network recipe

  • Normalize parameters
  • Add embeddings for batsman, bowler

4) Set the MLP-DNN hyperparameters

  • epochs=100
  • hidden units =5
  • dropout regularization =0.1

5) Fit on Training data

cores <- parallel::detectCores()
cores

nn_recipe <- 
  recipe(isWinner ~ ., data = df_other) %>% 
step_normalize(ballNum,ballsRemaining,runs,runRate,numWickets,runsMomentum,perfIndex) %>%
  step_embed(batsman,bowler, outcome = vars(isWinner)) %>%
  prep(training = df_other, retain = TRUE) 

# For validation:
test_normalized <- bake(nn_recipe, new_data = df_test)

set.seed(57974)
# Set the hyper parameters for DNN
# Use Keras
# Fit on training data
nnet_fit <-
  mlp(epochs = 100, hidden_units = 5, dropout = 0.1) %>%
  set_mode("classification") %>% 
  # Also set engine-specific `verbose` argument to prevent logging the results: 
  set_engine("keras", verbose = 0) %>%
  fit(isWinner ~ ., data = bake(nn_recipe, new_data = df_other))

nnet_fit
parsnip model object
Model:"sequential"

____________________________________________________________________________

Layer (type)                                           Output Shape                                    Param #            
============================================================================
dense (Dense)                                           (None, 5)                                          60                 
____________________________________________________________________________

dense_1 (Dense)                                         (None, 5)                                          30                 
____________________________________________________________________________
dropout (Dropout)                                       (None, 5)                                          0                  
____________________________________________________________________________
dense_2 (Dense)                                         (None, 2)                                          12                 
============================================================================
Total params: 102
Trainable params: 102
Non-trainable params: 0

6) Test on Test data

  • Check ROC_AUC. It is 0.854
  • Check accuracy. The MLP-DNN gives a decent performance with an acuracy of 0.76
  • Compute the Confusion Matrix
# Validate on test data
val_results <- 
  df_test %>%
  bind_cols(
    predict(nnet_fit, new_data = test_normalized),
    predict(nnet_fit, new_data = test_normalized, type = "prob")
  )
val_results 

# Check roc_auc
val_results %>% roc_auc(truth = isWinner, .pred_0)
  .metric .estimator .estimate
  
   <chr>   <chr>          <dbl>
1 roc_auc binary         0.854

# Check accuracy
val_results %>% accuracy(truth = isWinner, .pred_class)
  .metric  .estimator .estimate
  <chr>    <chr>          <dbl>
1 accuracy binary         0.762

# Display confusion matrix
val_results %>% conf_mat(truth = isWinner, .pred_class)
          Truth
Prediction     
           0     1        
       0 97419 31564       
       1 25548 85292

Conclusion

  1. Of the 3 ML models, glmnet, random forest and Multi-layer Perceptron DNN, random forest had the best performance
  2. Random Forest ML model with batsman, bowler embeddings was able to achieve an accuracy of 92.4% and a ROC_AUC of 0.98 with very low false positives, negatives. This was a quantum jump from my earlier random forest model without embeddings which had an accuracy of 73.7% and an ROC_AUC of 0.834
  3. The glmnet and NN models are fairly light weight. Random Forest is computationally very intensive.

Check out my other posts

  1. Using Reinforcement Learning to solve Gridworld
  2. Deep Learning from first principles in Python, R and Octave – Part 8
  3. Introducing QCSimulator: A 5-qubit quantum computing simulator in R
  4. Big Data-5: kNiFi-ing through cricket data with yorkpy
  5. Singularity
  6. Practical Machine Learning with R and Python – Part 6
  7. GooglyPlusPlus2022 optimizes batting/bowling lineup
  8. Fun simulation of a Chain in Android
  9. Introducing cricpy:A python package to analyze performances of cricketers
  10. Programming languages in layman’s language

To see all posts click Index of posts

GooglyPlusPlus gets ready for ICC Men’s T20 World Cup

It is time!! So last weekend, I turned the wheels, moved the levers and listened to the hiss of steam, as I cranked up my Shiny app GooglyPlusPlus. The ICC Men’s T20 World Cup is just around the corner, and it was time to prepare for this event. This latest GooglyPlusPlus is current with the latest Intl. men’s T20 match data, give or take a few. GooglyPlusPlus can analyze batsmen, bowlers, matches, team-vs-team, team-vs-all teams, besides also ranking batsmen, bowlers and plot performances in Powerplay, middle and death overs.

In this post, I include a quick refresher of some of features of my app GooglyPlusPlus. Note: This is a random sampling of the functions available. There are more than 120+ features available in the app.

Check out your favourite players and your country’s team with GooglyPlusPlus

Note 1: All charts are interactive

Note 2: You can choose a date range for your analysis

Note 3: The data for this app is taken from Cricsheet

  1. T20 Batsman tab

This tab includes functions pertaining to individual batsmen. Functions include Runs vs Deliveries, moving average runs, cumulative average run, cumulative average strike rate, runs against opposition, runs at venue etc.

For e.g.

a) Suryakumar Yadav’s (India) cumulative strike rate

b) Mohammed Rizwan’s (Pakistan) performance against opposition

2. T20 Bowler’s Tab

The bowlers tab has functions for computing mean economy rate, moving average wickets, cumulative average wicks, cumulative economy rate, bowlers performance against opposition, bowlers performance in venue, predict wickets and others

A random function is shown below

a) Predict wickets for Wanindu Hasaranga of Sri Lanka

3. T20 Match tab

The match tab has functions that can compute match batting & bowling scorecard, batting partnerships, batsmen performance vs bowlers, bowler’s wicket kind, bowler’s wicket match, match worm graph, match worm wicket graph, team runs across 20 overs, team wickets in 20 overs, teams runs or wickets in powerplay, middle and death overs

Here are a couple of functions from this tab

a) Afghanistan vs Ireland – 2022-08-15

b) Australia vs Sri Lanka – 2019-11-01 – Runs across 20 overs

4. T20 Head-to-head tab

This tab provides the analysis of all combination of T20 teams (countries) in different aspects. This tab can compute the overall batting, bowling scorecard in all matches between 2 countries, batsmen partnerships, performances against bowlers, bowlers vs batsmen, runs, strike rate, wickets, economy rate across 20 overs, runs vs SR plot and wicket vs ER plot in all matches between team and so on. Here are a couple of examples from this tab

a) Bangladesh vs West Indies – Batting scorecard from 2019-01-01 to 2022-07-07

b) Wickets vs ER plot – England vs New Zealand – 2019-01-01 to 2021-11-10

5. T20 Team performance overall tab

This tab provides detailed analysis of the team’s performance against all other teams. As in the previous tab there are functions to compute the overall batting, bowling scorecard of a team against all other teams for any specific interval of time. This can help in picking out the most consistent batsmen, bowlers. Besides there are functions to compute overall batting partnerships, bowler vs batsmen, runs, wickets across 20 overs, run vs SR and wickets vs ER etc.

a) Batsmen vs Bowlers (Rank 1- V Kohli 2019-01-01 to 2022-09-25)

b) team Runs vs SR in Death overs (India) (2019-01-01 to 2022-09-25)

6) Optimisation tab

In the optimisation tab we can check the performance of a specific batsmen against specific bowlers or bowlers against batsmen

a) Batsmen vs Bowlers

b) Bowlers vs batsmen

7) T20 Batting Performance tab

This tab performs various analytics like ranking batsmen based on Run over SR and SR over Runs. Also you can plot overall Runs vs SR, and more specifically Runs vs SR in Powerplay, Middle and Death overs. All of this can be done for a specific date range. Here are some examples. The data includes all of T20 (all countries all matches)

a) Rank batsmen (Runs over SR, minimum matches played=33, date range=2019-01-01 to 2022-09-27)

The top 3 batsmen are Mohamen Rizwan, V Kohli and Babar Azam

b) Overall runs vs SR plot (2019-01-01 to 2022-09-27)

c) Overall Runs vs SR in Powerplay (all teams- 2019-01-01-2022-09-27)

This plot will be crowded. However, we can zoom into an area of interest. The controls for interacting with the plot are in the top of the plot as shown

Zooming in and panning to the area we can see the best performers in powerplay are as below

8) T20 Bowling Performance tab

This tab computes and ranks bowlers on Wickets over Economy and Economy rate over wickets. We can also compute and plot the Wickets vs ER in all matches , besides the Wickets vs ER in powerplay, middle and death overs with data from all countries

a) Rank Bowlers (Wickets over ER, minimum matches=28, 2019-01-01 to 2022-09-27)

b) Wickets vs ER plot

S Lamichhane (NEP), Hasaranga (SL) and Shamsi (SA) are excellent bowlers with high wickets and low ER as seen in the plot below

c) Wickets vs ER in death overs (2019-01-01 to 2022-09-27, min matches=24)

Zooming in and panning we see the best performers in death overs are MR Adair (IRE), Haris Rauf(PAK) and Chris Jordan (ENG)

With the excitement building up, it is time you checked out how your country will perform and the players who will do well.

Go ahead give GooglyPlusPlus a spin !!!

Also see

  1. Deep Learning from first principles in Python, R and Octave – Part 5
  2. Big Data-5: kNiFi-ing through cricket data with yorkpy
  3. Understanding Neural Style Transfer with Tensorflow and Keras
  4. De-blurring revisited with Wiener filter using OpenCV
  5. Re-introducing cricketr! : An R package to analyze performances of cricketers
  6. Modeling a Car in Android
  7. Presentation on “Intelligent Networks, CAMEL protocol, services & applications”
  8. Practical Machine Learning with R and Python – Part 2
  9. Cricpy adds team analytics to its arsenal!!
  10. Benford’s law meets IPL, Intl. T20 and ODI cricket

To see all posts click Index of posts

Then, Now(IPL 2022), Beyond : Insights from GooglyPlusPlus

IPL 2022 has just concluded and yet again, it is has thrown a lot of promising and potential youngsters in its wake, while established players have fallen! With IPL 2022, we realise that “Sceptre and Crown must tumble down” and that ‘the glories‘ of form and class like everything else are “shadows not substantial things” (Death the Leveller by James Shirley).

So King Kohli had to kneel, and hitman’ himself got hit. Rishabh Pant, Jadeja also had a poor season. On the contrary there were several youngsters who shone like Abhishek Sharma, Tilak Verma, Umran Malik or a Mohsin Khan

This post is about my potential T20 Indian players for the World Cup 2022 and beyond.

The post below includes my own analysis and thoughts. Feel free to try out my Shiny app GooglyPlusPlus and draw your own conclusions.

You can also view the analyais as a youtube video at Insights from GooglyPlusPlus

How often we hear that data by itself is useless, unless we can draw insights from it? This is a prevailing theme in the corporate world and everybody uses all sorts of tools to analyse and subsequently draw insights. Data analysis can be done in many ways as data can be sliced, diced, chopped in a zillion ways. There are many facets and perspectives to analysing data. Creating insights is easy, but arriving at actionable insights is anything but. So, the problem of selecting the best 11 is difficult as there are so many ways to look at the analysis. My Shiny app GooglyPlusPlus based on my R package yorkr can analyse data in several ways namely

  1. Batsman analysis
  2. Bowler analysis
  3. Match analysis
  4. Team vs team analysis
  5. Team vs all teams analysis
  6. Batsman vs bowler and vice versa
  7. Analysis of in 3,4,5 in power play, middle and death overs

GooglyPlusPlus uses my R package yorkr which has ~ 160 functions some which have several options. So, we can say roughly there are ~500 different ways that analysis can be done or in other words we can gather almost roughly 500+ different insights, not to mention that there are so many combinations of head-on matches and one-vs-all matches.

So generating insights or different ways of analysis data alone is not enough. The question is whether we can get a consolidated view from the different insights. In this post, I try to identify the best contenders for the Indian T20 team. This is far more difficult than it looks. Do you select players on past historical performance or do you choose from the newer crop of players, who have excelled in the recent IPL season. I think this boils down the typical situation in any domain. In engineering, we have tradeoffs – processing power vs memory tradeoff, throughput vs latency tradeoff or in the financial domain it is cost vs benefit or risk vs reward tradeoff. For team selection, the quandary is, whether to choose seasoned players with good historical performance but a poor performances in recent times or go with youngsters who have played with great courage and flair in this latest episode of IPL 2022. Hence there is a tradeoff between reliable but below average performance or risky but superlative performances of new players.

For this I base my potential list from

  • Then (past history of batsmen & bowlers) – I have chosen the performance of batsmen and bowlers in the last 3 years. With we can arrive at those who have had reasonably reliable performance for the last 3 years
  • Now (IPL 2022) – Performance in the current season IPL 2022

A. Then (Jan 2020 – May 2022) – Batsmen analysis

In this section I analyse the performances of batsmen and bowlers from Jan 2022 – May 2022. This is done based on ranking, and plots of Runs vs Strike Rate in Power Play, Middle and Death overs

Also I analyse bowlers based on the overall rank from Jan 2022- May 2022. Further more analysis is done on Wickets vs Economy Rate overall and in Power Play, Middle and Death overs

a. Ranks of batsmen (Runs over Strike Rate) : Jan 2020 – May 2022

The top batsmen consistency wise

[KL Rahul, Shikhar Dhawan, Ruturaj Gaikwad, Ishan Kishan, Shubman Gill, Suryakumar Yadav, Sanju Samson, Mayank Agarwal, Prithvi Shaw, Devdutt Padikkal, Nitish Rana, Virat Kohli, Shreyas Iyer, Ambati Rayadu, Rahul Tripathi, Rishabh Pant, Rohit Sharma, Hardik Pandya]

b. Ranks of batsmen (Strike Rate over Runs) : Jan 2020 – May 2022

The most consistent players from the Strike Rate perspective are

The batsmen with best Strike Rate in the last 3 years are

[Dinesh Karthik, Prithvi Shaw, Hardik Pandya, Rishabh Pant, Sanju Samson, Rahul Tripathi, Suryakumar Yadav, Nitish Rana, Mayank Agarwal, Krunal Pandya, MS Dhoni, Shikhar Dhawan, Ishan Kishan, KL Rahul]

c.Best Batsmen Runs vs SR : Jan 2020 – May 2022

The best batsmen should have a reasonable combination of Runs and SR. The best batsmen are

[KL Rahul, Shikhar Dhawan, Ruturaj Gaikwad, Ishan Kishan, Shubman Gill , Sanju Samson, Suryakumar Yadav, Shubman Gill, Mayank Agarwal, Prithvi Shaw, Nitish Rana, Hardik Pandya, Rishabh Pant, Rahul Tripathi,

d. Best batsmen Runs vs SR in Powerplay: Jan 2020 – May 2022

The best players in Power play

The best players in Power play in the last 3 years are

[KL Rahul, Prithvi Shaw, Rohit Sharma, Devdutt Padikkal, Mayank Agarwal, Virat Kohli, Ishan Kishan, Yashashvi Jaiswal, Wriddhiman Saha, Rahul Tripathi, Sanju Samson, Robin Uthappa, Venkatesh Iyer, Nitish Rana,Suryakumar Yadav, Abhishek Sharma Shreyas Iyer ]

e. Best batsmen Runs vs SR in Middleovers: Jan 2020 – May 2022

The most consistent players in the last 3 years in the middle overs are

[KL Rahul, Sanju Samson, Shikhar Dhawan, Rishabh Pant, Nitish Rana, Shreyas Iyer, Shubman Gill, Ishan Kishan, Devdutt Padikkal, Rahul Tripathi, Ruturaj Gaikwad, Shivam Dube, Hardik Pandya]

f. Best batsmen Runs vs SR in Death overs: Jan 2020 – May 2022

The best batsmen in death overs are

[Dinesh Karthik, Ravindra Jadeja, Hardik Pandya, Rahul Tewatia, MS Dhoni, KL Rahul, Rishabh Pant, Suryakumar Yadav, Ambati Rayadu, Virat Kohli, Nitish Rana, Shikhar Dhawan, Ruturaj Gaikwad, Ishan Kishan]

B) Now (IPL 2022) – Batsmen analysis

IPL 2022 just finished and clearly brings out the batsmen who are in great nick. It is always going to be a judgment call of whether to go for ‘old reliable’ or ‘new and awesome’.

a. Ranks of batsmen (Runs over Strike Rate) : IPL 2022

The best batsmen this season in Runs over Strike rate are

The best batsmen are

[KL Rahul, Shikhar Dhawan, Hardik Pandya, Deepak Hooda, Shubman Gill, Rahul Tripathi, Abhishek Sharma, Ishan Kishan, Wriddhiman Saha, Shreyas Iyer, Tilak Verma, Ruturaj Gaikwad, Sanju Samson, Shivam Dube]

b. Ranks of batsmen (Strike Rate over Runs) : IPL 2022

The batsmen with the best strike rate are

[Dinesh Karthik, Rishabh Pant, Rahul Tewathia, Rahul Tripathi, Sanju Samson, R Ashwin, Deepak Hooda, MS Dhoni, Nitish Rana, Riyan Parag, Shreya Iyer]

c.Best Batsmen Runs vs SR :IPL 2022

From an overall performance the following batsmen shone this season

[KL Rahul, Shikhar Dhawan, Shubman Gill, Hardik Pandya, Abhishel Sharma, Deepak Hooda, Rahul Tripathi, Tilak Verma, Shreya Iyer, Nitish Rana, Sanju Samson, Rishabh Pant]

d. Best batsmen Runs vs SR in Powerplay: IPL 2022

Top batsmen in Power play in IPL 2022

[Abhishek Sharma, Shikhar Dhawan, Rohit Sharma, Ishan Kishan, Shubman Gill, Prithvi Shaw, Wriddhiman Saha, Ishan Kishan, KL Rahul, Ruturaj Gaikwad, Virat Kohli, Yashasvi Jaiswal, Mayank Agarwal, Robin Uthappa, Sanju Samson, Nitish Rana]

e. Best batsmen Runs vs SR in Middleovers: IPL 2022

Best batsmen in middle overs in IPL 2022

[Deepak Hooda, Hardik Pandya, Tilak Verma, KL Rahul, Sanju Samson, Rishabh Pant, Shubman Gill, Ambati Rayudu, Suryaprakash Yadav, Shikhar Dhawan, Ruturaj Gaikwad]

f. Best batsmen Runs vs SR in Death overs: IPL 2022

Top batsmen in death overs in IPL 2022

[Dinesh Karthik, Rahul Tewatia, MS Dhoni, KL Rahul, Azar Patel, Washington Sundar, R Ashwin, Hardik Pandya, Ayush Badoni, Shivam Dube, Suryakumar Yadav, Ravindra Jadeja, Sanju Samson]

Overall Batting Performance in season

Kohli peaked in 2016 and from then on it has been a downward slide (see below)

Taking a look at Kohli’s moving average it is clear that he is past his prime and it will take a herculean effort to regain his lost glory

Similarly, Rohit Sharma’s moving average is constantly around ~30 as seen below

The cumulative average of Rohit Sharma is shown below

Comparing KL Rahul, Shikhar Dhawan, Rohit Sharma and V Kohli we see that KL Rahul and Shikhar Dhawan have had a much superior performance in the last 2-3 years. Rohit has averaged about ~25 runs every season.

Comparing the 4 wicket-keeper batsmen Sanju Samson, Rishabh Pant, Ishan Kishan and Dinesh Karthik from 2016

i) Runs over Strike Rate

We see that Pant peaked in 2018 but has not performed as well since. In the last 2 years Sanju Samson and Ishan Kishan have done well

ii) Strike Rate over Runs

For the last couple of seasons Rishabh Pant and Dinesh Kartik top the strike rate over the other 2

Similar analysis can be done other combinations of batsmen

Choosing the best batsmen from the above, my top 5 batsmen would be

  1. KL Rahul
  2. Shikhar Dhawan
  3. Prithvi Shaw, Ruturaj Gaikwad, Ishan Kishan
  4. Sanju Samson, Shreyas Iyer, Shubman Gill, Shivam Dube,
  5. Abhishek Sharma, Tilak Verma, Rahul Tripathi, Suryakumar Yadav, Deepak Hooda
  6. Rishabh Pant, Dinesh Karthik

Personally, I feel Ishan Kishan and Shreyas Iyer are a little tardy while playing express speeds, as compared to Sanju Samson or Rishabh Pant.

If you notice, I have not included both Virat Kohli or Rohit Sharma who have been below par for some time

C. Then (Jan 2020 – May 2022) – Bowler analysis

This section I analyse the performances of bowlers from Jan 2022 – May 2022. This is done based on ranking, and plots of Wickets vs Economy Rate in Power Play, Middle and Death overs

a. Ranks of bowlers (Wickets over Economy Rate) : Jan 2020 – May 2022

The most consistent bowlers Wickets over Economy Rate for the last 3 years are

[YS Chahal, Jasprit Bumrah, Mohammed Dhami, Harshal Patel, Shardul Thakur, Arshdeep Singh, Rahul Chahar, Varun Chakravarthy, Ravi Bishnoi, Prasidh Krishna, R Ashwon, Axar Patel, Mohammed Siraj, Ravindra Jadeja, Krunal Pandya, Rahul Tewatia]

b. Ranks of bowlers (Economy Rate over Wickets) : Jan 2020 – May 2022

The most economical bowlers since 2020 are

[Axar Patel, Krunal Pandya, Jasprit Bumrah, CV Varun, R Ashwin, Ravi Bishnoi, Rahul Chahar, YS Chahal, Ravindra Jadeja, Harshal Patel, Mohammed Shami, Mohammed Siraj, Rahul Tewatia, Arshdeep Singh, Prasidh Krishna, Shardul Thakur]

c.Best Bowlers Wickets vs ER : Jan 2020 – May 2022

The best bowlers Wickets vs ER will be in the bottom right quadrant. The most consistent and reliable bowlers are

[YS Chahal, Jasprit Bumrah, Mohammed Shami, Harshal Patel, CV Arun, Ravi Bishnoi, Rahul Chahar, R Ashwin, Axar Patel]

d. Best bowlers Wickets vs ER in Powerplay: Jan 2020 – May 2022

The best bowlers in Powerplay are

[Mohammed Shami, Deepak Chahar, Mohammed Siraj, Arshdeep Singh, Jasprit Bumrah, Avesh Khan, Mukesh Choudhary, Shardul Thakur, T Natarajan, Bhuvaneshwar Kumar, WashingtonSundar, Shivam Mavi]

e. Best bowlers Wickets vs ER in Middle overs : Jan 2020 – May 2022

The most reliable performers in middle overs from 2020-2022 are

[YS Chahal, Rahul Chahr, Ravi Bishnoi, Harshal Patel, Axar Patel, Jasprit Bumrah, Umran Malik, R Ashwin, Avesh Khan, Shardul Thakur, Kuldeep Yadav]

f. Best bowlers Wickets vs ER in Death overs : Jan 2020 – May 2022

The most reliable bowlers are

[Harshal Patel, Mohammed Shami, Jasprit Bumrah, Arshdeep Singh, T Natarajan, Avesh Khan, Shardul Thakur, Bhuvaneshwar Kumar, Shivam Mavi, YS Chahal, Prasidh Krishna, Mohammed Siraj, Chetan Sakariya]

B) Now (IPL 2022) – Bowler analysis

a. Ranks of bowlers (Wickets over Economy Rate) : IPL 2022

The best bowlers in IPL 2022 when considering Wickets over Economy Rate

[YS Chahal, Umran Malik, Prasidh Krishna, Mohammed Shami, Kuldeep Yadav, Harshal Patel, T Natarajan, Avesh Khan, Shardul Thakur, Mukesh Choudhary, Jasprit Bumrah, Ravi Bishnoi]

a. Ranks of bowlers (Economy Rate over Wickets) : IPL 2022

The most economical bowlers in IPL 2022 are

[Axar Patel, Jasprit Bumrah, Krunal Pandya, Umesh Yadav, Bhuvaneshwar Kumar, Rahul Chahr, Harshal Patel, Arshdeep Singh, R Ashwion, Umran Malik, Kuldeep Yadav, YS Chahal, Mohammed Shami, Avesh Khan, Prasidh Krishna]

c.Best Bowlers Wickets vs ER : IPL 2022

The overall best bowlers in IPL 2022 are

[YS Chahal, Umran Malik, Harshal Patel, Prasidh Krishna, Mohammed Shami, Kuldeep Yadav, Avesh Khan, Jasprit Bumrah, Umesh Yadav, Bhuvaneshwar Kumar, Arshdeep Singh, R Ashwin, Rahul Chahar, Krunal Pandya]

d. Best bowlers Wickets vs ER in Powerplay: IPL 2022

The best bowlers in IPL 2022 in Power play are

[Mukesh Choudhary, Mohammed Shami, Prasidh Krishna, Umesh Yadav, Avesh Khan, Mohsin Khan, T Natarajan, Jasprit Bumrah, Yash Dayal, Mohammed Siraj]

d. Best bowlers Wickets vs ER in Middle overs: IPL 2022

The best bowlers in IPL 2022 during middle overs

The best bowlers are

[YS Chahal, Umran Malik, Kuldeep Yadav, Harshal Patel, Ravi Bishnoi, R Ashwin]

e. Best bowlers Wickets vs ER in Death overs: IPL 2022

The best bowlers in death overs in IPL 2022 are

[T Natarajan, Harshal Patel, Bhuvaneshwar Kumar, Mohammed Shami, Jasprit Bumrah, Shardul Thakur, YS Chahal, Prasidh Krishna, Avesh Khan, Mohsin Khan, Yash Dayal, Umran Malik, Arshdeep Singh]

Typically in a team we would need a combination of 4 bowlers (2 fast & 2 spinner or 3 fast and 1 spinner) with an additional player who is all rounder.

For 4 bowlers we could have

  1. JJ Bumrah
  2. Mohammed Shami, Umran Malik, Bhuvaneshwar Kumar, Umesh Yadav
  3. Arshdeep Singh, Avesh Khan, Mohsin Khan, Harshal Patel
  4. YS Chahal, Ravi Bishnoi, Rahul Chahar, Axar Patel
  5. Ravindra Jadeja, Hardik Pandya, Rahul Tewathia, R Ashwin

i) Performance comparison (Wickets over Economy Rate)

Bumrah had the best season in 2020. He has been doing quite well and has been among the wickets

ii) Performance comparison (Economy Rate over Wickets)

Bumrah has the best Economy Rate

We can do a wicket prediction of bowlers. So for example for Bumrah it is

iii) Performance evaluation (Wickets over Economy Rate)

Harshal Patel followed by Avesh Khan had a good season last year, but Umran Malik pipped them this year (see below)

iv) Performance analysis of spinners

a. Wickets over Economy Rate: 2022

Chahal has the best season followed by Bishnoi and Chahar this season

b) Economy Rate over WIckets

Axar Patel has the best economy rate followed by Rahul Chahar

Conclusion

The above post identified the best candidates for the Indian team in the future and beyond. In my T20 list, I have neither included Virat Kohli or Rohit Sharma. The data in T20 clearly indicates that they have had their days. There is a lot more talent around. The tradeoff is a little risk for a greater potential performance. My list would be

  1. KL Rahul
  2. Shikhar Dhawan
  3. Ruturaj Gaikwad, Prithvi Shaw, Rahul Tripathi
  4. Suryakumar Yadav, Shreyas Iyer, Abhishek Sharma, Deepak Hooda
  5. Sanju Samson (Wicket keeper/captain)/ Rishabh Pant/Dinesh Karthik
  6. Hardik Pandya, Ravindra Jadeja, Rahul Tewathia
  7. Jasprit Bumrah
  8. Mohammed Shami, Bhuvaneshwar Kumar, Umran Malik
  9. Arshdeep Singh, Avesh Khan, Harshal Patel
  10. YS Chahal
  11. Axar Patel, Ravi Bishnoi, Rahul Chahar

You may agree/ disagree with my list. Feel free to do your analysis with GooglyPlusPlus and come to your own conclusions

This analysis is also available on youtube Insights from GooglyPlusPlus

You may also like

  1. Deep Learning from first principles in Python, R and Octave – Part 1
  2. Player Performance Estimation using AI Collaborative Filtering
  3. The mechanics of Convolutional Neural Networks in Tensorflow and Keras
  4. TWS-4: Gossip protocol: Epidemics and rumors to the rescue
  5. Big Data-4: Webserver log analysis with RDDs, Pyspark, SparkR and SparklyR
  6. Programming languages in layman’s language
  7. Practical Machine Learning with R and Python – Part 4
  8. Pitching yorkpy…swinging away from the leg stump to IPL – Part 3
  9. Revisiting World Bank data analysis with WDI and gVisMotionChart
  10. Natural language processing: What would Shakespeare say?

To see all posts click Index of posts


IPL 2022: Near real-time analytics with GooglyPlusPlus!!!

It is that time of the year when there is “a song in the air, the lark’s on the wing, and the snail’s on the the thorn“. Yes, it is the that time of year when the grand gala event of IPL 2022 is underway. So, I managed to wake myself from my Covid-induced slumber, worked up my ‘creaking bones‘ and cranked up the GooglyPlusPlus machinery.

So now, every morning, a scheduled CRON tab entry will automatically download the previous night’s match data from Cricsheet, unzip, process and transform it into the necessary format required by my R package yorkr, and make it available to my Shiny app GooglyPlusPlus. Hence the data is current and you have access to ‘analytics-in-the-now’!.

As you know in 2021, I added a lot of new features to GooglyPlusPlus, new tabs to do even more. analytics – or in other words there is “more GooglyPlusPlus per click!!”. So now, you have the following

  • Batsman tab: For detailed analysis of batsmen
  • Bowler tab: For detailed analysis of bowlers
  • Match tab: Analysis of individual matches, plot of Runs vs SR, Wickets vs ER in power play, middle and death overs
  • Head-to-head tab: Detailed analysis of team-vs-team batting/bowling scorecard, batting, bowling performances, performances in power play, middle and death overs
  • Team performance tab: Analysis of team-vs-all other teams with batting /bowling scorecard, batting, bowling performances, performances in power play, middle and death overs
  • Optimisation tab: Allows one to pit batsmen vs bowlers and vice-versa. This tab also uses integer programming to optimise batting and bowling lineup
  • Batting analysis tab: Ranks batsmen using Runs or SR. Also plots performances of batsmen in power play, middle and death overs and plots them in a 4×4 grid
  • Bowling analysis tab: Ranks bowlers based on Wickets or ER. Also plots performances of bowlers in power play, middle and death overs and plots them in a 4×4 grid

Also note all these tabs and features are available for all T20 formats namely IPL, Intl. T20 (men, women), BBL, NTB, PSL, CPL, SSM.

Note: All charts are interactive, which means that you can hover, zoom-in, zoom-out, pan etc on the charts

The latest avatar of GooglyPlusPlus2022 is based on my R package yorkr with data from Cricsheet.

Go ahead, give GooglyPlusPlus a try!!!

To know all the new features and how to use them, check out these posts

  1. Ranking of batsmen, bowlers – GooglyPlusPlus2021 interactively ranks T20 batsmen and bowlers!!!
  2. Interactive charts – GooglyPlusPlus2021 is now fully interactive!!!
  3. Detailed batsmen/bowler analytics – GooglyPlusPlus2021 enhanced with drill-down batsman, bowler analytics
  4. Addition of Date Range picker to charts – GooglyPlusPlus2021 adds new bells and whistles!!
  5. Analysis of power play, middle and death overs across players, teams – GooglyPlusPlus2021 now with power play, middle and death over analysis
  6. Analysis based on 4 x 4 grid of players – GooglyPlusPlus2021: Towards more picturesque analytics!
  7. Optimisation of batsmen/bowlers – GooglyPlusPlus2022 optimizes batting/bowling lineup

Here are some random analysis that can be done by GooglyPlusPlus across the tabs. Note the app will be updated daily and the analytics will be current throughout the season of IPL 2022

A) Match tab

a) GT vs DC – 2 Apr 2022

Runs vs SR – Gujarat Titans

b) CSK vs LSG – 31 Mar 2022

Runs across 20 overs

c) KKR vs PBKS -Match wicket worm chart – 1 Apr 2022

B) Batsmen tab

a) Faf Du Plessis – Runs vs Deliveries

b) Sanju Samson – Runs against opposition

C) Bowler’s tab

a) D J Bravo – No of deliveries to wicket

b) Trent Boult – Wickets at Venues

D) Head-to-head tab

a) DC vs MI – Mar -2019 till date : Batting scorecard

b) CSK vs KKR – Jan 2019 till date : Runs vs SR

E) Team vs All Teams tab

a) Punjab Kings vs all Teams – Wickets vs ER in Power play

b) Rajasthan Royals vs all Teams : Jan 2019 till date : Runs vs SR in Power play

F) Optimisation tab

a) Batsmen vs Bowlers

b) Bowlers vs batsmen

G) Batting analysis

This tab is for ranking batsmen

a) Batsmen rank from 2019 till date (Runs over SR)

b) Overall Runs vs SR (Jan 2020 till date)

Best batsmen in top right quadrant

zooming in on the above (right-most)

H) Bowling analysis tab

a) Best middle over bowlers in IPL (2019 onwards)

The bottom right quadrant are the best bowlers

b) Best bowlers in death overs (bottom-right)

Check out GooglyPlusPlus!!!

Also see

  1. Deconstructing Convolutional Neural Networks with Tensorflow and Keras
  2. Deep Learning from first principles in Python, R and Octave – Part 5
  3. Big Data-4: Webserver log analysis with RDDs, Pyspark, SparkR and SparklyR
  4. Latency, throughput implications for the Cloud
  5. Introducing QCSimulator: A 5-qubit quantum computing simulator in R
  6. Practical Machine Learning with R and Python – Part 3
  7. Natural language processing: What would Shakespeare say?
  8. Introducing cricpy:A python package to analyze performances of cricketers

To see all posts click Index of posts

GooglyPlusPlus2022 optimizes batting/bowling lineup

GooglyPlusPlus2022 is the new avatar of last year’s GooglyPlusPlus2021. Roughly, about 5 years back I had written a post on Using linear programming to optimize T20 batting and bowling line up. This post has been on the back of my mind for a long time and I decided to pay this post a revisit. This requires computing performance of individual batsmen vs bowlers and vice-versa for performing the optimization. So in this latest incarnation, there are 4 new functions

  1. batsmanVsBowlerPerf – Performance of batsmen against chosen bowlers
  2. bowlerVsBatsmanPerf – Performance of bowlers versus specific batsmen
  3. battingOptimization – Optimizing batting line up based on strike rates ad remaining overs
  4. bowlingOptimization – Optimizing bowling line up based on economy rates and remaining overs

These 4 functions have been incorporated in all the supported 9 T20 formats namely a. IPL b. Intl. T20(men) c. Intl. T20 (women) d. BBL e. NTB f. PSL g. WBB h. CPL i. SSM

Check out GooglyPlusPlus2022!!

You can clone/fork the code for GooglyPlusPlus2022 from Github from gpp2022-1

With this latest update you can do a myriad of analyses of batsmen, bowlers, teams, matches. This is just-in-time for the IPL Mega-auction!! Do check out these other posts of GooglyPlusPlus for other detailed analysis

  1. GooglyPlusPlus2021: Towards more picturesque analytics!
  2. GooglyPlusPlus2021 now with power play, middle and death over analysis
  3. GooglyPlusPlus2021 adds new bells and whistles!!
  4. GooglyPlusPlus2021 is now fully interactive!!!

A) Batsman Vs Bowlers – This option computes the performance of individual batsman against individual bowlers

a) IPL Batsmen vs Bowlers

Included below are the performances of Dhoni, Raina and Kohli against Malinga, Ashwin and Bumrah. Note: The last 2 text box input are not required for this.

b) Intl. T20 (men) Batsmen vs Bowlers

Note: You can type the name and choose from the drop down list

B) Bowler vs Batsmen – You can check the performance of specific bowlers against specific batsmen

a) Intl. T20 (women) India vs Australia

b) PSL Bowlers vs Batsmen

C) Strategy for optimizing batting and bowling line up

From the above 2 tabs, it is obvious, that different bowlers have different ER and wicket rate against different batsmen. In other words, the effectiveness of the bowlers varies by batsmen. Conversely, batsmen are more comfortable with certain bowlers versus others and this shows up in different strike rates.

Hence during the death overs, when trying to restrict batsmen to a certain score or on the flip side when the batting side needs to score a target within certain overs, we need to take advantage of the relative effectiveness of bowlers vs batsmen for optimising bowling and aggressiveness of batsmen versus bowlers to quickly reach the target.

This is the approach that is used for bowling and batting optimisation. For optimising bowling, we need to formulate a minimisation problem based on ER rates and for optimising batting, a maximisation strategy is chosen based on SR. ‘Integer programming’ is used to compute during the last set of overs

This latest version includes optimization using “integer programming” based on R package lpSolve.

Here are the 2 formulations

Assume there are 3 bowlers – bwlr_{1},bwlr_{2},bwlr_{3}
and there are 3 batsmen – bman_{1},bman_{2},bman_{3}

I) LP Formulation for bowling order

Let the economy rate er_{ij} be the Economy Rate of the jth bowler to the ith batsman. Also if remaining overs for the bowlers are o_{1},o_{2},o_{3}
and the total number of overs left to be bowled are
o_{1}+o_{2}+o_{3} = N

Let the economy rate er_{ij} be the Economy Rate of the jth bowler to the ith batsman.
Objective function : Minimize –
er_{11}*o_{11} + er_{12}*o_{12} +..+er_{1n}*o_{1n}+ er_{21}*o_{21} + er_{22}*o_{22}+.. + er_{22}*o_{2n}+ er_{m1}*o_{m1}+..+ er_{mn}*o_{mn}
i.e.
\sum_{i=1}^{i=m}\sum_{j=1}^{i=n}er_{ij}*o_{ij}
Constraints
Where o_{j} is the number of overs remaining for the jth bowler against  ‘k’ batsmen
o_{j1} + o_{j2} + .. o_{jk} < o_{j}
and if the total number of overs remaining to be bowled is N then
o_{1} + o_{2} +...+ o_{k} = N or
\sum_{j=1}^{j=k} o_{j} =N
The overs that any bowler can bowl is o_{j} >=0

II) LP Formulation for batting lineup

Let the strike rate sr_{ij}  be the Strike Rate of the ith batsman to the jth bowler
Objective function : Maximize –
sr_{11}*o_{11} + sr_{12}*o_{12} +..+ sr_{1n}*o_{1n}+ sr_{21}*o_{21} + sr_{22}*o_{22}+.. sr_{2n}*o_{2n}+ sr_{m1}*o_{m1}+..+ sr_{mn}*o_{mn}
i.e.
\sum_{i=1}^{i=4}\sum_{j=1}^{i=3}sr_{ij}*o_{ij}
Constraints
Where o_{j} is the number of overs remaining for the jth bowler against  ‘k’ batsmen
o_{j1} + o_{j2} + .. o_{jk} < o_{j}
and the total number of overs remaining to be bowled is N then
o_{1} + o_{2} +...+ o_{k} = N or
\sum_{j=1}^{j=k} o_{j} =N
The overs that any bowler can bowl is
o_{j} >=0

C) Optimized bowling lineup

a) IPL – Optimizing bowling line up

Note: For computing the Optimal bowling lineup, the total number of overs remaining and the number of overs for each bowler have to be entered.

b) PSL – Optimizing batting line up

d) Optimized batting lineup

a) Intl. T20 (men) India vs England

b) Carribean Premier LeagueOptimizing batting line up

Give GooglyPlusPlus2022 a spin!

You can also check the code here gpp2022-1

Hope you have a good time with GooglyPlusPlus2022!

Also see

  1. Re-working the Lucy Richardson algorithm in OpenCV
  2. Deconstructing Convolutional Neural Networks with Tensorflow and Keras
  3. Deep Learning from first principles in Python, R and Octave – Part 5
  4. Cricketr adds team analytics to its repertoire!!!
  5. Practical Machine Learning with R and Python – Part 4
  6. Cricpy takes a swing at the ODIs
  7. yorkpy takes a hat-trick, bowls out Intl. T20s, BBL and Natwest T20!!!
  8. Big Data-4: Webserver log analysis with RDDs, Pyspark, SparkR and SparklyR
  9. Introducing QCSimulator: A 5-qubit quantum computing simulator in R

To see all posts click Index of posts

More player analysis with gganimate()

This post continues the analysis of IPL and T20 (men) batsmen and bowlers through animated charts. In my last post Analyzing player performance with animated charts! I had used animated horizontal bars to display the totalRuns or totalWickets over a 3 year ‘sliding window’. While that was cool, the only drawback of that animation was the batsman and bowler performance was measured in a single dimension of either total(mean) runs or total(mean) wickets.

I think to fairly describe batsmen and bowlers we need at least the following 2 attributes

  • Runs and Strike rate for batsmen and
  • Wickets and Economy rate for bowlers

So, I have created new animation charts which use these attributes for batsmen and bowlers.

The animated charts are

  • Based on a sliding window of 3 years (Jan 2008- Dec 2010, Jan 2009-Dec 2010,…, Jan 2019-Dec 2021)
  • I have taken the top 10 percentile and sometimes the top 5 percentile of batsmen and bowlers to keep the charts more manageable
  • The charts are based on gganimate().

Note 1: I tried several options for the animation before settling on this one. The animation may seem a bit jerky but, we can follow the progress of players more easily through the years

Note 2: Some charts may display points, without the corresponding names. I think this may be because the animation tries to create intermediate points between the charts.

Note 3: For fine-grained, but static analysis across different intervals or seasons, checkout my my posts GooglyPlusPlus2021 now with power play, middle and death over analysis and GooglyPlusPlus2021: Towards more picturesque analytics!

The code for the animation can be cloned from Github at animation2. Feel free to modify the parameters for a different animation behavior.

Here are performances of IPL and T20 (men) players. Note all charts are based on a 3 year staggered window. The Top 10 percentile is considered

  1. Runs vs SR – IPL

We can that Shikhar Dhawan is a top performer for 4 years from 2018-2021. He definitely deserved a slot in the India WC 15 member squad.

2. Wickets vs ER – IPL

Similarly, YS Chahal also deserved a slot in the 15 member sqad

3. Runs vs SR in Power play – IPL

S Dhawan, De Kock & KL Rahul are the best players in Power play

4. Runs vs Strike rate in Middle overs – IPL

Rishabh Pant, Shreyas Iyer,Sanju Samson and KL Rahul are best performers in Middle overs

5.Runs vs SR in Death overs – IPL

It is MS Dhoni all the way, till Hardik Pandya catches up. But H Pandya had poor IPL seasons in 2020, 2021. See my post GooglyPlusPlus2021: Towards more picturesque analytics! for finer analysis

6. Wickets vs ER in Power play – IPL

In the early years B. Kumar led. More recently D Chahar and T Boult

7. Wickets vs ER in Middle overs – IPL

YS Chahal, Rashid Khan, Imran Tahir and Rahul Chahar lead in Middle overs

8. Wickets vs ER in Death overs – IPL

Bumrah & Rabada top performers

9. Runs vs SR – T20 (men)

Babar Azam, PR Stirling, Rohit Sharma, S Dhawan, KL Rahul are best performers in recent times

10. Wickets vs ER – T20 (men)

Wanindu Hasaranga, T Shamsi, Shadab Khan, Rashid Khan, T Boult are best performers in recent times

11. Runs vs SR in Power Play – T20 (men)

PR Stirling, RG Sharma, C Munro, Shikhar Dhawan lead

12. Runs vs SR in Middle overs – T20 (men)

Babar Azam, followed by Kohli, S Dhawan, Rizwan, RG Sharma in recent years

13. Runs vs SR in Death overs – T20 (men)

Shoaib Malik, V Kohli, Mohamed Nabi. Mohammed Rizwan and other top the death overs

14. Wickets vs ER in Power play (T20 men)

TG Southee, Mujeeb Ur Rahman and B Stanlake lead in recent years

15. Wickets vs ER in Middle overs – T20 (men)

Top bowlers are Shadab Khan, T Shamsi, Kuldeep Yadav, YS Chahal and AC Agar

16. Wickets vs ER in Death overs – T20 (men)

Haris Rauf, AJ Tye, Rashid Khan and Chris Jordan excel in death overs

You may also like

  1. Re-introducing cricketr! : An R package to analyze performances of cricketers
  2. Cricketr adds team analytics to its repertoire!!!
  3. Pitching yorkpy … short of good length to IPL – Part 1
  4. yorkr rocks women’s One Day International (ODI) and International T20!!
  5. Big Data-5: kNiFi-ing through cricket data with yorkpy
  6. Using Linear Programming (LP) for optimizing bowling change or batting lineup in T20 cricket
  7. Introducing cricpy:A python package to analyze performances of cricketers
  8. Benford’s law meets IPL, Intl. T20 and ODI cricket
  9. GooglyPlusPlus2021 is now fully interactive!!!
  10. Sixer – R package cricketr’s new Shiny avatar

To see all posts click Index of posts

Analyzing player performance with animated charts!

Analytics is by definition, the science (& art) of identifying, discovering and interpreting patterns in data. There are different ways of capturing these patterns through charts (bar, pie, cumulative data, moving average etc.). One such way is the motion or animated chart which captures the changes in data across different time periods. This was made famous by Hans Rosling in his Gapminder charts.

In this post, I use animated charts, based on gganimate(), to display the rise and fall of batsmen and bowlers in IPL and Intl. T20 (men). I only did this for these 2 formats as they have sufficient data over at least 10+ years.

To construct these animated charts, I use a ‘sliding window’ of 3 years, so that we get a clearer view of batsman and bowler consistency. The animated charts show the performance of players for this moving window for e.g. Jan 2008- Dec 2010, Jan 2009-Dec 2011, Jan 2010- Dec 2012 and so on till Jan 2019- Dec 2021. This is done for both batting( total runs) and bowling (total wickets). If you would like to analyse the performance of particular batsmen, bowler during specific periods or for a team vs another team or in the overall T20 format, check out my post GooglyPlusPlus2021: Towards more picturesque analytics!

You clone/fork the code from Github here animation.

Note: This code is based on a snippet from this blog How to create animations in R with gganimate by Ander Fernandez Jauregui

Included below are the animated charts.

Important note: The year which is displayed on the side actually represents the last 3 years, for e.g. 2015 (2013, 2014, 2015) or 2019 (2017, 2018, 2019)

  1. IPL Batting performance

We can see that Kohli stays in the top 3 from 2015-2019

2. IPL Bowling performance

Malinga ruled from 2010- 2015. Bumrah is in top 3 from 2019-2021

3. IPL Batting in Power play

Adam Gilchrist, Tendulkar, Warner, KL Rahul, Shikhar Dhawan have a stay at the top

4. IPL Batting in Middle overs

Rohit Sharma, Kohli, Pant have their stay at the top

5. IPL Batting Death overs

MS Dhoni is lord and master of the death overs in IPL for a rolling period of 10 years from 2011-2020. No wonder, he is the best finisher of T20 cricket

6. IPL Bowling Power Play

Bhuvanesh Kumar is in top 3 from 2014-2018 and then Deepak Chahar

7. IPL Bowling Middle overs

Toppers Harbhajan Singh, YS Chahal, Rashid Khan

8. IPL Bowling Death overs

SL Malinga, B. Kumar, JJ Bumrah and Rabada top the list across the years

9. T20 (men) Batting performance

Kohli, Babar Azam, P R Stirling are best performers

10. T20 (men) bowling performance

Saaed Ajmal tops from 2010-2014 and Rashid Khan 2018-2020

11. T20 (men) batting Power play

Shahzad, D Warner, Rohit Sharma, PR Stirling best performers

12. T20 (men) batting middle overs

Babar Azam is the best middle overs player from 2018-2021

13. T20(men) batting death overs

MS Dhoni, Shoaib Malik, V Kohli, David Miller are the best death over players

14. T20 (men) bowling Power play

Mohammad Nabi, Mujeeb ur Rahman, TG Southee are the best bowlers in power play

15. T20 (men) bowling middle overs

Imran Tahir from 2015-2017, Shadab Khan from 2018-2020, T Shamsi in 2021 top the tables

16. T20 (men) bowling death overs

Saaed Ajmal, A J Tye, Bumrah, Haris Rauf occupy the top slot in different periods

Also see

  1. Experiments with deblurring using OpenCV
  2. Using Reinforcement Learning to solve Gridworld
  3. Deep Learning from first principles in Python, R and Octave – Part 8
  4. Big Data-4: Webserver log analysis with RDDs, Pyspark, SparkR and SparklyR
  5. The Anomaly
  6. Practical Machine Learning with R and Python – Part 3
  7. Using Linear Programming (LP) for optimizing bowling change or batting lineup in T20 cricket
  8. Introducing cricpy:A python package to analyze performances of cricketers

To see all posts click Index of posts

GooglyPlusPlus2021: Towards more picturesque analytics!

Analytics for e.g. sports analytics, business analytics or analytics in e-commerce or in other domain has 2 main requirements namely a) What kind of analytics (set of parameters,function) will squeeze out the most intelligence from the data b) How to represent the analytics so that an expert can garner maximum insight?

While it may appear that the former is more important, the latter is also equally, if not, more vital to the problem. Indeed, a picture is worth a thousand words, and often times is more insightful than a large table of numbers. However, in the case of sports analytics, for e.g. in cricket a batting or bowling scorecard captures more information and can never be represented in chart.

So, my Shiny app GooglyPlusPlus includes both charts and tables for different aspects of the analysis. In this post, a newer type of chart, popular among senior management experts, namely the 4 quadrant graph is introduced, which helps in categorising batsmen and bowlers into 4 categories as shown below

a) Batting Performances – Top right quadrant (High runs, High Strike rate)

b) Bowling Performances – Bottom right quadrant( High wickets, Low Economy Rate)

I have added the following 32 functions in this latest version of GooglyPlusPlus

A. Match Tab

All the functions below are at match level

  1. Team Runs vs SR Plot
  2. Team Wickets vs ER Plot
  3. Team Runs vs SR Power play plot
  4. Team Runs vs SR Middle overs plot
  5. Team Runs vs SR Death overs plot
  6. Team Wickets vs ER Power Play
  7. Team Wickets vs ER Middle overs
  8. Team Wickets vs ER Death overs

B. Head-to-head Tab

The below functions are based on all matches between 2 teams’

  1. Team Runs vs SR Plot all Matches
  2. Team Wickets vs ER Plot all Matches
  3. Team Runs vs SR Power play plot all Matches
  4. Team Runs vs SR Middle overs plot all Matches
  5. Team Runs vs SR Death overs plot all Matches
  6. Team Wickets vs ER Power Play plot all Matches
  7. Team Wickets vs ER Middle overs plot all Matches
  8. Team Wickets vs ER Death overs plot all Matches

C. Team Performance tab

The below functions are based on a team’s performance against all other teams

  1. Team Runs vs SR Plot overall
  2. Team Wickets vs ER Plot overall
  3. Team Runs vs SR Power play plot overall
  4. Team Runs vs SR Middle overs plot overall
  5. Team Runs vs SR Death overs plot overall
  6. Team Wickets vs ER Power Play overall
  7. Team Wickets vs ER Middle overs overall
  8. Team Wickets vs ER Death overs overall

D. T20 format Batting Analysis

This analysis is at T20 format level (IPL, Intl. T20(men), Intl. T20 (women), PSL, CPL etc.)

  1. Overall Runs vs SR plot
  2. Overall Runs vs SR Power play plot
  3. Overall Runs vs SR Middle overs plot
  4. Overall Runs vs SR Death overs plot

E. T20 Bowling Analysis

This analysis is at T20 format level (IPL, Intl. T20(men), Intl. T20 (women), PSL, CPL etc.)

  1. Overall Wickets vs ER plot
  2. Team Wickets vs ER Power Play
  3. Team Wickets vs ER Middle overs
  4. Team Wickets vs ER Death overs

These 32 functions have been added to my yorkr package and so all these functions become plug-n-play in my Shiny app GooglyPlusPlus2021 which means that the 32 functions apply across all the nine T20 formats that the app supports i.e. IPL, Intl. T20 (men), Intl. T20 (women), BBL, NTB, PSL, CPL, SSM, WBB.

Hence the multiplicative factor of the new addition is 32 x 9 = 288 additional ways of exploring match, team and player data

The data for GooglyPlusPlus is taken from Cricsheet. My shiny app GooglyPlusPlus2021 is based on my R package yorkr.

You can clone/fork GooglyPlusPlus from Github at gpp2021-10

Check out my app GooglyPlusPlus2021 and analyze batsmen, bowlers, teams, overall performance. The data for all the nine T20 formats have been updated to include the latest data.

Hence, the app is just in time for the IPL mega auction. You should be able to analyse players in IPL, Intl. T20 or in any of the other formats from where they could be drawn and check out their relative standings

I am including some random plots to demonstrate the newly minted functions

Note 1: All plots are interactive. The controls are on the top right. You can hover over data, zoom-in, zoom-out, compare data etc by choosing the appropriate control. To know more about how to use the interactive charts see GooglyPlusPlus2021 is now fully interactive!!!

You can also check my short video on how to navigate interactive charts

Note 2: To know about Powerplay, Middle overs and Death over analysis see my post GooglyPlusPlus2021 now with power play, middle and death over analysis

Note 3: All tabs(except Match tab) now include Date range pickers to focus on the period of interest. See my post GooglyPlusPlus2021 enhanced with drill-down batsman, bowler analytics

I) Match tab

New Zealand vs Australia (2021-11-14)

New Zealand batting, except K Williamson, the rest did not fire as much

For Australia, Warner, Maxwell and Marsh played good knocks to wrest control

II) Head-to-head

a) Wickets vs ER during Power play of Mumbai Indians in all matches against Chennai Super Kings (IPL)

b) Karachi Kings Runs vs SR during middle overs against Multan Sultans (PSL)

c) Wickets vs ER during death overs of Barbados Tridents in all matches against Jamaica Tallawahs (CPL)

III) Teams overall batting performance

India’s best T20 performers in Power play since 2018 (Intl. T20)

e) Australia’s best performers in Death overs since Mar 2017 (Intl. T20)

f) India’s Intl. T20 (women) best Runs vs SR since 2018

g) England’s Intl. T20 (women) best bowlers in Death overs

IV) Overall Batting Performance across T20

This tab gives the batsmen’s rank and overall batting performance across the T20 format.

a) Why was Hardik Pandya chosen, and why this was in error?

Of course, it provides an insight into why Hardik Pandya was chosen in India’s World cup team despite poor performances recently. Here are the best Intl. T20 death over batsmen

Of course, we can zoom in to get a better look

This is further substantiated when we performances in IPL

However, if you move the needle forward a year at a time, you see Hardik Pandya’s performance drops significantly

and further down

Rather, Dinesh Karthik, Sanju Samson or Ruturaj Gaikwad would have been better options

b) Best batsmen Intl. T20 (women) in Power play since 2018

V) Overall bowling performance

This tab gives the bowler’s rank and overall bowling performance in Power play, middle and death overs across all T20 formats

a) Intl. T20 (men) best bowlers in Power Play from 2019 (zoomed in)

b) Intl. T20(men) best bowlers in Death overs since 2019

c) Was B. Kumar a good choice for India team in World cup?

Bhuvi was one of India’s best bowler in Power play only if we go back to the beginning of time

i) From 2008

But if we move forward to 2020 onwards we see Arshdeep Singh or D Chahar would have been a better choice

ii) From 2020 onwards

iii) 2021 onwards

Hence D Chahar & Arshdeep Singh are the natural choice moving forwards for India

iv) T20 Best batsman

If we look at Intl. T20 performances since 2017, Babar Azam leads the pack, however his Strike rate needs to move up.

v) T20 best bowlers

As mentioned above go ahead and give GooglyPlusPlus2021 a spin!!!

You can download/fork the code for the Shiny app from Github at gpp2021-10

Also see

  1. Introducing QCSimulator: A 5-qubit quantum computing simulator in R
  2. Deep Learning from first principles in Python, R and Octave – Part 6
  3. Deconstructing Convolutional Neural Networks with Tensorflow and Keras
  4. Big Data 6: The T20 Dance of Apache NiFi and yorkpy
  5. What’s up Watson? Using IBM Watson’s QAAPI with Bluemix, NodeExpress – Part 1
  6. Sea shells on the seashore
  7. Practical Machine Learning with R and Python – Part 4
  8. Benford’s law meets IPL, Intl. T20 and ODI cricket
  9. Video presentation on Machine Learning, Data Science, NLP and Big Data – Part 1
  10. How to program – Some essential tips

To see all posts click Index of posts