<jupyter_start><jupyter_text>About Problem Statement- Here we have the ipl teams and here we are going to predict score on base of more than 5 over and run and wickets are occured on that particular over and bating team, bowling team and venue.<jupyter_code># first let's remove unnecessary variables

df.drop(columns = ["mid", "date", "batsman", "bowler", "striker", "non-striker"], inplace = True)
# so we have to predict runs so our target variable is runs

# now we have lots of teams of IPL from 2008 to 2018 but here we take only that team which currently playing

current_team = ['Kolkata Knight Riders', 'Chennai Super Kings', 'Rajasthan Royals',
                    'Mumbai Indians', 'Kings XI Punjab', 'Royal Challengers Bangalore',
                    'Delhi Daredevils', 'Sunrisers Hyderabad']

df = df.loc[(df.bat_team.isin(['Kolkata Knight Riders', 'Chennai Super Kings', 'Rajasthan Royals',
                    'Mumbai Indians', 'Kings XI Punjab', 'Royal Challengers Bangalore',
                    'Delhi Daredevils', 'Sunrisers Hyderabad'])) & df.bowl_team.isin(['Kolkata Knight Riders', 'Chennai Super Kings', 'Rajasthan Royals',
                    'Mumbai Indians', 'Kings XI Punjab', 'Royal Challengers Bangalore',
                    'Delhi Daredevils', 'Sunrisers Hyderabad'])]
df.head()
# for prediction we want at least 5 overs data so that's here we train our model on above 5 overs data
df = df[df.overs > 5]
# let's convert text data into lower case

df.venue = df.venue.str.lower()
df.bat_team = df.bat_team.str.lower()
df.bowl_team = df.bowl_team.str.lower()
# let's check bats and bowl team

print(df.bat_team.unique())
print(df.bowl_team.unique())
# In 2020 IPL "delhi daredevils" becomes "delhi capitals" so let's replace it

df.bat_team.replace("delhi daredevils", "delhi capitals", inplace = True)
df.bowl_team.replace("delhi daredevils", "delhi capitals", inplace = True)
# let's check bats and bowl team

print(df.bat_team.unique())
print(df.bowl_team.unique())
df.bat_team.unique() in df.bowl_team.unique()
# let's get unique teams and venue

venue = df.venue.unique()
team = df.bat_team.unique()

print("Venue: ", venue)
print("\n\n Teams: ", team)
# let's encode text data using one hot encoding

# here i' going to encode bat_team and bowl_team using get_dummies
dummy_team = pd.get_dummies(df.drop(columns = "venue"), drop_first = True)
# in dummy team data frame we removed first column for preventing dumy variable trap
# and removed teams are bat_team_chennai super kings and bowl_team_chennai super kings 

# now let's encode the venue
dummy_venue =  pd.get_dummies(df.venue, drop_first = True)
# in venune dummy first column which is barabati stadium is removed bcz preventnig dummy variable trap

# now let's remove text columns from df and concat one hot encoded dummy columns

df = dummy_team

# df = pd.concat([df, dummy_team], axis = 1)
df = pd.concat([df, dummy_venue], axis = 1)

# so our final data for builiding model is look like this
df.head()
df.columns
dummy_team
# let's create feature matrix X and response vector y

X = df.drop(columns = "total")
y = df.total
# let's divide our data into training and testing data set

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)<jupyter_output><empty_output><jupyter_text>it's model building time<jupyter_code># here is regression problem 
# so here we check linear, ridge and lasso regression model for building our model and find best model among them

# Linear Regression

from sklearn.linear_model import LinearRegression

linear_regression = LinearRegression()
linear_regression.fit(X_train, y_train)
linear_regression.score(X_test, y_test)
# let's use Ridge, Lasso and random forest regression if there is any overfitting are available Ridge and Lasso regression will
# removed it

# here we are going to hyper parameter tuning for our ridge and lasso algorithm

from sklearn.model_selection import RandomizedSearchCV
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.ensemble import RandomForestRegressor

algos = {
    "Ridge": {
        "model": Ridge(),
        "params": {
            "alpha": [1e-15, 1e-10, 1e-8, 1e-3, 1e-2, 1, 5, 10, 20, 30 , 40]
        }
    },
    "Lasso": {
        "model": Lasso(),
        "params": {
            "alpha": [1e-15, 1e-10, 1e-8, 1e-3, 1e-2, 1, 5, 10, 20, 30, 40]
        }
    },
    "Random Forest": {
        "model": RandomForestRegressor(),
        "params": {
            "n_estimators": [int(x) for x in np.linspace(100, 1200, 12)],
            "max_features": ["auto", "sqrt"],
            "max_depth": [int(x) for x in np.linspace(5, 30, 6)],
            "min_samples_split": [2, 5, 10, 15, 100],
            "min_samples_leaf": [1, 2, 5, 10]
        }
    }
}

best_models = {}
score = []
for model_name, values in algos.items():
    rscv = RandomizedSearchCV(values["model"], values["params"], cv = 5, n_jobs = -1)
    rscv.fit(X_train, y_train)
    best_models[model_name] = rscv
    score.append({
        "Model": model_name,
        "Best Parameters": rscv.best_params_,
        "Best Score": rscv.best_score_
    })
    
pd.DataFrame(score)
# now let's test ridge lasso and random forest regressor model on our test data set

print("Ridge: ", best_models["Ridge"].score(X_test, y_test))
print("Lasso: ", best_models["Lasso"].score(X_test, y_test))
print("Random Forest", best_models["Random Forest"].score(X_test, y_test))
# here Random Forest Regression give best result with 88.12% accuracy and best parameters are
# {'n_estimators': 400,
#  'min_samples_split': 2,
#  'min_samples_leaf': 5,
#  'max_features': 'sqrt',
#  'max_depth': 25}

# so we take Random Forest Regression for build this model
import time

start_time = time.time()
final_model = RandomForestRegressor(n_estimators = 400, min_samples_split = 2, min_samples_leaf = 5,
                                    max_depth = 25, max_features = "sqrt")
final_model.fit(X, y)

print("Random Forest Regression take ", time.time() - start_time, " to train our model.")
# let's make a prediction function for taking user input
import numpy as np
def predict_score(runs, wickets, overs, runs_last_5, wickets_last_5, bat_team, bowl_team , venue):
    X_pred = np.zeros(len(X.columns))
    
    if bat_team != "chennai super kings":
        # because we removed first columns for prevent dummy variable trap
        # and first column of bat_team was chennai super kings
        
        bat_team_index = np.where(X.columns == "bat_team_" + bat_team)[0][0]
    
    if bowl_team != "chennai super kings":
        # because we removed first columns for prevent dummy variable trap
        # and first column of bowl_team was chennai super kings
        
        bowl_team_index = np.where(X.columns == "bowl_team_" + bowl_team)[0][0]
        
    if venue != "barabati stadium":
        # because we removed first columns for prevent dummy variable trap
        # and first column of venue was barabati stadium
        venue_index = np.where(X.columns == venue)[0][0]
    
    numeric_columns = [runs, wickets, overs, runs_last_5, wickets_last_5]
    for i in range(5):
        X_pred[i] = numeric_columns[i]
        
    
    result = final_model.predict([X_pred])
    return result
    
predict_score(36, 2, 7.3, 32, 4, "delhi capitals", "mumbai indians", "m chinnaswamy stadium")
# let's export some useful stuff for finding prediction on frontend

# let's save model
import pickle

with open("ipl.pickle", "wb")as f:
    pickle.dump(final_model, f)
# let's save columns, venue, team 
# we save it 3 into json file

import json

features = {"columns": X.columns.to_list(), "team": list(team), "venue": list(venue)}

with open("features.json", "w") as f:
    json.dump(features, f)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1090747104492809, 'fraction_numerical': 0.016673030418734885, 'mean_word_length': 3.630524454920448, 'pattern_counts': {'":': 25, '<': 9, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '140948', 'license': 'Apache-2.0', 'n_tokens_mistral': 2680, 'n_tokens_neox': 2498, 'n_words': 852, 'path': 'ipl score prediction.ipynb', 'repo_name': 'PuRgE-CoDeE/IITM-Cricket_Hackathon', 'size': '7857'}