<jupyter_start><jupyter_text>IPL Prediction<jupyter_code>import numpy as np
import pandas as pd
##merging
# matches = pd.read_csv("ipl_dataset.csv")
# deliveries = pd.read_csv("deliveries.csv")
# ipl = pd.merge(matches, deliveries, left_on="id", right_on="match_id").drop('match_id', axis=1)
ipl = pd.read_csv('ipl_dataset.csv')
ipl.describe()
ipl.head()
ipl.info()
ipl[pd.isnull(ipl['winner'])]
ipl['winner'].fillna('tie', inplace=True)
ipl.info()
ipl.replace(['Delhi Daredevils'],['Delhi Capitals'],inplace=True)
ipl.replace(['Mumbai Indians','Kolkata Knight Riders','Royal Challengers Bangalore','Deccan Chargers','Chennai Super Kings',
                 'Rajasthan Royals','Delhi Capitals','Gujarat Lions','Kings XI Punjab',
                 'Sunrisers Hyderabad','Rising Pune Supergiants','Rising Pune Supergiant','Kochi Tuskers Kerala','Pune Warriors']
                ,['MI','KKR','RCB','DC','CSK','RR','DCS','GL','KXIP','SRH','RPS','RPS','KTK','PW'],inplace=True)

encode = {'team1': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DCS':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'team2': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DCS':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'toss_winner': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DCS':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13},
          'winner': {'MI':1,'KKR':2,'RCB':3,'DC':4,'CSK':5,'RR':6,'DCS':7,'GL':8,'KXIP':9,'SRH':10,'RPS':11,'KTK':12,'PW':13,'tie':15},
         'toss_decision' : {'field':0,'bat':1}
         }

ipl.replace(encode, inplace=True)
ipl.head(10)
ipl[pd.isnull(ipl['city'])]
ipl['city'].fillna('Dubai',inplace=True)
# cities=pd.unique(ipl[['city']].values.ravel('K'))
stadium=pd.unique(ipl[['venue']].values.ravel('K'))
stadium
# selecting required columns
ipl = ipl[['team1','team2','toss_winner','toss_decision','venue','winner']]
ipl.info()
## FOR LABELING LONG STRING HOLDING COLUMNS
from sklearn.preprocessing import LabelEncoder
var_mod = ['venue']
le = LabelEncoder()
for i in var_mod:
    ipl[i] = le.fit_transform(ipl[i]).astype(np.int64)
ipl.dtypes
%matplotlib inline
import matplotlib.pyplot as plt
ipl.hist(bins=50,figsize=(20,15))
# ipl["dl_applied"].value_counts()<jupyter_output><empty_output><jupyter_text>Train Test Splitting<jupyter_code>from sklearn.model_selection import train_test_split
train_test, test_test = train_test_split(ipl, test_size=0.2,random_state=11)
ipl = train_test.copy()<jupyter_output><empty_output><jupyter_text>Looking for correlation<jupyter_code>corr_matrix = ipl.corr()
corr_matrix['winner'].sort_values(ascending=False)
from pandas.plotting import scatter_matrix
attributes = ["team2","toss_winner","team1","venue"]
scatter_matrix(ipl[attributes],figsize=(12,8))
ipl.plot(kind = "scatter", x="team2", y="toss_winner", alpha=0.8)
teams = encode['winner']
toss= encode['toss_decision']
print(teams['MI'])
ipl_new = ipl.drop("winner",axis=1)
ipl_labels = ipl["winner"].copy()<jupyter_output><empty_output><jupyter_text>Model Selection<jupyter_code>from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
# model = DecisionTreeClassifier()
# model = KNeighborsClassifier()
# model = LinearRegression() #- shows more error of 23.86
model = RandomForestClassifier()
model.fit(ipl_new,ipl_labels)
some_data = ipl_new.iloc[:5]
some_labels = ipl_labels[:5]
model.predict(some_data)
from sklearn.metrics import mean_squared_error
ipl_predictions = model.predict(ipl_new)
mse = mean_squared_error(ipl_labels,ipl_predictions)
rmse = np.sqrt(mse)
rmse
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model,ipl_new,ipl_labels,scoring="neg_mean_squared_error",cv=5) #cv is 10 folds
rmse_scores = np.sqrt(-scores)
rmse_scores
def print_scores(scores):
    print("Scores : ",scores)
    print("Mean : ",scores.mean())
    print("Standard Deviation:",scores.std())
print_scores(rmse_scores)
X_test = ipl.drop("winner",axis=1)
y_test = ipl["winner"].copy()
final_predictions = model.predict(X_test)
final_mse = mean_squared_error(y_test,final_predictions)
final_rmse = np.sqrt(final_mse)
y_test.head()
print(final_predictions[:5])
final_mse
final_rmse
print(y_test[:5])
print(X_test[::2])
team1 = 'CSK'
team2 = 'MI'
toss_winner = 'CSK'
toss_decision = 'field'
venue = 28
input = [teams[team1],teams[team2],teams[toss_winner],toss[toss_decision],venue]
features = np.array([input])
output=model.predict(features)
print(list(teams.keys())[list(teams.values()).index(output)])
from sklearn.metrics import accuracy_score
acr = accuracy_score(y_test,final_predictions)
print("Accuracy",acr*100)
finals = pd.DataFrame()
finals['Team 1'] = X_test.iloc[:,0]
finals['Team 2'] = X_test.iloc[:,1]
finals['Winner'] = final_predictions
finals['Stadium'] =X_test.iloc[:,4]
vals = [i for i in range(0,41)]
finals['Stadium'] = finals['Stadium'].replace(to_replace=vals, value=stadium)
finals=finals.replace(to_replace=[1,2,3,4,5,6,7,8,9,10,11,12,13,14], value=teams)
finals
from joblib import dump, load
dump(model,'ipl_predictor.joblib')
import pickle
pickle.dump(model,open('ipl_predictor.pkl','wb'))
outs = model.predict(np.array([[5,1,5,1,6]]))
outs
print(list(teams.keys())[list(teams.values()).index(outs)])
X_test['venue'].head()
X_test["venue"]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1937984496124031, 'fraction_numerical': 0.028423772609819122, 'mean_word_length': 8.676785714285714, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '342067', 'license': 'MIT', 'n_tokens_mistral': 2251, 'n_tokens_neox': 2079, 'n_words': 293, 'path': 'IPL_Predictor.ipynb', 'repo_name': 'raeespeer/ipl_predictor', 'size': '5418'}