# GooglyPlusPlus: Computing T20 player’s Win Probability Contribution

In this post, I compute each batsman’s or bowler’s Win Probability Contribution (WPC) in a T20 match. This metric captures by how much the player (batsman or bowler) changed/impacted the Win Probability of the T20 match. For this computation I use my machine learning models, I had created earlier, which predicts the ball-by-ball win probability as the T20 match progresses through the 2 innings of the match.

In the picture snippet below, you can see how the win probability changes ball-by-ball for each batsman for a T20 match between CSK vs LSG- 31 Mar 2022

In my previous posts I had created several Machine Learning models. In order to compute the player’s Win Probability contribution in this post, I have used the following ML models

The batsman’s or bowler’s win probability contribution changes ball-by=ball. The player’s contribution is calculated as the difference in win probability when the batsman faces the 1st ball in his innings and the last ball either when is out or the innings comes to an end. If the difference is +ve the the player has had a positive impact, and likewise for negative contribution. Similarly, for a bowler, it is the win probability when he/she comes into bowl till, the last delivery he/she bowls

Note: The Win Probability Contribution does not have any relation to the how much runs or at what strike rate the batsman scored the runs. Rather the model computes different win probability for each player, based on his/her embedding, the ball in the innings and six other feature vectors like runs, run rate, runsMomentum etc. These values change for every ball as seen in the table above. Also, this is not continuous. The 2 ML models determine the Win Probability for a specific player, ball and the context in the match.

This metric is similar to Win Probability Added (WPA) used in Sabermetrics for baseball. Here is the definition of WPA from Fangraphs “Win Probability Added (WPA) captures the change in Win Expectancy from one plate appearance to the next and credits or debits the player based on how much their action increased their team’s odds of winning.” This article in Fangraphs explains in detail how this computation is done.

In this post I have added 4 new function to my R package yorkr.

• batsmanWinProbLR – batsman’s win probability contribution based on glmnet (Logistic Regression)
• bowlerWinProbLR – bowler’s win probability contribution based on glmnet (Logistic Regression)
• batsmanWinProbDL – batsman’s win probability contribution based on Deep Learning Model
• bowlerWinProbDL – bowlerWinProbLR – bowler’s win probability contribution based on Deep Learning

Hence there are 4 additional features in GooglyPlusPlus based on the above 4 functions. In addition I have also updated

-winProbLR (overLap) function to include the names of batsman when they come to bat and when they get out or the innings comes to an end, based on Logistic Regression

-winProbDL(overLap) function to include the names of batsman when they come to bat and when they get out based on Deep Learning

Hence there are 6 new features in this version of GooglyPlusPlus.

Note: All these new 6 features are available for all 9 formats of T20 in GooglyPlusPlus namely

a) IPL b) BBL c) NTB d) PSL e) Intl, T20 (men) f) Intl. T20 (women) g) WBB h) CSL i) SSM

Note: The data for GooglyPlusPlus comes from Cricsheet and the Shiny app is based on my R package yorkr

A) Chennai SuperKings vs Delhi Capitals – 04 Oct 2021

To understand Win Probability Contribution better let us look at Chennai Super Kings vs Delhi Capitals match on 04 Oct 2021

This was closely fought match with fortunes swinging wildly. If we take a look at the Worm wicket chart of this match

a) Worm Wicket chartCSK vs DC – 04 Oct 2021

Delhi Capitals finally win the match

b) Win Probability Logistic Regression (side-by-side) – CSK vs DC – 4 Oct 2021

Plotting how win probability changes over the course of the match using Logistic Regression Model

In this match Delhi Capitals won. The batting scorecard of Delhi Capitals

c) Batting Scorecard of Delhi Capitals – CSK vs DC – 4 Oct 2021

d) Win Probability Logistic Regression (Overlapping) – CSK vs DC – 4 Oct 2021

The Win Probability LR (overlapping) shows the probability function of both teams superimposed over one another. The plot includes when a batsman came into to play and when he got out. This is for both teams. This looks a little noisy, but there is a way to selectively display the change in Win Probability for each team. This can be done , by clicking the 3 arrows (orange or blue) from top to bottom. First double-click the team CSK or DC, then click the next 2 items (blue,red or black,grey) Sorry the legends don’t match the colors! 😦

Below we can see how the win probability changed for Delhi Capitals during their innings, as batsmen came into to play. See below

e) Batsman Win Probability contribution:DC – CSK vs DC – 4 Oct 2021

Computing the individual batsman’s Win Contribution and plotting we have. Hetmeyer has a higher Win Probability contribution than Shikhar Dhawan depsite scoring fewer runs

f) Bowler’s Win Probability contribution :CSK – CSK vs DC – 4 Oct 2021

We can also check the Win Probability of the bowlers. So for e.g the CSK bowlers and which bowlers had the most impact. Moeen Ali has the least impact in this match

B) Intl. T20 (men) Australia vs India – 25 Sep 2022

a) Worm wicket chart – Australia vs India – 25 Sep 2022

This was another close match in which India won with the penultimate ball

b) Win Probability based on Deep Learning model (side-by-side) – Australia vs India – 25 Sep 2022

c) Win Probability based on Deep Learning model (overlapping) – Australia vs India – 25 Sep 2022

The plot below shows how the Win Probability of the teams varied across the 20 overs. The 2 Win Probability distributions are superimposed over each other

d) Batsman Win Probability Contribution : IndiaAustralia vs India – 25 Sep 2022

Selectively choosing the India Win Probability plot by double-clicking legend ‘India’ on the right , followed by single click of black, grey legend we have

We see that Kohli, Suryakumar Yadav have good contribution to the Win Probability

e) Plotting the Runs vs Strike Rate:India – Australia vs India – 25 Sep 2022

f) Batsman’s Win Probability Contribution- Australia vs India – 25 Sep 2022

Finally plotting the Batsman’s Win Probability Contribution

Interestingly, Kohli has a greater Win Probability Contribution than SKY, though SKY scored more runs at a better strike rate. As mentioned above, the Win Probability is context dependent and also depends on past performances of the player (batsman, bowler)

Finally let us look at

C) India vs England Intll T20 Women (11 July 2021)

a) Worm wicket chart – India vs England Intl. T20 Women (11 July 2021)

India won this T20 match by 8 runs

b) Win Probability using the Logistic Regression Model – India vs England Intl. T20 Women (11 July 2021)

c) Win Probability with the DL model – India vs England Intl. T20 Women (11 July 2021)

d) Bowler Win Probability Contribution with the LR model India vs England Intl. T20 Women (11 July 2021)

e) Bowler Win Contribution with the DL model India vs England Intl. T20 Women (11 July 2021)

Also see my other posts

To see all posts click Index of posts

# T20 Win Probability using CTGANs, synthetic data

This should be my last post on computing T20 Win Probability. In this post I compute Win Probability using Augmented Data with the help of Conditional Tabular Generative Adversarial Networks (CTGANs).

A.Introduction

I started the computation of T20 match Win Probability in my earlier post

a) ‘Computing Win-Probability of T20 matches‘ where I used

• vanilla Logistic Regression to get an accuracy of 0.67,
• Random Forest with Tidy models gave me an accuracy of 0.737
• Deep Learning with Keras also with 0.73.

This was done without player embeddings

b) Next I used player embeddings for batsmen and bowlers in my post Boosting Win Probability accuracy with player embeddings , and my accuracies improved significantly

• 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

c) Third I tried using Deep Learning with Keras using player embeddings

• DL network gave an accuracy of 0.8639

This was lightweight and could be easily deployed in my Shiny GooglyPlusPlus app as opposed to the Tidymodel’s Random Forest, which was bulky and slow.

d) Finally I decided to try and improve the accuracy of my Deep Learning Model using Synthetic data. Towards this end, my explorations led me to Conditional Tabular Generative Adversarial Networks (CTGANs). CTGAN are GAN networks that can be used with Tabular data as GAN models are not useful with tabular data. However, the best performance I got for

• DL Keras Model + Synthetic data : accuracy =0.77

The poorer accuracy was because CTGAN requires enormous computing power (GPUs) and RAM. The free version of Colab, Kaggle kept crashing when I tried with even 0.1 % of my 1.2 million dataset size. Finally, I tried with just 0.05% and was able to generate synthetic data. Most likely, it is the small sample size and the smaller number of epochs could be the reason for the poor result. In any case, it was worth trying and this approach would possibly work with sufficient computing resources.

Generative Adversarial Networks (GANs) was the brain child of Ian Goodfellow who demonstrated it in 2014. GANs are capable of generating synthetic text, tables, images, videos using available data. In Adversarial nets framework, the generative model is pitted against an adversary: a
discriminative model that learns to determine whether a sample is from the model distribution or the
data distribution.

GANs have 2 Deep Neural Networks , the Generator and Discriminator which compete against other

• The Generator (Counterfeiter) takes random noise as input and generates fake images, tables, text. The generator learns to generate plausible data. The generated instances become negative training examples for the discriminator.
• The Discriminator (Police) which tries to distinguish between the real and fake images, text. The discriminator learns to distinguish the generator’s fake data from real data. The discriminator penalises the generator for producing implausible results.

A pictorial representation of the GAN model can be shown below

Theoretically best performance of GANs are supposed to happen when the network reaches the ‘Nash equilibrium‘, i.e. when the Generator produces near fake images and the Discriminator’s loss is f ~0.5 i.e. the discriminator is unable to distinguish between real and fake images.

Note: Though I have mentioned T20 data in the above GAN model, the T20 tabular data is actually used in CTGAN which is slightly different from the above. See Reference 2) below.

C. Conditional Tabular Generative Adversial Networks (CTGANs)

“Modeling the probability distribution of rows in tabular data and generating realistic synthetic data is a non-trivial task. Tabular data usually contains a mix of discrete and continuous columns. Continuous columns may have multiple modes whereas discrete columns are sometimes imbalanced making the modeling difficult.” CTGANs handle these challenges.

I came upon CTGAN after spending some time exploring GANs via blogs, videos etc. For building the model I use real T20 match data. However, CTGAN requires immense raw computing power and a lot of RAM. My initial attempts on Colab, my Mac (12 core, 32GB RAM), took forever before eventually crashing, I switched to Kaggle and used GPUs. Still I was only able to use only a miniscule part of my T20 dataset. My match data has 1.2 million rows, hoanything > 0.05% resulted in Kaggle crashing. Since I was able to use only a fraction, I executed the CTGAN model over several iterations, each iteration with a random 0.05% sample of the dataset. At the end of each iterations I also generate synthetic dataset. Over 12 iterations, I generate close 360K of ‘synthetic‘ T20 match data.

I then augment the 1.2 million rows of ‘real‘ T20 match data with the generated ‘synthetic T20 match data to run my Deep Learning model

D. Executing the CTGAN model

a. Read the real T20 match data

!pip install ctgan
import pandas as pd
import ctgan
from ctgan import CTGAN
from numpy.random import seed

# Read the T20 match data

# Randomly sample 0.05% of the dataset. Note larger datasets cause the algo to crash
train_dataset = df.sample(frac=0.05)

# Print the real T20 match data
print(train_dataset.shape)

batsmanIdx  bowlerIdx  ballNum  ballsRemaining  runs   runRate  \
363695         3333        432      134             119   153  1.285714
1082839        3881       1180      218              30    93  3.100000
595799         2366        683      187              65   120  1.846154
737614         4490       1381      148              87   144  1.655172
410202          934       1003       19             106    35  1.842105
525627          921       1711      251               1     8  8.000000
657669         4718       1602      130             115   145  1.260870
666461         4309       1989       44              87    38  0.863636
651229         3336        754       30              92    36  1.200000
709892         3048        421       97              28   119  1.226804

numWickets  runsMomentum  perfIndex  isWinner
363695            0      0.092437  18.333333         1
1082839           5      0.200000   4.736842         0
595799            4      0.107692   9.566667         0
737614            1      0.114943   9.130435         1
410202            0      0.103774  20.263158         0
525627            8      3.000000   3.837209         0
657669            0      0.095652  19.555556         0
666461            0      0.126437   9.500000         0
651229            0      0.119565  13.200000         0
709892            3      0.285714   9.814433         1
(59956, 10)

b. Run CTGAN model on the real T20 data

import pandas as pd
import ctgan
from ctgan import CTGAN
from numpy.random import seed
from pickle import TRUE

#Specify the categorical features. batsmanIdx & bowlerIdx are player embeddings
categorical_features = ['batsmanIdx','bowlerIdx']

# Create a empty dataframe for synthetic data
df1 = pd.DataFrame()

# Loop for 12 iterations. Minimize generator & discriminator loss
for i in range(12):
print(i)
train_dataset = df.sample(frac=0.05)
seed(33)

ctgan = CTGAN(epochs=20,verbose=True,generator_lr=.001,discriminator_lr=.001,batch_size=1000)
ctgan.fit(train_dataset, categorical_features)

# Generate synthetic data
samples = ctgan.sample(30000)

# Concatenate the synthetic data after each iteration
df1 = pd.concat([df1,samples])
print(df1.shape)

# Output the synthetic data to file
df1.to_csv("output1.csv",index=False)

0
Epoch 1, Loss G:  8.3825,Loss D: -0.6159
Epoch 2, Loss G:  3.5117,Loss D: -0.3016
Epoch 3, Loss G:  2.1619,Loss D: -0.5713
Epoch 4, Loss G:  0.9847,Loss D:  0.1010
Epoch 5, Loss G:  0.6198,Loss D:  0.0789
Epoch 6, Loss G:  0.1710,Loss D:  0.0959
Epoch 7, Loss G:  0.3236,Loss D: -0.1554
Epoch 8, Loss G:  0.2317,Loss D: -0.0765
Epoch 9, Loss G: -0.0127,Loss D:  0.0275
Epoch 10, Loss G:  0.1477,Loss D: -0.0353
Epoch 11, Loss G:  0.0997,Loss D: -0.0129
Epoch 12, Loss G:  0.0066,Loss D: -0.0486
Epoch 13, Loss G:  0.0351,Loss D: -0.0805
Epoch 14, Loss G: -0.1399,Loss D: -0.0021
Epoch 15, Loss G: -0.1503,Loss D: -0.0518
Epoch 16, Loss G: -0.2306,Loss D: -0.0234
Epoch 17, Loss G: -0.2986,Loss D:  0.0469
Epoch 18, Loss G: -0.1941,Loss D: -0.0560
Epoch 19, Loss G: -0.3794,Loss D:  0.0000
Epoch 20, Loss G: -0.2763,Loss D:  0.0368
batsmanIdx  bowlerIdx  ballNum  ballsRemaining  runs   runRate  numWickets  \
0         906        224        8              75    81  1.955153           4
1        4159        433       17              31   126  1.799280           9
2         229        351      192              66    82  1.608527           5
3        1926        962       63               0   117  1.658105           0
4         286        431      128               1    36  1.605079           0

runsMomentum  perfIndex  isWinner
0      0.146670   6.937595         1
1      0.160534  10.904346         1
2      0.516010  11.698128         1
3      0.380986  11.914613         0
4      0.112255   5.392120         0
(30000, 10)
1
Epoch 1, Loss G:  7.9977,Loss D: -0.3592
Epoch 2, Loss G:  3.7418,Loss D: -0.3371
Epoch 3, Loss G:  1.6685,Loss D: -0.3211
Epoch 4, Loss G:  1.0539,Loss D: -0.3495
Epoch 5, Loss G:  0.4664,Loss D: -0.0907
Epoch 6, Loss G:  0.4004,Loss D: -0.1208
Epoch 7, Loss G:  0.3250,Loss D: -0.1482
Epoch 8, Loss G:  0.1753,Loss D:  0.0169
Epoch 9, Loss G:  0.1382,Loss D:  0.0661
Epoch 10, Loss G:  0.1509,Loss D: -0.1023
Epoch 11, Loss G: -0.0235,Loss D:  0.0210
Epoch 12, Loss G: -0.1636,Loss D: -0.0124
Epoch 13, Loss G: -0.3370,Loss D: -0.0185
Epoch 14, Loss G: -0.3054,Loss D: -0.0085
Epoch 15, Loss G: -0.5142,Loss D:  0.0121
Epoch 16, Loss G: -0.3813,Loss D: -0.0921
Epoch 17, Loss G: -0.5838,Loss D:  0.0210
Epoch 18, Loss G: -0.4033,Loss D: -0.0181
Epoch 19, Loss G: -0.5711,Loss D:  0.0269
Epoch 20, Loss G: -0.4828,Loss D: -0.0830
batsmanIdx  bowlerIdx  ballNum  ballsRemaining  runs   runRate  numWickets  \
0        2202        265      223              39    13  0.868927           0
1        3641        856       35              59    26  2.236160           6
2         676       2903      218              93    16  0.460693           1
3        3482       3459       44             117   102  0.851471           8
4        3046       3076       59               5    84  1.016824           2

runsMomentum  perfIndex  isWinner
0      0.138586   4.733462         0
1      0.124453   5.146831         1
2      0.273168  10.106869         0
3      0.129520   5.361127         0
4      1.083525  25.677574         1
(60000, 10)
...
...
11
Epoch 1, Loss G:  8.8362,Loss D: -0.7111
Epoch 2, Loss G:  4.1322,Loss D: -0.8468
Epoch 3, Loss G:  1.2782,Loss D:  0.1245
Epoch 4, Loss G:  1.1135,Loss D: -0.3588
Epoch 5, Loss G:  0.6033,Loss D: -0.1255
Epoch 6, Loss G:  0.6912,Loss D: -0.1906
Epoch 7, Loss G:  0.3340,Loss D: -0.1048
Epoch 8, Loss G:  0.3515,Loss D: -0.0730
Epoch 9, Loss G:  0.1702,Loss D:  0.0237
Epoch 10, Loss G:  0.1064,Loss D:  0.0632
Epoch 11, Loss G:  0.0884,Loss D: -0.0005
Epoch 12, Loss G:  0.0556,Loss D: -0.0607
Epoch 13, Loss G: -0.0917,Loss D: -0.0223
Epoch 14, Loss G: -0.1492,Loss D:  0.0258
Epoch 15, Loss G: -0.0986,Loss D: -0.0112
Epoch 16, Loss G: -0.1428,Loss D: -0.0060
Epoch 17, Loss G: -0.2225,Loss D: -0.0263
Epoch 18, Loss G: -0.2255,Loss D: -0.0328
Epoch 19, Loss G: -0.3482,Loss D:  0.0277
Epoch 20, Loss G: -0.2667,Loss D: -0.0721
batsmanIdx  bowlerIdx  ballNum  ballsRemaining  runs   runRate  numWickets  \
0         367       1447      129              27    30  1.242120           2
1        2481       1528      221               4    10  1.344024           2
2        1034       3116      132              87   153  1.142750           3
3        1201       2868      151              60   136  1.091638           1
4        4327       3291      108              89    22  0.842775           2

runsMomentum  perfIndex  isWinner
0      1.978739   6.393691         1
1      0.539650   6.783990         0
2      0.107156  12.154197         0
3      3.193574  11.992059         0
4      0.127507  12.210876         0
(360000, 10)

E. Sample of the Synthetic data

synthetic_data = ctgan.sample(20000)

batsmanIdx  bowlerIdx  ballNum  ballsRemaining  runs    runRate  \
0         1073       3059       72              72   149   2.230236
1         3769       1443      106               7   137   0.881409
2          448       3048      166               6   220   1.092504
3         2969       1244      103              82   207  12.314862
4          180       1372      125             111    14   1.310051
..         ...        ...      ...             ...   ...        ...
95        1521       1040      153               6   166   1.097363
96        2366         62       25             114   119   0.910642
97        3506       1736      100             118   140   1.640921
98        3343       2347       47              54    50   0.696462
99        1957       2888      136              27   153   1.315565

numWickets  runsMomentum  perfIndex  isWinner
0            0      0.111707  17.466925         0
1            1      0.130352  14.274113         0
2            1      0.173541  11.076731         1
3            1      0.218977   6.239951         0
4            4      2.829380   9.183323         1
..         ...           ...        ...       ...
95           0      0.223437   7.011180         0
96           1      0.451371  16.908120         1
97           5      0.156936   9.217205         0
98           6      0.124536   6.273091         0
99           1      0.249329  14.221554         0

[100 rows x 10 columns]

F. Evaluating the synthetic T20 match data

Here the quality of the synthetic data set is evaluated.

a) Statistical evaluation

• Read the real T20 match data
• Read the generated T20 synthetic match data
import pandas as pd

# Read the T20 match and synthetic match data
df = pd.read_csv('/kaggle/input/cricket1/t20.csv').  #1.2 million rows

# Randomly sample 1000 rows, and generate stats
df1=df.sample(n=1000)
real=df1.describe()
realData_stats=real.transpose
print(realData_stats)

synthetic1=synthetic.sample(n=1000)
synthetic=synthetic1.describe()
syntheticData_stats=synthetic.transpose
syntheticData_stats

a) Stats of real T20 match data

<bound method DataFrame.transpose of         batsmanIdx    bowlerIdx      ballNum  ballsRemaining         runs  \
count  1000.000000  1000.000000  1000.000000     1000.000000  1000.000000
mean   2323.940000  1776.481000   118.165000       59.236000    77.649000
std    1329.703046  1011.470703    70.564291       35.312934    49.098763
min       8.000000    13.000000     1.000000        1.000000    -2.000000
25%    1134.750000   850.000000    58.000000       28.750000    39.000000
50%    2265.000000  1781.500000   117.000000       59.000000    72.000000
75%    3510.000000  2662.250000   178.000000       89.000000   111.000000
max    4738.000000  3481.000000   265.000000      127.000000   246.000000

runRate   numWickets  runsMomentum    perfIndex     isWinner
count  1000.000000  1000.000000   1000.000000  1000.000000  1000.000000
mean      1.734979     2.614000      0.310568     9.580386     0.499000
std       5.698104     2.267189      0.686171     4.530856     0.500249
min      -2.000000     0.000000      0.071429     0.000000     0.000000
25%       1.009063     1.000000      0.105769     6.666667     0.000000
50%       1.272727     2.000000      0.141026     9.236842     0.000000
75%       1.546891     4.000000      0.250000    12.146735     1.000000
max     166.000000    10.000000     10.000000    30.800000     1.000000

b) Stats of Synthetic T20 match data


batsmanIdx    bowlerIdx      ballNum  ballsRemaining         runs  \
count  1000.000000  1000.000000  1000.000000     1000.000000  1000.000000
mean   2304.135000  1760.776000   116.081000       50.102000    74.357000
std    1342.348684  1003.496003    72.019228       35.795236    48.103446
min       2.000000    15.000000    -4.000000       -2.000000    -1.000000
25%    1093.000000   881.000000    46.000000       18.000000    30.000000
50%    2219.500000  1763.500000   116.000000       45.000000    75.000000
75%    3496.500000  2644.750000   180.250000       77.000000   112.000000
max    4718.000000  3481.000000   253.000000      124.000000   222.000000

runRate   numWickets  runsMomentum    perfIndex     isWinner
count  1000.000000  1000.000000   1000.000000  1000.000000  1000.000000
mean      1.637225     3.096000      0.336540     9.278073     0.507000
std       1.691060     2.640408      0.502346     4.727677     0.500201
min      -4.388339     0.000000      0.083351    -0.902991     0.000000
25%       1.077789     1.000000      0.115770     5.731931     0.000000
50%       1.369655     2.000000      0.163085     9.104328     1.000000
75%       1.660477     5.000000      0.311586    12.619318     1.000000
max      23.757001    10.000000      4.630908    29.829497     1.000000

c) Plotting the Generator and Discriminator loss

import pandas as pd

# CTGAN prints out a new line for each epoch
epochs_output = str(output).split('\n')

# CTGAN separates the values with commas
raw_values = [line.split(',') for line in epochs_output]
loss_values = pd.DataFrame(raw_values)[:-1] # convert to df and delete last row (empty)

# Rename columns
loss_values.columns = ['Epoch', 'Generator Loss', 'Discriminator Loss']

# Extract the numbers from each column
loss_values['Epoch'] = loss_values['Epoch'].str.extract('(\d+)').astype(int)
loss_values['Generator Loss'] = loss_values['Generator Loss'].str.extract('([-+]?\d*\.\d+|\d+)').astype(float)
loss_values['Discriminator Loss'] = loss_values['Discriminator Loss'].str.extract('([-+]?\d*\.\d+|\d+)').astype(float)

# the result is a row for each epoch that contains the generator and discriminator loss
loss_values.head()

	Epoch	Generator Loss	Discriminator Loss
0	1	8.0158	-0.3840
1	2	4.6748	-0.9589
2	3	1.1503	-0.0066
3	4	1.5593	-0.8148
4	5	0.6734	-0.1425
5	6	0.5342	-0.2202
6	7	0.4539	-0.1462
7	8	0.2907	-0.0155
8	9	0.2399	0.0172
9	10	0.1520	-0.0236
import plotly.graph_objects as go

# Plot loss function
fig = go.Figure(data=[go.Scatter(x=loss_values['Epoch'], y=loss_values['Generator Loss'], name='Generator Loss'),
go.Scatter(x=loss_values['Epoch'], y=loss_values['Discriminator Loss'], name='Discriminator Loss')])

# Update the layout for best viewing
fig.update_layout(template='plotly_white',
legend_orientation="h",
legend=dict(x=0, y=1.1))

title = 'CTGAN loss function for T20 dataset - '
fig.update_layout(title=title, xaxis_title='Epoch', yaxis_title='Loss')
fig.show()

G. Qualitative evaluation of Synthetic data

a) Quality of continuous columns in synthetic data

KSComplement -This metric computes the similarity of a real column vs. a synthetic column in terms of the column shapes.The KSComplement uses the Kolmogorov-Smirnov statistic. Closer to 1.0 is good and 0 is worst

from sdmetrics.single_column import KSComplement
numerical_columns=['ballNum','ballsRemaining','runs','runRate','numWickets','runsMomentum','perfIndex']
total_score = 0
for column_name in numerical_columns:
column_score = KSComplement.compute(df[column_name], synthetic[column_name])
total_score += column_score
print('Column:', column_name, ', Score: ', column_score)

print('\nAverage: ', total_score/len(numerical_columns))

Column: ballNum , Score:  0.9502754283367316
Column: ballsRemaining , Score:  0.8770284103276166
Column: runs , Score:  0.9136464248633367
Column: runRate , Score:  0.9183841670732166
Column: numWickets , Score:  0.9016209114638712
Column: runsMomentum , Score:  0.8773491702213716
Column: perfIndex , Score:  0.9173808852778924

Average:  0.9079550567948624

b) Quality of categorical columns

This statistic measures the quality of generated categorical columns. 1 is best and 0 is worst

categorical_columns=['batsmanIdx','bowlerIdx']
from sdmetrics.single_column import TVComplement

total_score = 0
for column_name in categorical_columns:
column_score = TVComplement.compute(df[column_name], synthetic[column_name])
total_score += column_score
print('Column:', column_name, ', Score: ', column_score)

print('\nAverage: ', total_score/len(categorical_columns))

Column: batsmanIdx , Score:  0.8436263499539245
Column: bowlerIdx , Score:  0.7356177407921669

Average:  0.7896220453730457

The performance is decent but not excellent. I was unable to execute more epochs as it it required larger than the memory allowed

c) Correlation similarity

This metric measures the correlation between a pair of numerical columns and computes the similarity between the real and synthetic data – it compares the trends of 2D distributions. Best 1.0 and 0.0 is worst

import itertools
from sdmetrics.column_pairs import CorrelationSimilarity

total_score = 0
total_pairs = 0
for pair in itertools.combinations(numerical_columns,2):
col_A, col_B = pair
score = CorrelationSimilarity.compute(df[[col_A, col_B]], synthetic[[col_A, col_B]])
print('Columns:', pair, ' Score:', score)
total_score += score
total_pairs += 1

print('\nAverage: ', total_score/total_pairs)

Columns: ('ballNum', 'ballsRemaining')  Score: 0.7153942317384889
Columns: ('ballNum', 'runs')  Score: 0.8838043045134777
Columns: ('ballNum', 'runRate')  Score: 0.8710243133637056
Columns: ('ballNum', 'numWickets')  Score: 0.7978515509750435
Columns: ('ballNum', 'runsMomentum')  Score: 0.8956281260834316
Columns: ('ballNum', 'perfIndex')  Score: 0.9275145840528048
Columns: ('ballsRemaining', 'runs')  Score: 0.9566928975064546
Columns: ('ballsRemaining', 'runRate')  Score: 0.9127313819127167
Columns: ('ballsRemaining', 'numWickets')  Score: 0.6770737279315224
Columns: ('ballsRemaining', 'runsMomentum')  Score: 0.7939260278412358
Columns: ('ballsRemaining', 'perfIndex')  Score: 0.8694582252638351
Columns: ('runs', 'runRate')  Score: 0.999593795992159
Columns: ('runs', 'numWickets')  Score: 0.9510731832916608
Columns: ('runs', 'runsMomentum')  Score: 0.9956131422133428
Columns: ('runs', 'perfIndex')  Score: 0.9742931845536701
Columns: ('runRate', 'numWickets')  Score: 0.8859830711832263
Columns: ('runRate', 'runsMomentum')  Score: 0.9174744874779561
Columns: ('runRate', 'perfIndex')  Score: 0.9491100087911353
Columns: ('numWickets', 'runsMomentum')  Score: 0.8989709776329797
Columns: ('numWickets', 'perfIndex')  Score: 0.7178946968801441
Columns: ('runsMomentum', 'perfIndex')  Score: 0.9744441623018661

Average:  0.8840738134048025

d) Category coverage

This metric measures whether a synthetic column covers all the possible categories that are present in a real column. 1.0 is best , 0 is worst

from sdmetrics.single_column import CategoryCoverage

total_score = 0
for column_name in categorical_columns:
column_score = CategoryCoverage.compute(df[column_name], synthetic[column_name])
total_score += column_score
print('Column:', column_name, ', Score: ', column_score)

print('\nAverage: ', total_score/len(categorical_columns))

Column: batsmanIdx , Score:  0.9533951919021509
Column: bowlerIdx , Score:  0.9913966160022942

Average:  0.9723959039522225

H. Augmenting the T20 match data set

In this final part I augment my T20 match data set with the generated synthetic T20 data set.

import pandas as pd
from numpy import savetxt
import tensorflow as tf
from tensorflow import keras
import pandas as pd
import numpy as np

from keras.layers import Input, Embedding, Flatten, Dense, Reshape, Concatenate, Dropout
from keras.models import Model
import matplotlib.pyplot as plt

# Read real and synthetic data

# Augment the data. Concatenate real & synthetic data
df1=pd.concat([df,synthetic])

# Create training and test samples
print("Shape of dataframe=",df1.shape)
train_dataset = df1.sample(frac=0.8,random_state=0)
test_dataset = df1.drop(train_dataset.index)
train_dataset1 = train_dataset[['batsmanIdx','bowlerIdx','ballNum','ballsRemaining','runs','runRate','numWickets','runsMomentum','perfIndex']]
test_dataset1 = test_dataset[['batsmanIdx','bowlerIdx','ballNum','ballsRemaining','runs','runRate','numWickets','runsMomentum','perfIndex']]
train_dataset1
train_labels = train_dataset.pop('isWinner')
test_labels = test_dataset.pop('isWinner')
print(train_dataset1.shape)

a=train_dataset1.describe()
stats=a.transpose
print(a)

a) Create A Deep Learning Model in Keras

from numpy.random import seed
seed(33)
tf.random.set_seed(432)
# create input layers for each of the predictors
batsmanIdx_input = Input(shape=(1,), name='batsmanIdx')
bowlerIdx_input = Input(shape=(1,), name='bowlerIdx')
ballNum_input = Input(shape=(1,), name='ballNum')
ballsRemaining_input = Input(shape=(1,), name='ballsRemaining')
runs_input = Input(shape=(1,), name='runs')
runRate_input = Input(shape=(1,), name='runRate')
numWickets_input = Input(shape=(1,), name='numWickets')
runsMomentum_input = Input(shape=(1,), name='runsMomentum')
perfIndex_input = Input(shape=(1,), name='perfIndex')

no_of_unique_batman=len(df1["batsmanIdx"].unique())
print(no_of_unique_batman)
no_of_unique_bowler=len(df1["bowlerIdx"].unique())
print(no_of_unique_bowler)

embedding_size_bat = no_of_unique_batman ** (1/4)
print(embedding_size_bat)
embedding_size_bwl = no_of_unique_bowler ** (1/4)
print(embedding_size_bwl)

# create embedding layer for the categorical predictor
batsmanIdx_embedding = Embedding(input_dim=no_of_unique_batman+1, output_dim=16,input_length=1)(batsmanIdx_input)
print(batsmanIdx_embedding)
batsmanIdx_flatten = Flatten()(batsmanIdx_embedding)
print(batsmanIdx_flatten)
bowlerIdx_embedding = Embedding(input_dim=no_of_unique_bowler+1, output_dim=16,input_length=1)(bowlerIdx_input)
bowlerIdx_flatten = Flatten()(bowlerIdx_embedding)
print(bowlerIdx_flatten)
# concatenate all the predictors
x = keras.layers.concatenate([batsmanIdx_flatten,bowlerIdx_flatten, ballNum_input, ballsRemaining_input, runs_input, runRate_input, numWickets_input, runsMomentum_input, perfIndex_input])
print(x.shape)
x = Dense(96, activation='relu')(x)
x = Dropout(0.1)(x)
x = Dense(64, activation='relu')(x)
x = Dropout(0.1)(x)
x = Dense(32, activation='relu')(x)
x = Dropout(0.1)(x)
x = Dense(16, activation='relu')(x)
x = Dropout(0.1)(x)
x = Dense(8, activation='relu')(x)
x = Dropout(0.1)(x)
output = Dense(1, activation='sigmoid', name='output')(x)
print(output.shape)
# create model
model = Model(inputs=[batsmanIdx_input,bowlerIdx_input, ballNum_input, ballsRemaining_input, runs_input, runRate_input, numWickets_input, runsMomentum_input, perfIndex_input], outputs=output)
model.summary()
# compile model
#optimizer=keras.optimizers.RMSprop(learning_rate=0.001, rho=0.2, momentum=0.2, epsilon=1e-07)
#optimizer=keras.optimizers.SGD(learning_rate=.01,momentum=0.1) #- Works without dropout
#optimizer = tf.keras.optimizers.RMSprop(0.01)
#optimizer=keras.optimizers.SGD(learning_rate=.01,momentum=0.1)
#optimizer=keras.optimizers.RMSprop(learning_rate=.005, rho=0.1, momentum=0, epsilon=1e-07)

model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])

# train the model
history=model.fit([train_dataset1['batsmanIdx'],train_dataset1['bowlerIdx'],train_dataset1['ballNum'],train_dataset1['ballsRemaining'],train_dataset1['runs'],
train_dataset1['runRate'],train_dataset1['numWickets'],train_dataset1['runsMomentum'],train_dataset1['perfIndex']], train_labels, epochs=20, batch_size=1024,
validation_data = ([test_dataset1['batsmanIdx'],test_dataset1['bowlerIdx'],test_dataset1['ballNum'],test_dataset1['ballsRemaining'],test_dataset1['runs'],
test_dataset1['runRate'],test_dataset1['numWickets'],test_dataset1['runsMomentum'],test_dataset1['perfIndex']],test_labels), verbose=1)

plt.plot(history.history["loss"])
plt.plot(history.history["val_loss"])
plt.title("model loss")
plt.ylabel("loss")
plt.xlabel("epoch")
plt.legend(["train", "test"], loc="upper left")
plt.show()

==================================================================================================
Total params: 144,497
Trainable params: 144,497
Non-trainable params: 0
__________________________________________________________________________________________________
Epoch 1/20
1219/1219 [==============================] - 15s 11ms/step - loss: 0.6285 - accuracy: 0.6372 - val_loss: 0.5164 - val_accuracy: 0.7606
Epoch 2/20
1219/1219 [==============================] - 14s 11ms/step - loss: 0.5594 - accuracy: 0.7121 - val_loss: 0.4920 - val_accuracy: 0.7663
Epoch 3/20
1219/1219 [==============================] - 14s 12ms/step - loss: 0.5338 - accuracy: 0.7244 - val_loss: 0.4541 - val_accuracy: 0.7878
Epoch 4/20
1219/1219 [==============================] - 14s 11ms/step - loss: 0.5176 - accuracy: 0.7317 - val_loss: 0.4226 - val_accuracy: 0.7933
Epoch 5/20
1219/1219 [==============================] - 13s 11ms/step - loss: 0.4966 - accuracy: 0.7420 - val_loss: 0.4547 - val_accuracy: 0.7
...
...
poch 18/20
1219/1219 [==============================] - 14s 11ms/step - loss: 0.4300 - accuracy: 0.7747 - val_loss: 0.3536 - val_accuracy: 0.8288
Epoch 19/20
1219/1219 [==============================] - 14s 12ms/step - loss: 0.4269 - accuracy: 0.7766 - val_loss: 0.3565 - val_accuracy: 0.8302
Epoch 20/20
1219/1219 [==============================] - 14s 11ms/step - loss: 0.4259 - accuracy: 0.7775 - val_loss: 0.3498 - val_accuracy: 0.831

As can be seen the accuracy with augmented dataset is around 0.77, while without it I was getting 0.867 with just the real data. This degradation is probably due to the folllowing reasons

• Only a fraction of the dataset was used for training. This was not representative of the data distribution for CTGAN to correctly synthesise data
• The number of epochs had to be kept low to prevent Kaggle/Colab from crashing

I. Conclusion

This post shows how we can generate synthetic T20 match data to augment real T20 match data. Assuming we have sufficient processing power we should be able to generate synthetic data for augmenting our data set. This should improve the accuracy of the Win Probabily Deep Learning model.

References

Also see

To see all posts click Index of posts

# Near Real-time Analytics of ICC Men’s T20 World Cup with GooglyPlusPlus

In my last post GooglyPlusPlus gets ready for ICC Men’s T20 World Cup, I had mentioned that GooglyPlusPlus was preparing for the big event the ICC Men’s T20 World cup. Now that the T20 World cup is underway, my Shiny app in R, GooglyPlusPlus ,will be generating near real-time analytics of matches completed the previous day. Besides the app can also do historical analysis of players, teams and matches.

The whole process is automated. A cron job will execute every day, in the morning, which will automatically download the matches of the previous day from Cricsheet, unzip them, start a pipeline which will transform and process the match data into necessary folders and finally upload the newly acquired data into my Shiny app. Hence, you will be able to access all the breathless, pulsating cricketing action in timeless, interactive plots and tables which will capture all aspects of Men’s T20 matches, namely batsman, bowler performance, match analysis, team-vs-team, team-vs-all teams besides ranking of batsmen & bowlers. Since the data is cumulative, all the analytics are historical and current.

Check out GooglyPlusPlus!!

The data for GooglyPlusPlus is taken from Cricsheet

Interest in cricket, has mushroomed in recent times around the world, with the addition of new formats which started with ODI, T20, T10, 100 ball and so on. There are leagues which host these matches at different levels around the world. While GooglyPlusPlus, provides near real-time analytics of Men’s T20 World cup, we can clearly envision a big data platform which ingests matches daily from multiple cricket formats, leagues around the world generating real-time and near real-time analytics which are essential these days to selection of teams at different levels through auctions. For more discussion on this see my posts

We could imagine a Data Lake, into which are ingested data from the different cricket formats, leagues through appropriate technology connectors. Once the data is ingested, we could have data pipelines, based on Azure ADF, Apache NiFi, Apache Airflow or Amazon EMR etc., to transform, process and enhance the data, generating real-time analytics on the fly. Recent formats like T20, T10 require more urgency in strategic thinking based on scoring within limited overs, or containing batsmen from going on a rampage within the set of overs, the analytics on a fly may help the coach to modify the batting or bowling lineup at points in match. In this context see my earlier post Using Linear Programming (LP) for optimizing bowling change or batting lineup in T20 cricket

All of these are not just possible, but are likely to become reality as more and more formats, leagues and cricket data proliferate around the world.

This post, focuses on generating near-real time analytics for ICC Men’s T20 World Cup using GooglyPlusPlus. Included below, is a sampling of the analytics that you can perform for analysing the matches. In addition you can do all the analysis included in my post GooglyPlusPlus gets ready for ICC Men’s T20 World Cup

1. Namibia-Sri Lanka-16 Oct 2022 : Match Worm graph

The opening match between Namibia vs Sri Lanka resulted in an upset. We can see this in the match worm-wicket graph below

2. Scotland vs West Indies – 17 Oct 2022: Batsmen vs Bowlers

George Munsey was the top scorer for Scotland and was instrumental in the win against WI. His performance against West Indies bowlers is shown below. Note, the charts are interactive

3. Zimbabwe vs Ireland – 17 Oct 2022 : Team Runs vs SR

Sikander Raza of Zimbabwe with 82 runs with the strike rate ~ 170

4. United Arab Emirates vs Netherlands – 16 Oct 2022: Team runs across 20 overs

UAE pipped Netherlands in the middle overs and were able to win by 1 ball and 3 wickets

5. Scotland vs Ireland – 19 Oct 2022 : Team Runs vs SR Middle overs plot

Curtis Campher snatched the game away from Scotland with his stellar performance in middle and death overs

6. UAE vs Namibia : 20 Oct 2022 : Team Wickets vs ER plot

Basoor Hameed and Zahoor Khan got 2 wickets apiece with an economy rate of ~5.00 but still they were not able to stop UAE from stealing a win

7. Overall Runs vs SR in T20 World Cup 2022

It is too early to rank the players, nevertheless in the current T20 World Cup, MP O’Dowd (Netherlands), BKG Mendis (Sri Lanka) and JN Frylinck(Namibia) are the top 3 batsmen with good runs and Strike Rate

8. Overall Wickets over ER in T20 World Cup 2022

The top 3 bowlers so far in T20 World Cup 2022 are a) BFW de Leede (Netherlands) b) PWH De Silva (Sri Lanka) c) KP Meiyappan (UAE) with a total of 7,7, and 6 wickets respectively

Note: Besides the match analysis GooglyPlusPlus also provides detailed analysis of batsmen, bowlers, matches as above, team-vs-team, team-vs-all teams, ranking of batsmen & bowlers etc. For more details see my post GooglyPlusPlus gets ready for ICC Men’s T20 World Cup

Do visit GooglyPlusPlus everyday to check out the cricketing actions of matches gone by. You can also follow me on twitter @tvganesh_85 for daily highlights.

You may also like

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.

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

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

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

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

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

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

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

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

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)

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

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

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

To see all posts click Index of posts

# GooglyPlusPlus2021 now with power play, middle and death over analysis

This latest edition of GooglyPlusPlus2021 now includes detailed analysis of teams, batsmen and bowlers in power play, middle and death overs. The T20 format is based on 3 phases as each side faces 20 overs.

Power play: Overs: 0 – 6 – No more than 2 players can be outside the 30 yard circle

Middle overs: Overs: 7- 16 – During these overs the batting side tries to consolidate their innings

Death overs: Overs: 16 -20 – During these 5 overs the batting side tries to accelerate the scoring rate, while the bowling side will try to restrict the batsmen against going for big hits

This is shown below

This latest update of GooglyPlusPlus2021 includes the following functions

a) Match tab

1. teamRunsAcrossOvers
2. teamSRAcrossOvers
3. teamWicketsAcrossOvers
4. teamERAcrossOvers
5. matchWormWickets

1. teamRunsAcrossOversOppnAllMatches
2. teamSRAcrossOversOppnAllMatches
3. teamWicketsAcrossOversOppnAllMatches
4. teamERAcrossOversOppnAllMatches
5. topRunsBatsmenAcrossOversOppnAllMatches
6. topSRBatsmenAcrossOversOppnAllMatches
7. topWicketsBowlersAcrossOversOppnAllMatches
8. topERBowlerAcrossOverOppnAllMatches

c) Overall performance tab

1. teamRunsAcrossOversAllOppnAllMatches
2. teamSRAcrossOversAllOppnAllMatches
3. teamWicketsAcrossOversAllOppnAllMatches
4. teamERAcrossOversAllOppnAllMatches
5. topRunsBatsmenAcrossOversAllOppnAllMatches
6. topSRBatsmenAcrossOversAllOppnAllMatches
7. topWicketsBowlersAcrossOversAllOppnAllMatches
8. topERBowlerAcrossOverAllOppnAllMatches

Hence a total of 8 + 8 + 5 = 21 functions have been added. These functions can be utilized across all the 9 T20 formats that are supported in GooglyPlusPlus2021 namely

i) IPL ii) Intl. T20 (men) iii) Intl. T20 (women) iv) BBL v) NTB vi) PSL vii) CPL viii) SSM ix) WBB

Hence there are a total of 21 x 9 = 189 new possibilities to explore in GooglyPlusPlus2021

GooglyPlusPlus2021 is based on my R package yorkr and is based on data from Cricsheet. To know how to use GooglyPlusPlus see any of earlier posts GooglyPlusPlus2021 is now fully interactive!!!, GooglyPlusPlus2021 adds new bells and whistles!!, GooglyPlusPlus2021 enhanced with drill-down batsman, bowler analytics

Take GooglyPlusPlus for a spin here GooglyPlusPlus2021-9

You can clone/fork the code for the Shiny app from Github – gpp2021-9

Included below is a random selection of options from the 189 possibilities mentioned above. Feel free to try out for yourself

A) IPL – CSK vs KKR 2018-04-10

a) Team Runs in power play, middle and death overs

b) Team Strike rate in power play, middle and death overs

B) Intl. T20 (men) – India vs Afghanistan (2021-11-03)

a) Team wickets in power play, middle and death overs

b) Team Economy rate in power play, middle and death overs

a) Team Runs in all matches in power play, middle and death overs

a) Team vs team Strike rate : Karachi Kings vs Lahore Qalanders since 2019 in power play, middle and death overs

E) Team overall performance in all matches against all opposition

a) BBL : Brisbane Heats : Team Wickets between 2015 – 2018 in power play, middle and death overs

F) Top Runs and Strike rate Batsman of Mumbai Indians vs Royal Challengers Bangalore since 2018

a) Top runs scorers for Mumbai Indians (MI) in power play, middle and death overs

b) Top strike rate for RCB in power play, middle and death overs

F) Intl. T20 (women) India vs England since 2018

a) Top wicket takers for England in power play, middle and death overs since 2018

b) Top wicket takers for India in power play, middle and death overs since 2018

G) Intl. T20 (men) All time best batsmen and bowlers for India

a) Most runs in power play, middle and death overs

b) Highest strike rate in power play, middle and death overs

H) Match worm wicket chart

Note: You can zoom to the area where you would like to focus more

The option of looking at the Match worm chart (without wickets) also exists.

Go ahead take GooglyPlusPlus2021 for a test drive and check out how your favourite players perform in power play, middle and death overs. Click GooglyPlusPlus2021-9