<jupyter_start><jupyter_text>Import Data<jupyter_code>matches = pd.read_csv("../Data/matches.csv")
matches.head()
attributes = pd.read_csv("../Data/attributes.csv")
attributes.head()
scorecard = open('../Data/scorecard.json',) 
scorecard_data = json.load(scorecard)
tmap = open('../Data/tmap.json',) 
tmap_data = json.load(tmap)<jupyter_output><empty_output><jupyter_text>Get NRR<jupyter_code>def get_score(matches_data, scorecard_data):
    
    matches_data['Toss']=''
    matches_data['Score_team1']=''
    matches_data['Score_team2']=''
    
    matches_data['Result']=''
    
    rem=[]
    
    for i in range(len(matches_data)):
        
        try:
            score=scorecard_data[str(matches_data['MatchCode'].iloc[i])]['SCORES']
            
            if(score[0]>score[1]):
                matches_data['Result'].iloc[i]=1
            elif(score[1]>score[0]):
                matches_data['Result'].iloc[i]=2
            else:
                matches_data['Result'].iloc[i]=3
            
            matches_data['Score_team1'].iloc[i]=score[0]
            matches_data['Score_team2'].iloc[i]=score[1]
            
            toss = tmap_data[scorecard_data[str(matches_data['MatchCode'].iloc[i])]['TOSS']]
            
            if(toss==matches_data['Team_1'].iloc[i]):
                matches_data['Toss'].iloc[i]=1
            else:
                matches_data['Toss'].iloc[i]=2
            
        except:
            rem.append(i)
    
    #print(rem)
    matches_data.drop(rem, inplace = True)    
    return matches_data 
def check_allOut(scorecard_data, matchCode, team_num):
    
    bat = 'BATTING' + str(team_num)
    
    dismissal = [i[1] for i in scorecard_data[matchCode][bat]]
    
    if("not out" in dismissal or '' in dismissal):
        return False
    
    return True
    
def get_totalOvers(scorecard_data, matchCode, team_num):
    
    bat = 'BATTING' + str(team_num)
    
    balls = [i[3] for i in scorecard_data[matchCode][bat] if i[3]!=-1 ]
    
    overs = sum(balls)/6
    return overs
def get_NRR(match, scorecard_data):
    match['NRR_team1']=''
    match['NRR_team2']=''


    for i in range(len(match)):
        match_code = str(match['MatchCode'].iloc[i])
        score=scorecard_data[match_code]['SCORES']
        
        if(match['Result'].iloc[i]==0):
            match['NRR_team1'].iloc[i]=0
            match['NRR_team2'].iloc[i]=0
            
        else:
            runRate_team1=score[0]/50

            if(check_allOut(scorecard_data,match_code,2)):
                runRate_team2=score[1]/50
            else:
                if(match['Result'].iloc[i]==2):
                    runRate_team2=score[1]/get_totalOvers(scorecard_data, match_code, 2)
                else:
                    runRate_team2=score[1]/50

            #print(runRate_team1 - runRate_team2)
            match['NRR_team1'].iloc[i]= runRate_team1 - runRate_team2
            match['NRR_team2'].iloc[i]= runRate_team2 - runRate_team1
        
    return match
    
matches_data = get_score(matches,scorecard_data)
matches_data = get_NRR(matches_data,scorecard_data)
matches_data.head()<jupyter_output><empty_output><jupyter_text>Model with NRR<jupyter_code>enc = OneHotEncoder(handle_unknown='ignore')
enc_df = pd.DataFrame(enc.fit_transform(matches_data[['Result','Toss']]).toarray())
matches_data = matches_data.join(enc_df)
matches_data.head()
matches_data.rename(columns = {0: 'Win1',1: 'Win2',2: 'Tie', 3: 'Toss1',4: 'Toss2'}, inplace = True)

labelencoder = LabelEncoder()

matches_data['Team_1Enc'] = labelencoder.fit_transform(matches_data['Team_1'])
matches_data['Team_2Enc'] = labelencoder.fit_transform(matches_data['Team_2'])
venue_encoding = {
    
    "Home" : 0,
    "Away" : 1,
    "Neutral" : 2
}
matches_data.replace({'Venue':venue_encoding}, inplace=True)
matches_data.head()
X = matches_data[['Date','Team_1Enc','Team_2Enc','Venue','GroundCode','Toss','Toss1','Toss2']].copy()
y = matches_data[['Result','Win1','Win2','Tie','NRR_team1']]
# Test Train Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/5, random_state = 100)
X_train.head()
y_train.head()
def print_model_scores(model, data, y, predictors, target):
    '''
    A generic function to generate the performance report of the
    model in question on the data passed to it using cross-validation
    
    Args:
        model: ML Model to be checked
        data: data on which the model needs to pe trained
        predictors: independent feature variable
        target: target variable
    '''
    model.fit(data[predictors], y[target])
    predictions = model.predict(data[predictors])
    #scores = cross_val_score(model, data[predictors], y[target], scoring="neg_mean_squared_error", cv=5)
    #print('Cross-Validation Score :{}'.format(np.sqrt(-scores)))
    rms = sklearn.metrics.mean_squared_error(predictions,y[target])**0.5
    print('RMS : %s' % '{0:.2%}'.format(rms))
    #print(f"Average RMSE: {np.sqrt(-scores).mean()}")
    r2 = sklearn.metrics.r2_score(predictions,y[target])
    print('R2 : %s' % '{0:.2%}'.format(r2))
    return np.asarray(predictions)
def winner_prediction(model, data, y, predictors,winner):
    pred = print_model_scores(model, X_train, y_train,predictor_var, ['NRR_team1'])
    
    
    for i in range(len(pred)):
        if ((pred[i])>0):
            pred[i] = 1
        elif (pred[i]==0):
            pred[i] = 0
        else:
            pred[i] = 2

    print("Model Accuracy is: ")
    print(sum(1 for x,y in zip(pred,winner) if x == y) / len(winner))<jupyter_output><empty_output><jupyter_text>Model1 - Toss + GroundCode<jupyter_code>winner = y_train['Result']
predictor_var = ['Team_1Enc','Team_2Enc', 'GroundCode','Toss']
model = RandomForestRegressor(n_estimators = 100, random_state = 0)
winner_prediction(model, X_train, y_train,predictor_var, winner)
winner = y_train['Result']
predictor_var = ['Team_1Enc','Team_2Enc', 'GroundCode','Toss']
model = LinearRegression()
winner_prediction(model, X_train, y_train,predictor_var, winner)
winner = y_train['Result']
predictor_var = ['Team_1Enc','Team_2Enc', 'GroundCode','Toss']
model = DecisionTreeRegressor()
winner_prediction(model, X_train, y_train,predictor_var, winner)
winner = y_train['Result']
predictor_var = ['Team_1Enc','Team_2Enc', 'GroundCode','Toss']
model = LassoCV()
winner_prediction(model, X_train, y_train,predictor_var, winner)<jupyter_output>RMS : 161.77%
R2 : -54707.61%
Model Accuracy is: 
0.4850976361767729<jupyter_text>Model2 - Toss + GroundCode + Venue<jupyter_code>winner = y_train['Result']
predictor_var = ['Team_1Enc','Team_2Enc', 'GroundCode','Toss','Venue']
model = RandomForestRegressor(n_estimators = 100, random_state = 0)
winner_prediction(model, X_train, y_train,predictor_var, winner)
winner = y_train['Result']
predictor_var = ['Team_1Enc','Team_2Enc', 'GroundCode','Toss','Venue']
model = LinearRegression()
winner_prediction(model, X_train, y_train,predictor_var, winner)
winner = y_train['Result']
predictor_var = ['Team_1Enc','Team_2Enc', 'GroundCode','Toss','Venue']
model = DecisionTreeRegressor()
winner_prediction(model, X_train, y_train,predictor_var, winner)
winner = y_train['Result']
predictor_var = ['Team_1Enc','Team_2Enc', 'GroundCode','Toss','Venue']
model = LassoCV()
winner_prediction(model, X_train, y_train,predictor_var, winner)<jupyter_output>RMS : 161.77%
R2 : -56506.86%
Model Accuracy is: 
0.4850976361767729
{'fraction_non_alphanumeric': 0.15101710898558535, 'fraction_numerical': 0.024922538057389195, 'mean_word_length': 3.861820563195809, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 22, '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': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '607812', 'license': 'MIT', 'n_tokens_mistral': 2751, 'n_tokens_neox': 2644, 'n_words': 415, 'path': 'models/WithNRR.ipynb', 'repo_name': 'someshsingh22/TeamEleven', 'size': '7423'}