kernel_id
int64 24.2k
23.3M
| prompt
stringlengths 8
1.85M
| completetion
stringlengths 1
182k
| comp_name
stringlengths 5
57
|
---|---|---|---|
8,179,034 | train.drop(['Name','Ticket','Cabin'],axis = 1,inplace = True )<correct_missing_values> | data_dict = {}
for i in glob.glob('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/*'):
name = i.split('/')[-1].split('.')[0]
if name != 'MTeamSpellings':
data_dict[name] = pd.read_csv(i)
else:
data_dict[name] = pd.read_csv(i, encoding='cp1252' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | train.dropna(inplace=True )<categorify> | data_dict['MNCAATourneySeeds']['Seed'] = data_dict['MNCAATourneySeeds']['Seed'].apply(lambda x: int(x[1:3]))
data_dict['MNCAATourneySeeds'] = data_dict['MNCAATourneySeeds'][['Season', 'TeamID', 'Seed']]
data_dict['MNCAATourneyCompactResults'] = data_dict['MNCAATourneyCompactResults'][['Season','WTeamID', 'LTeamID']]
df = pd.merge(data_dict['MNCAATourneyCompactResults'], data_dict['MNCAATourneySeeds'],
how='left', left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'])
df = pd.merge(df, data_dict['MNCAATourneySeeds'], how='left', left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'])
df = df.drop(['TeamID_x', 'TeamID_y'], axis=1)
df.columns = ['Season', 'WTeamID', 'LTeamID', 'WSeed', 'LSeed']
df.head() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | embarked =pd.get_dummies(train['Embarked'], drop_first = True)
embarked.head()<categorify> | team_win_score = data_dict['MRegularSeasonCompactResults'].groupby(['Season', 'WTeamID'] ).agg({'WScore':['sum', 'count']} ).reset_index()
team_win_score.columns = ['Season', 'WTeamID', 'WScore_sum', 'WScore_count']
team_loss_score = data_dict['MRegularSeasonCompactResults'].groupby(['Season', 'LTeamID'] ).agg({'LScore':['sum', 'count']} ).reset_index()
team_loss_score.columns = ['Season', 'LTeamID', 'LScore_sum', 'LScore_count']
df = pd.merge(df, team_win_score, how='left', left_on=['Season', 'WTeamID'], right_on=['Season', 'WTeamID'])
df = pd.merge(df, team_loss_score, how='left', left_on=['Season', 'LTeamID'], right_on=['Season', 'LTeamID'])
df = pd.merge(df, team_loss_score, how='left', left_on=['Season', 'WTeamID'], right_on=['Season', 'LTeamID'])
df = pd.merge(df, team_win_score, how='left', left_on=['Season', 'LTeamID_x'], right_on=['Season', 'WTeamID'])
df.drop(['LTeamID_y', 'WTeamID_y'], axis=1, inplace=True)
df['x_score'] = df['WScore_sum_x'] + df['LScore_sum_y']
df['y_score'] = df['WScore_sum_y'] + df['LScore_sum_x']
df['x_count'] = df['WScore_count_x'] + df['LScore_count_y']
df['y_count'] = df['WScore_count_y'] + df['WScore_count_x']
df = df.drop(['WScore_sum_x','WScore_count_x','LScore_sum_x','LScore_count_x',
'LScore_sum_y','LScore_count_y','WScore_sum_y','WScore_count_y'], axis =1)
df.head() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | pcl =pd.get_dummies(train['Pclass'], drop_first = True)
pcl.head()<categorify> | df_win = df.copy()
df_los = df.copy()
df_win = df_win[['WSeed', 'LSeed', 'x_score', 'y_score', 'x_count', 'y_count']]
df_los = df_los[['LSeed', 'WSeed', 'y_score', 'x_score', 'x_count', 'y_count']]
df_win.columns = ['Seed_1', 'Seed_2', 'Score_1', 'Score_2', 'Count_1', 'Count_2']
df_los.columns = ['Seed_1', 'Seed_2', 'Score_1', 'Score_2', 'Count_1', 'Count_2']
df_win['Seed_diff'] = df_win['Seed_1'] - df_win['Seed_2']
df_win['Score_diff'] = df_win['Score_1'] - df_win['Score_2']
df_los['Seed_diff'] = df_los['Seed_1'] - df_los['Seed_2']
df_los['Score_diff'] = df_los['Score_1'] - df_los['Score_2'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | sex = pd.get_dummies(train['Sex'], drop_first = True)
sex.head()<concatenate> | df_win['result'] = 1
df_los['result'] = 0
data = pd.concat(( df_win, df_los)).reset_index(drop=True ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | train = pd.concat([train,embarked,pcl,sex],axis = 1 )<drop_column> | test = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv')
test = test.drop(['Pred'], axis=1)
test['Season'] = test['ID'].apply(lambda x: int(x.split('_')[0]))
test['Team1'] = test['ID'].apply(lambda x: int(x.split('_')[1]))
test['Team2'] = test['ID'].apply(lambda x: int(x.split('_')[2]))
test = pd.merge(test, data_dict['MNCAATourneySeeds'], how='left', left_on=['Season', 'Team1'], right_on=['Season', 'TeamID'])
test = pd.merge(test, data_dict['MNCAATourneySeeds'], how='left', left_on=['Season', 'Team2'], right_on=['Season', 'TeamID'])
test = pd.merge(test, team_win_score, how='left', left_on=['Season', 'Team1'], right_on=['Season', 'WTeamID'])
test = pd.merge(test, team_loss_score, how='left', left_on=['Season', 'Team2'], right_on=['Season', 'LTeamID'])
test = pd.merge(test, team_loss_score, how='left', left_on=['Season', 'Team1'], right_on=['Season', 'LTeamID'])
test = pd.merge(test, team_win_score, how='left', left_on=['Season', 'Team2'], right_on=['Season', 'WTeamID'])
test.drop(['LTeamID_y', 'WTeamID_y'], axis=1, inplace=True)
test.head() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | train.drop(['Embarked','Pclass','Sex'],axis = 1,inplace = True )<data_type_conversions> | test['x_score'] = test['WScore_sum_x'] + test['LScore_sum_y']
test['y_score'] = test['WScore_sum_y'] + test['LScore_sum_x']
test['x_count'] = test['WScore_count_x'] + test['LScore_count_y']
test['y_count'] = test['WScore_count_y'] + test['WScore_count_x']
test = test[['Seed_x', 'Seed_y', 'x_score', 'y_score', 'x_count', 'y_count']]
test.columns = ['Seed_1', 'Seed_2', 'Score_1', 'Score_2', 'Count_1', 'Count_2']
test['Seed_diff'] = test['Seed_1'] - test['Seed_2']
test['Score_diff'] = test['Score_1'] - test['Score_2']
test_df = test | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | train.fillna(train.mean() , inplace=True )<prepare_x_and_y> | params_lgb = {'num_leaves': 127,
'min_data_in_leaf': 10,
'objective': 'binary',
'max_depth': -1,
'learning_rate': 0.01,
"boosting_type": "gbdt",
"bagging_seed": 11,
"metric": 'logloss',
"verbosity": -1,
'random_state': 42,
}
X = data.drop('result', axis=1)
y = data['result'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | X = train.drop(['Survived','PassengerId'],axis = 1)
y = train['Survived']<split> | NFOLDS = 10
folds = KFold(n_splits=NFOLDS)
columns = X.columns
splits = folds.split(X, y)
y_preds_lgb = np.zeros(test_df.shape[0])
y_train_lgb = np.zeros(X.shape[0])
y_oof = np.zeros(X.shape[0])
feature_importances = pd.DataFrame()
feature_importances['feature'] = columns
for fold_n,(train_index, valid_index)in enumerate(splits):
print('Fold:',fold_n+1)
X_train, X_valid = X[columns].iloc[train_index], X[columns].iloc[valid_index]
y_train, y_valid = y.iloc[train_index], y.iloc[valid_index]
dtrain = lgb.Dataset(X_train, label=y_train)
dvalid = lgb.Dataset(X_valid, label=y_valid)
clf = lgb.train(params_lgb, dtrain, 10000, valid_sets = [dtrain, dvalid], verbose_eval=200)
feature_importances[f'fold_{fold_n + 1}'] = clf.feature_importance()
y_pred_valid = clf.predict(X_valid)
y_oof[valid_index] = y_pred_valid
y_train_lgb += clf.predict(X)/ NFOLDS
y_preds_lgb += clf.predict(test_df)/ NFOLDS
del X_train, X_valid, y_train, y_valid
gc.collect() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.33, random_state=123 )<train_model> | Google Cloud & NCAA® ML Competition 2020-NCAAM |
|
8,179,034 | clf = GradientBoostingClassifier()
clf.fit(X_train,y_train )<predict_on_test> | df_compact = data_dict['MNCAATourneyCompactResults']
df_detailed = data_dict['MNCAATourneyDetailedResults']
results_merged = pd.merge(df_compact, df_detailed)
results_merged.head() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | y_pred = clf.predict(X_valid )<compute_test_metric> | results_merged['WeFG%'] =(results_merged['WFGM']+0.5*results_merged['WFGM3'])/ results_merged['WFGA']
results_merged['LeFG%'] =(results_merged['LFGM']+0.5*results_merged['LFGM3'])/ results_merged['LFGA']
results_merged['WTO%'] = results_merged['WTO'] /(results_merged['WFGA']+0.44*results_merged['WFTA'] +results_merged['WTO'])
results_merged['LTO%'] = results_merged['LTO'] /(results_merged['LFGA']+0.44*results_merged['LFTA'] +results_merged['LTO'])
results_merged['WFTR%'] = results_merged['WFTA'] / results_merged['WFGA']
results_merged['LFTR%'] = results_merged['LFTA'] / results_merged['LFGA']
results_merged['WORB%'] = results_merged['WOR'] / results_merged['LDR']
results_merged['LORB%'] = results_merged['LOR'] / results_merged['WDR'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | report = classification_report(y_valid,y_pred)
print(report )<compute_test_metric> | ts = TrueSkill(draw_probability=0.01)
beta = 25 / 6
def win_probability(p1, p2):
delta_mu = p1.mu - p2.mu
sum_sigma = p1.sigma * p1.sigma + p2.sigma * p2.sigma
denom = np.sqrt(2 *(beta * beta)+ sum_sigma)
return ts.cdf(delta_mu / denom)
submit = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv')
submit[['Season', 'Team1', 'Team2']] = submit.apply(lambda r:pd.Series([int(t)for t in r.ID.split('_')]), axis=1)
df_tour = results_merged
teamIds = np.unique(np.concatenate([df_tour.WTeamID.values, df_tour.LTeamID.values]))
ratings = { tid:ts.Rating() for tid in teamIds }
def feed_season_results(season):
print("season = {}".format(season))
df1 = df_tour[df_tour.Season == season]
for r in df1.itertuples() :
ratings[r.WTeamID], ratings[r.LTeamID] = rate_1vs1(ratings[r.WTeamID], ratings[r.LTeamID])
def update_pred(season):
beta = np.std([r.mu for r in ratings.values() ])
print("beta = {}".format(beta))
submit.loc[submit.Season==season, 'Pred'] = submit[submit.Season==season].apply(lambda r:win_probability(ratings[r.Team1], ratings[r.Team2]), axis=1)
for season in sorted(df_tour.Season.unique())[:-5]:
feed_season_results(season)
update_pred(2015)
feed_season_results(2015)
update_pred(2016)
feed_season_results(2016)
update_pred(2017)
feed_season_results(2017)
update_pred(2018)
feed_season_results(2018)
update_pred(2019)
submit.drop(['Season', 'Team1', 'Team2'], axis=1, inplace=True)
y_preds_ts = submit['Pred'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | accuracy_score(y_valid,y_pred )<categorify> | submission_df = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv')
submission_df['Pred'] = 0.4*y_preds_lgb + 0.6*y_preds_ts | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,179,034 | sex1 = pd.get_dummies(test['Sex'], drop_first = True )<categorify> | submission_df.to_csv('submission.csv', index=False ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | embarked1 = pd.get_dummies(test['Embarked'], drop_first = True)
pcl1 = pd.get_dummies(test['Pclass'], drop_first = True )<concatenate> | import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.model_selection import GridSearchCV | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | test = pd.concat([test,embarked1,pcl1,sex1], axis = 1 )<drop_column> | tourney_result = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MNCAATourneyCompactResults.csv')
tourney_seed = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MNCAATourneySeeds.csv' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | test.drop(['Sex', 'Embarked', 'Name', 'Ticket','Pclass','Cabin'], axis=1,inplace=True )<correct_missing_values> | tourney_result = tourney_result.drop(['DayNum', 'WScore', 'LScore', 'WLoc', 'NumOT'], axis=1)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | test.fillna(test.mean() , inplace=True )<predict_on_test> | tourney_result = pd.merge(tourney_result, tourney_seed, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Seed':'WSeed'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result = pd.merge(tourney_result, tourney_seed, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Seed':'LSeed'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | ids = test['PassengerId']
predictions = clf.predict(test.drop('PassengerId', axis=1))
<save_to_csv> | def get_seed(x):
return int(x[1:3])
tourney_result['WSeed'] = tourney_result['WSeed'].map(lambda x: get_seed(x))
tourney_result['LSeed'] = tourney_result['LSeed'].map(lambda x: get_seed(x))
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | output = pd.DataFrame({ 'PassengerId' : ids, 'Survived': predictions })
output.to_csv('submission.csv', index=False )<import_modules> | season_result = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MRegularSeasonCompactResults.csv' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | tf.__version__<import_modules> | season_win_result = season_result[['Season', 'WTeamID', 'WScore']]
season_lose_result = season_result[['Season', 'LTeamID', 'LScore']]
season_win_result.rename(columns={'WTeamID':'TeamID', 'WScore':'Score'}, inplace=True)
season_lose_result.rename(columns={'LTeamID':'TeamID', 'LScore':'Score'}, inplace=True)
season_result = pd.concat(( season_win_result, season_lose_result)).reset_index(drop=True)
season_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | from tensorflow.keras import layers
import tensorflow.keras.backend as K
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPool2D, Dropout, Reshape, Input
from tensorflow.keras.losses import CategoricalCrossentropy
from tensorflow.keras.optimizers import Adam, Adadelta, Adagrad, Adamax, Nadam, RMSprop, Ftrl<set_options> | season_score = season_result.groupby(['Season', 'TeamID'])['Score'].sum().reset_index()
season_score | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | device = torch.device("cuda" )<load_from_csv> | tourney_result = pd.merge(tourney_result, season_score, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Score':'WScoreT'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result = pd.merge(tourney_result, season_score, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Score':'LScoreT'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | df_train = pd.read_csv(".. /input/digit-recognizer/train.csv")
df_test = pd.read_csv(".. /input/digit-recognizer/test.csv")
df_sub = pd.read_csv(".. /input/digit-recognizer/sample_submission.csv")
df_Id = df_sub["ImageId"]<prepare_x_and_y> | tourney_win_result = tourney_result.drop(['Season', 'WTeamID', 'LTeamID'], axis=1)
tourney_win_result.rename(columns={'WSeed':'Seed1', 'LSeed':'Seed2', 'WScoreT':'ScoreT1', 'LScoreT':'ScoreT2'}, inplace=True)
tourney_win_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | X = df_train.drop("label", axis=1 ).values
y = df_train["label"].values
X_test = df_test.values
X = X / 255
X_test = X_test / 255
X = X.reshape(( -1, 1, 28, 28))
X_test = X_test.reshape(( -1, 1, 28, 28))<split> | tourney_lose_result = tourney_win_result.copy()
tourney_lose_result['Seed1'] = tourney_win_result['Seed2']
tourney_lose_result['Seed2'] = tourney_win_result['Seed1']
tourney_lose_result['ScoreT1'] = tourney_win_result['ScoreT2']
tourney_lose_result['ScoreT2'] = tourney_win_result['ScoreT1']
tourney_lose_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.1, random_state=123 )<prepare_x_and_y> | tourney_win_result['Seed_diff'] = tourney_win_result['Seed1'] - tourney_win_result['Seed2']
tourney_win_result['ScoreT_diff'] = tourney_win_result['ScoreT1'] - tourney_win_result['ScoreT2']
tourney_lose_result['Seed_diff'] = tourney_lose_result['Seed1'] - tourney_lose_result['Seed2']
tourney_lose_result['ScoreT_diff'] = tourney_lose_result['ScoreT1'] - tourney_lose_result['ScoreT2'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | t_X_train = torch.from_numpy(X_train ).float()
t_y_train = torch.from_numpy(y_train ).long()
t_X_val = torch.from_numpy(X_val ).float()
t_y_val = torch.from_numpy(y_val ).long()
dataset_train = TensorDataset(t_X_train, t_y_train)
dataset_val = TensorDataset(t_X_val, t_y_val)
loader_train = DataLoader(dataset_train, batch_size=20, shuffle=True)
loader_val = DataLoader(dataset_val, batch_size=20 )<choose_model_class> | tourney_win_result['result'] = 1
tourney_lose_result['result'] = 0
tourney_result = pd.concat(( tourney_win_result, tourney_lose_result)).reset_index(drop=True)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | activation_relu = torch.nn.ReLU()
class cnn(nn.Module):
def __init__(self):
super(cnn, self ).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(32, 32, 3, padding=1)
self.conv3 = nn.Conv2d(32, 32, 3, padding=1)
self.conv4 = nn.Conv2d(32, 32, 3, padding=1)
self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv5 = nn.Conv2d(32, 64, 3, padding=1)
self.conv6 = nn.Conv2d(64, 64, 3, padding=1)
self.conv7 = nn.Conv2d(64, 64, 3, padding=1)
self.conv8 = nn.Conv2d(64, 64, 3, padding=1)
self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.flatten = nn.Flatten()
self.drop1 = nn.Dropout(p=0.5)
self.fc1 = nn.Linear(7*7*64, 1024)
self.drop2 = nn.Dropout(p=0.5)
self.fc2 = nn.Linear(1024, 10)
def forward(self, x):
x = activation_relu(self.conv1(x))
x = activation_relu(self.conv2(x))
x = activation_relu(self.conv3(x))
x = activation_relu(self.conv4(x))
x = activation_relu(self.maxpool1(x))
x = activation_relu(self.conv5(x))
x = activation_relu(self.conv6(x))
x = activation_relu(self.conv7(x))
x = activation_relu(self.conv8(x))
x = activation_relu(self.maxpool2(x))
x = self.flatten(x)
x = self.drop1(x)
x = activation_relu(self.fc1(x))
x = self.drop2(x)
x = self.fc2(x)
return x
cnn = cnn()<set_options> | X_train=tourney_result.drop('result',axis=1)
y_train=tourney_result.result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | device = torch.device("cuda")
cnn.to(device )<choose_model_class> | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical, normalize
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(cnn.parameters() , lr=0.0002 )<train_on_grid> | model = tf.keras.models.Sequential([
tf.keras.layers.Dense(128, input_shape=(6,), activation='relu'),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(125, activation='relu'),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(1, activation='sigmoid')
] ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | train_history = []
val_history = []
for epoch in range(10):
total_train_loss = 0
total_val_loss = 0
total_train_acc = 0
total_val_acc = 0
total_train = 0
total_val = 0
for inputs, labels in loader_train:
inputs, labels = inputs.to(device), labels.to(device)
cnn.train()
optimizer.zero_grad()
outputs = cnn(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
total_train_loss += loss
with torch.no_grad() :
y_pred = torch.argmax(cnn(inputs), dim=1)
acc_train = int(( y_pred==labels ).sum())
total_train_acc += acc_train
total_train += len(labels)
for inputs, labels in loader_val:
inputs, labels = inputs.to(device), labels.to(device)
cnn.eval()
outputs = cnn(inputs)
loss = criterion(outputs, labels)
total_val_loss += loss
with torch.no_grad() :
y_pred = torch.argmax(cnn(inputs), dim=1)
total_acc_val = int(( y_pred==labels ).sum())
total_val += len(labels)
avg_train_acc = total_train_acc / total_train
avg_val_acc = total_acc_val / total_val
train_history.append([total_train_loss, total_train_acc])
val_history.append([total_val_loss, total_val_acc])
print(f"Epoch {epoch+1} ---> train_loss: {total_train_loss:.5f} | val_loss: {total_val_loss:.5f} || "\
f"train_acc {avg_train_acc:.5f} | val_acc {avg_val_acc:.5f}" )<prepare_x_and_y> | model.compile(loss='binary_crossentropy',
optimizer=Adam(0.0001),
metrics=['acc'] ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | x = torch.tensor([[1, 2, 3, 4, 5],
[2, 2, 2, 2, 2]])
y = torch.tensor([1, 3, 4, 4, 5])
type(len(x))<choose_model_class> | history = model.fit(X_train, y_train,epochs=150,verbose=1 ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | cnn1 = tf.keras.models.Sequential([Conv2D(input_shape=(28, 28, 1), filters=16, kernel_size=(3, 3), activation="relu", padding="same"),
Conv2D(filters=16, kernel_size=(3, 3), activation="relu", padding="same"),
Conv2D(filters=16, kernel_size=(3, 3), activation="relu", padding="same"),
Conv2D(filters=16, kernel_size=(3, 3), activation="relu", padding="same"),
MaxPool2D(pool_size=(2, 2), strides=(2, 2)) ,
Conv2D(filters=32, kernel_size=(3, 3), activation="relu", padding="same"),
Conv2D(filters=32, kernel_size=(3, 3), activation="relu", padding="same"),
Conv2D(filters=32, kernel_size=(3, 3), activation="relu", padding="same"),
Conv2D(filters=32, kernel_size=(3, 3), activation="relu", padding="same"),
MaxPool2D(pool_size=(2, 2), strides=(2, 2)) ,
Flatten() ,
Dense(units=1024, activation="relu"),
Dropout(rate=0.5),
Dense(units=10, activation="softmax")] )<train_model> | test_df = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | def seq_train_val(X, y, model, optimizer=Adam, validation_data=None, learning_rate=0.0001, loss="categorical_crossentropy", batch_size=10, epochs=40):
model.summary()
learning_rate_reduction = tf.keras.callbacks.ReduceLROnPlateau(monitor="val_loss", mode="min", patiencs=5, verbose=1, factor=0.5, min_lr=0.000001)
model.compile(optimizer=optimizer(learning_rate=learning_rate), loss=loss, metrics=["acc"])
model.fit(X_train, y_train, validation_data=validation_data, batch_size=batch_size, verbose=2, epochs=epochs, callbacks=[learning_rate_reduction])
return None
def predict(X, model):
y_pred = model.predict(X)
y_pred = np.argmax(y_pred, axis=1)
return y_pred<train_model> | test_df['Season'] = test_df['ID'].map(lambda x: int(x[:4]))
test_df['WTeamID'] = test_df['ID'].map(lambda x: int(x[5:9]))
test_df['LTeamID'] = test_df['ID'].map(lambda x: int(x[10:14]))
test_df | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | seq_train_val(X=X_train_std, y=y_train, validation_data=(X_val_std, y_val), model=cnn1 )<compute_test_metric> | test_df = pd.merge(test_df, tourney_seed, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
test_df.rename(columns={'Seed':'Seed1'}, inplace=True)
test_df = test_df.drop('TeamID', axis=1)
test_df = pd.merge(test_df, tourney_seed, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
test_df.rename(columns={'Seed':'Seed2'}, inplace=True)
test_df = test_df.drop('TeamID', axis=1)
test_df = pd.merge(test_df, season_score, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
test_df.rename(columns={'Score':'ScoreT1'}, inplace=True)
test_df = test_df.drop('TeamID', axis=1)
test_df = pd.merge(test_df, season_score, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
test_df.rename(columns={'Score':'ScoreT2'}, inplace=True)
test_df = test_df.drop('TeamID', axis=1)
test_df | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | validation(X_val_std, y_val, model=cnn )<save_to_csv> | test_df['Seed1'] = test_df['Seed1'].map(lambda x: get_seed(x))
test_df['Seed2'] = test_df['Seed2'].map(lambda x: get_seed(x))
test_df['Seed_diff'] = test_df['Seed1'] - test_df['Seed2']
test_df['ScoreT_diff'] = test_df['ScoreT1'] - test_df['ScoreT2']
test_df = test_df.drop(['ID', 'Pred', 'Season', 'WTeamID', 'LTeamID'], axis=1)
test_df | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | y_pred = predict(X_test_std, model=cnn)
y_pred = pd.DataFrame(y_pred, columns=["Label"])
sub = pd.concat([df_Id, y_pred], axis=1)
sub.to_csv("submission.csv", index=False )<choose_model_class> | from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold
import lightgbm as lgb
import xgboost as xgb
from xgboost import XGBClassifier
import gc | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | ac_relu = layers.Activation("relu")
ac_softmax = layers.Activation("softmax")
class cnn2(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(cnn2, self ).__init__(*args, **kwargs)
self.conv1 = Conv2D(filters=8, kernel_size=(3, 3), padding="same")
self.conv2 = Conv2D(filters=8, kernel_size=(3, 3), padding="same")
self.conv3 = Conv2D(filters=8, kernel_size=(3, 3), padding="same")
self.maxpool1 = MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding="same")
self.conv4 = Conv2D(filters=16, kernel_size=(3, 3), padding="same")
self.conv5 = Conv2D(filters=16, kernel_size=(3, 3), padding="same")
self.conv6 = Conv2D(filters=16, kernel_size=(3, 3), padding="same")
self.maxpool2 = MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding="same")
self.conv7 = Conv2D(filters=32, kernel_size=(3, 3), padding="same")
self.conv8 = Conv2D(filters=32, kernel_size=(3, 3), padding="same")
self.conv9 = Conv2D(filters=32, kernel_size=(3, 3), padding="same")
self.conv10 = Conv2D(filters=32, kernel_size=(3, 3), padding="same")
self.maxpool3 = MaxPool2D(pool_size=(2, 2), strides=(2, 2))
self.conv11 = Conv2D(filters=64, kernel_size=(3, 3), padding="same")
self.conv12 = Conv2D(filters=64, kernel_size=(3, 3), padding="same")
self.conv13 = Conv2D(filters=64, kernel_size=(3, 3), padding="same")
self.conv14 = Conv2D(filters=64, kernel_size=(3, 3), padding="same")
self.maxpool4 = MaxPool2D(pool_size=(2, 2), strides=(2, 2))
self.flatten = Flatten()
self.dense1 = Dense(units=1024)
self.drop = Dropout(rate=0.5)
self.dense2 = Dense(units=10)
def call(self, inputs, training=None):
x2 = ac_relu(self.conv1(inputs))
x3 = ac_relu(self.conv2(x2))
x4 = ac_relu(self.conv3(x3))
x5 = ac_relu(self.maxpool1(x4))
x6 = ac_relu(self.conv4(x5))
x7 = ac_relu(self.conv5(x6))
x8 = ac_relu(self.conv6(x7))
x9 = ac_relu(self.maxpool2(x8))
x10 = ac_relu(self.conv7(x9))
x11 = ac_relu(self.conv8(x10))
x12 = ac_relu(self.conv9(x11))
x13 = ac_relu(self.conv10(x12))
x14 = ac_relu(self.maxpool3(x13))
x15 = ac_relu(self.conv11(x14))
x16 = ac_relu(self.conv12(x15))
x17 = ac_relu(self.conv13(x16))
x18 = ac_relu(self.conv14(x17))
x19 = ac_relu(self.maxpool4(x18))
x20 = self.flatten(x19)
x21 = ac_relu(self.dense1(x20))
x22 = self.drop(x21)
outputs = ac_softmax(self.dense2(x22))
return outputs
cnn2 = cnn2()<categorify> | params_lgb = {'num_leaves': 400,
'min_child_weight': 0.034,
'feature_fraction': 0.379,
'bagging_fraction': 0.418,
'min_data_in_leaf': 106,
'objective': 'binary',
'max_depth': 50,
'learning_rate': 0.0068,
"boosting_type": "gbdt",
"bagging_seed": 11,
"metric": 'logloss',
"verbosity": -1,
'reg_alpha': 0.3899,
'reg_lambda': 0.648,
'random_state': 47,
}
params_xgb = {'colsample_bytree': 0.8,
'learning_rate': 0.0004,
'max_depth': 31,
'subsample': 1,
'objective':'binary:logistic',
'eval_metric':'logloss',
'min_child_weight':3,
'gamma':0.25,
'n_estimators':5000
} | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | def sub_train_val(X_train, y_train, X_val, y_val, model, optimizer=Adam, learning_rate=0.0001, loss_object=CategoricalCrossentropy() ,
batch_size=20, y_label=10, epochs=5):
X_trainn = X_train.astype("float32")
if y_label:
y_trainn = tf.one_hot(y_train, 10, dtype="float32")
else:
y_trainn = y_train.astype("float32")
train_sliced = tf.data.Dataset.from_tensor_slices(( X_trainn, y_trainn))
train_dataset = train_sliced.shuffle(100000 ).batch(batch_size)
X_vall = X_val.astype("float32")
if y_label:
y_vall = tf.one_hot(y_val, 10, dtype="float32")
else:
y_vall = y_vall.astype("float32")
val_sliced = tf.data.Dataset.from_tensor_slices(( X_vall, y_vall))
val_dataset = val_sliced.batch(batch_size)
optimizer = optimizer(learning_rate=learning_rate)
loss_object = loss_object
train_loss = tf.keras.metrics.Mean(name="train_loss")
val_loss = tf.keras.metrics.Mean(name="val_loss")
train_loss_list = []
val_loss_list = []
@tf.function
def train_step(X_train, y_train, model, optimizer, loss_object, train_loss):
training = True
K.set_learning_phase(training)
with tf.GradientTape() as tape:
y_pred_tra = model(X_train, training=training)
loss = loss_object(y_train, y_pred_tra)
gradient = tape.gradient(loss, model.trainable_weights)
optimizer.apply_gradients(zip(gradient, model.trainable_weights))
train_loss(loss)
@tf.function
def val_step(X_val, y_val, model, optimizer, loss_object, val_loss):
training = False
y_pred_val = model(X_val, training=training)
loss = loss_object(y_val, y_pred_val)
val_loss(loss)
for epoch in range(epochs):
print(f"Epoch is {str(epoch+1 ).zfill(3)} ----->", end=" ")
for X, y in train_dataset:
train_step(X, y, model=model, optimizer=optimizer, loss_object=loss_object, train_loss=train_loss)
print("train_loss: {:.6f}".format(float(train_loss.result())) , end=" | ")
train_loss_list.append(float(train_loss.result()))
train_loss.reset_states()
for X, y in val_dataset:
val_step(X, y, model=model, optimizer=optimizer, loss_object=loss_object, val_loss=val_loss)
print("val_loss: {:.6f}".format(float(val_loss.result())))
val_loss_list.append(float(val_loss.result()))
val_loss.reset_states()
print()
print("-"*100)
print()
print("Best val_loss is {:.6f}, and when the epoch is {}".format(min(val_loss_list), epoch+1))
fig = plt.figure(figsize=(10, 8))
plt.plot(range(1, epochs+1), train_loss_list, marker="o", c="b", label="train_loss")
plt.plot(range(1, epochs+1), val_loss_list, marker="v", c="r", label="validation_loss")
plt.legend()
plt.xlabel("epochs")
plt.ylabel("loss")
plt.title("train_and_validation_loss" )<train_model> | NFOLDS = 200
folds = KFold(n_splits=NFOLDS)
columns = X_train.columns
splits = folds.split(X_train, y_train ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | train_val(X_train=X_train_std, y_train=y_train, X_val=X_val_std, y_val=y_val, model=cnn2, learning_rate=0.0001, epochs=40, optimizer=Adam )<predict_on_test> | y_preds_lgb = np.zeros(test_df.shape[0])
y_oof_lgb = np.zeros(X_train.shape[0] ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | def validate(X, y, model):
X_tensor = tf.convert_to_tensor(X)
y_pred = model(X_tensor)
y_pred = y_pred.numpy()
y_pred = np.argmax(y_pred, axis=1)
acc = accuracy_score(y, y_pred)
return acc
def predict(X, model):
X_tensor = tf.convert_to_tensor(X)
y_pred = model(X_tensor)
y_pred = y_pred.numpy()
y_pred = np.argmax(y_pred, axis=1)
return y_pred<compute_test_metric> | for fold_n,(train_index, valid_index)in enumerate(splits):
print('Fold:',fold_n+1)
X_train1, X_valid1 = X_train[columns].iloc[train_index], X_train[columns].iloc[valid_index]
y_train1, y_valid1 = y_train.iloc[train_index], y_train.iloc[valid_index]
dtrain = lgb.Dataset(X_train1, label=y_train1)
dvalid = lgb.Dataset(X_valid1, label=y_valid1)
clf = lgb.train(params_lgb, dtrain, 10000, valid_sets = [dtrain, dvalid], verbose_eval=200)
y_pred_valid = clf.predict(X_valid1)
y_oof_lgb[valid_index] = y_pred_valid
y_preds_lgb += clf.predict(test_df)/ NFOLDS
del X_train1, X_valid1, y_train1, y_valid1
gc.collect() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | validate(X_train_std, y_train, cnn2 )<categorify> | Google Cloud & NCAA® ML Competition 2020-NCAAM |
|
7,994,061 | x = torch.empty(2, 3)
print(x)
x = torch.rand(2, 3)
print(x)
x = torch.zeros(2, 3, dtype=torch.float)
print(x)
x = torch.ones(2, 3, dtype=torch.int)
print(x)
x = torch.tensor([[0.0, 0.1, 0.2],
[1.0, 1.1, 1.2]])
print(x)
y = x.new_ones(1, 2)
print(y)
y = torch.ones_like(x, dtype=torch.int)
print(y )<categorify> | submission_df = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv')
submission_df['Pred'] = y_preds_lgb
submission_df | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,994,061 | b = x.numpy()
print('PyTorch計算→NumPy反映:')
print(b); x.add_(y); print(b)
print('NumPy計算→PyTorch反映:')
print(x); np.add(b, b, out=b); print(x)
c = np.ones(( 2, 3), dtype=np.float64)
d = torch.from_numpy(c)
print('NumPy計算→PyTorch反映:')
print(d); np.add(c, c, out=c); print(d)
print('PyTorch計算→NumPy反映:')
print(c); d.add_(y); print(c )<set_options> | Google Cloud & NCAA® ML Competition 2020-NCAAM |
|
7,994,061 | <define_variables><EOS> | submission_df.to_csv('submission.csv', index=False ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | <SOS> metric: logloss Kaggle data source: google-cloud-ncaa-march-madness-2020-division-1-mens-tournament<import_modules> | import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.model_selection import GridSearchCV | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | import numpy as np
import pandas as pd
import tensorflow as tf
import os
import math
from IPython.display import clear_output
import matplotlib.pyplot as plt
from sklearn.utils import shuffle<load_from_csv> | tourney_result = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MNCAATourneyCompactResults.csv')
tourney_seed = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MNCAATourneySeeds.csv' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | training_data_raw = pd.read_csv("/kaggle/input/titanic/train.csv")
testing_data_raw = pd.read_csv("/kaggle/input/titanic/test.csv")
print(training_data_raw.head())
print(testing_data_raw.head() )<create_dataframe> | tourney_result = tourney_result.drop(['DayNum', 'WScore', 'LScore', 'WLoc', 'NumOT'], axis=1)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | training_data = training_data_raw[['Sex','Name','Age','Pclass','SibSp','Parch','Fare','Survived']]
testing_data = testing_data_raw[['Sex','Name','Age','Pclass','SibSp','Parch','Fare']]<count_missing_values> | tourney_result = pd.merge(tourney_result, tourney_seed, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Seed':'WSeed'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result = pd.merge(tourney_result, tourney_seed, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Seed':'LSeed'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | print(( training_data[['Name','Sex','Age','Pclass','SibSp','Parch','Fare','Survived']].isnull() ).sum())
print(( testing_data[['Name','Sex','Age','Pclass','SibSp','Parch','Fare']].isnull() ).sum() )<feature_engineering> | def get_seed(x):
return int(x[1:3])
tourney_result['WSeed'] = tourney_result['WSeed'].map(lambda x: get_seed(x))
tourney_result['LSeed'] = tourney_result['LSeed'].map(lambda x: get_seed(x))
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | def handle_nans(dataframe):
dataframe['HasNAN'] = 0
for column in dataframe:
if dataframe[column].dtypes != 'int32' and dataframe[column].dtypes != 'float32' and \
dataframe[column].dtypes != 'int64' and dataframe[column].dtypes != 'float64':
continue
for row, value in dataframe[column].iteritems() :
if math.isnan(value):
dataframe.loc[row,'HasNAN'] = 1
if dataframe[column].isnull().sum() != 0:
temp = testing_data[column]
median = temp.append(training_data[column] ).median()
dataframe[column] = dataframe[column].fillna(median)
return dataframe
<categorify> | season_result = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MRegularSeasonCompactResults.csv' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | training_data = handle_nans(training_data)
testing_data = handle_nans(testing_data)
<categorify> | season_win_result = season_result[['Season', 'WTeamID', 'WScore']]
season_lose_result = season_result[['Season', 'LTeamID', 'LScore']]
season_win_result.rename(columns={'WTeamID':'TeamID', 'WScore':'Score'}, inplace=True)
season_lose_result.rename(columns={'LTeamID':'TeamID', 'LScore':'Score'}, inplace=True)
season_result = pd.concat(( season_win_result, season_lose_result)).reset_index(drop=True)
season_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | def get_title(name):
first_part_name = name.split(",")[1]
title = first_part_name.split(" ")[1]
return title
def age_class_dummies(dataframe):
dataframe['Sex'] = pd.factorize(dataframe['Sex'])[0]
dataframe['Name'] = dataframe['Name'].apply(get_title)
dataframe['Name'] = pd.factorize(dataframe['Name'])[0]
dataframe = dataframe.rename(columns={'Name':'Title'})
dataframe = pd.get_dummies(dataframe, columns=['Title'])
dataframe = dataframe.astype('int32')
return dataframe
training_data = age_class_dummies(training_data)
testing_data = age_class_dummies(testing_data)
for column in training_data:
if(column not in testing_data)and(column != 'Survived'):
print("Column not in testing data: ", column)
testing_data[column] = 0
for column in testing_data:
if column not in training_data:
print("Column not in training data: ", column)
training_data[column] = 0
training_data = training_data.reindex(sorted(training_data.columns), axis=1)
testing_data = testing_data.reindex(sorted(testing_data.columns), axis=1)
<categorify> | season_score = season_result.groupby(['Season', 'TeamID'])['Score'].sum().reset_index()
season_score | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | print(len(training_data))
validation_split = int(len(training_data)/ 2)
def shuffle_data() :
global train_x, train_y, validation_x, validation_y, test_x
shuffled_training_data = shuffle(training_data)
shuffled_training_data.reset_index(inplace=True, drop=True)
train_x = shuffled_training_data.drop(columns=['Survived'] ).to_numpy()
train_y = shuffled_training_data['Survived'].to_numpy()
validation_x = train_x[validation_split + 1:]
validation_y = train_y[validation_split + 1:]
train_x = train_x[0:validation_split]
train_y = train_y[0:validation_split]
test_x = testing_data.to_numpy()<import_modules> | tourney_result = pd.merge(tourney_result, season_score, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Score':'WScoreT'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result = pd.merge(tourney_result, season_score, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Score':'LScoreT'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | from xgboost import XGBRegressor, XGBClassifier
from sklearn.metrics import mean_absolute_error<find_best_model_class> | tourney_win_result = tourney_result.drop(['Season', 'WTeamID', 'LTeamID'], axis=1)
tourney_win_result.rename(columns={'WSeed':'Seed1', 'LSeed':'Seed2', 'WScoreT':'ScoreT1', 'LScoreT':'ScoreT2'}, inplace=True)
tourney_win_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | loss_log = pd.DataFrame(columns=['loss'])
best_model = None
best_score = 99
for i in range(0,50):
shuffle_data()
model = XGBClassifier(n_estimators=2000, learning_rate=0.001)
model.fit(train_x, train_y, early_stopping_rounds=150,
eval_set=[(train_x, train_y)], verbose=False)
predictions = model.predict(validation_x)
mae = mean_absolute_error(predictions, validation_y)
if mae < best_score:
best_score = mae
loss_log.loc[len(loss_log)] = [mae]
loss_log.plot(figsize=[20,4])
plt.show()<predict_on_test> | tourney_lose_result = tourney_win_result.copy()
tourney_lose_result['Seed1'] = tourney_win_result['Seed2']
tourney_lose_result['Seed2'] = tourney_win_result['Seed1']
tourney_lose_result['ScoreT1'] = tourney_win_result['ScoreT2']
tourney_lose_result['ScoreT2'] = tourney_win_result['ScoreT1']
tourney_lose_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | test_y = model.predict(test_x)
test_y = test_y.flatten()<save_to_csv> | tourney_win_result['Seed_diff'] = tourney_win_result['Seed1'] - tourney_win_result['Seed2']
tourney_win_result['ScoreT_diff'] = tourney_win_result['ScoreT1'] - tourney_win_result['ScoreT2']
tourney_lose_result['Seed_diff'] = tourney_lose_result['Seed1'] - tourney_lose_result['Seed2']
tourney_lose_result['ScoreT_diff'] = tourney_lose_result['ScoreT1'] - tourney_lose_result['ScoreT2'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | final_prediction = pd.DataFrame(columns=['PassengerId','Survived'])
final_prediction['Survived'] = test_y
final_prediction['PassengerId'] = testing_data_raw['PassengerId']
print(final_prediction.head())
final_prediction.to_csv('submission.csv', index=False )<load_from_csv> | tourney_win_result['result'] = 1
tourney_lose_result['result'] = 0
tourney_result = pd.concat(( tourney_win_result, tourney_lose_result)).reset_index(drop=True)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | train_data = pd.read_csv('.. /input/titanic/train.csv')
test_data = pd.read_csv('.. /input/titanic/test.csv')
features = ["Pclass", "Sex", "SibSp", "Parch"]
X_train = pd.get_dummies(train_data[features])
y_train = train_data["Survived"]
final_X_test = pd.get_dummies(test_data[features])
classifier = XGBClassifier(n_estimators=750,learning_rate=0.02,max_depth=3)
classifier.fit(X_train, y_train)
predictions = classifier.predict(final_X_test)
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions})
output.to_csv('submission.csv', index=False )<import_modules> | test_df = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import RandomizedSearchCV
from sklearn.preprocessing import LabelEncoder<load_from_csv> | test_df['Season'] = test_df['ID'].map(lambda x: int(x[:4]))
test_df['WTeamID'] = test_df['ID'].map(lambda x: int(x[5:9]))
test_df['LTeamID'] = test_df['ID'].map(lambda x: int(x[10:14]))
test_df | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | train = pd.read_csv("/kaggle/input/titanic/train.csv")
train.head()<load_from_csv> | test_df = pd.merge(test_df, tourney_seed, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
test_df.rename(columns={'Seed':'Seed1'}, inplace=True)
test_df = test_df.drop('TeamID', axis=1)
test_df = pd.merge(test_df, tourney_seed, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
test_df.rename(columns={'Seed':'Seed2'}, inplace=True)
test_df = test_df.drop('TeamID', axis=1)
test_df = pd.merge(test_df, season_score, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
test_df.rename(columns={'Score':'ScoreT1'}, inplace=True)
test_df = test_df.drop('TeamID', axis=1)
test_df = pd.merge(test_df, season_score, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
test_df.rename(columns={'Score':'ScoreT2'}, inplace=True)
test_df = test_df.drop('TeamID', axis=1)
test_df | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | test = pd.read_csv("/kaggle/input/titanic/test.csv")
test.head()<load_from_csv> | test_df['Seed1'] = test_df['Seed1'].map(lambda x: get_seed(x))
test_df['Seed2'] = test_df['Seed2'].map(lambda x: get_seed(x))
test_df['Seed_diff'] = test_df['Seed1'] - test_df['Seed2']
test_df['ScoreT_diff'] = test_df['ScoreT1'] - test_df['ScoreT2']
test_df = test_df.drop(['ID', 'Pred', 'Season', 'WTeamID', 'LTeamID'], axis=1)
test_df | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | df_sub = pd.read_csv("/kaggle/input/titanic/gender_submission.csv")
df_sub.head()<prepare_x_and_y> | h2o.init(
nthreads=-1,
max_mem_size = "8G" ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | X, y = train.drop(['PassengerId','Name','Survived'], axis = 1), train[['Survived']]
<count_missing_values> | train_1=h2o.H2OFrame(tourney_result)
train_1['result']=train_1['result'].asfactor() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | X.isnull().sum()<data_type_conversions> | param = {
"ntrees" : 2000
, "max_depth" : 20
, "learn_rate" : 0.02
, "sample_rate" : 0.7
, "col_sample_rate_per_tree" : 0.9
, "min_rows" : 5
, "seed": 4241
, "score_tree_interval": 100,"stopping_metric" :"MSE","nfolds":8,"fold_assignment":"AUTO","keep_cross_validation_predictions" : True,"booster":"dart"
}
model_xgb = H2OXGBoostEstimator(**param)
model_xgb.train(x = train_list, y = 'result', training_frame = train_1 ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | X.Age = X.Age.fillna(X.Age.median())
X.Cabin = X.Cabin.fillna(X.Cabin.mode())
X.Embarked = X.Embarked.fillna(X.Embarked.mode())
<count_missing_values> | param={
"ntrees" : 1000
, "max_depth" : 20
, "learn_rate" : 0.02
, "sample_rate" : 0.7
, "col_sample_rate_per_tree" : 0.9
, "min_rows" : 5
, "seed": 4241
, "score_tree_interval": 100,"stopping_metric" :"MSE","nfolds":8,"fold_assignment":"AUTO","keep_cross_validation_predictions" : True
}
model_gbm = H2OGradientBoostingEstimator(**param)
model_gbm.train(x = train_list, y = 'result', training_frame = train_1 ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | X.isnull().sum()<drop_column> | stack = H2OStackedEnsembleEstimator(model_id="ensemble11",
training_frame=train_1,
base_models=[model_xgb.model_id,model_gbm.model_id],metalearner_algorithm="glm")
stack.train(x=train_list, y="result", training_frame=train_1)
| Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | X_test = test.drop(['PassengerId', 'Name'], axis = 1 )<count_missing_values> | test_1=h2o.H2OFrame(test_df ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | X_test.isnull().sum()<data_type_conversions> | pred1=model_xgb.predict(test_1)
pred2=model_gbm.predict(test_1)
| Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | X_test.Cabin = X_test.Cabin.astype('str')
X_test.Fare = X_test.Fare.astype('float' )<count_missing_values> | pred_df1=pred1.as_data_frame()
pred_df2=pred2.as_data_frame()
| Google Cloud & NCAA® ML Competition 2020-NCAAM |
8,158,539 | <count_missing_values><EOS> | submission_df = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv')
submission_df['Pred'] = pred_df2['p1']*0.9+pred_df1['p1']*0.1
submission_df
submission_df.to_csv('submission.csv', index=False ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | <SOS> metric: logloss Kaggle data source: google-cloud-ncaa-march-madness-2020-division-1-mens-tournament<feature_engineering> | pd.set_option('max_columns', None)
plt.style.use('seaborn')
%matplotlib inline
py.init_notebook_mode(connected=True)
warnings.filterwarnings('ignore')
| Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | X['type'] = 'train'<feature_engineering> | class LGBWrapper(object):
def __init__(self):
self.model = lgb.LGBMClassifier()
def fit(self, X_train, y_train, X_valid=None, y_valid=None, X_holdout=None, y_holdout=None, params=None):
eval_set = [(X_train, y_train)]
eval_names = ['train']
self.model = self.model.set_params(**params)
if X_valid is not None:
eval_set.append(( X_valid, y_valid))
eval_names.append('valid')
if X_holdout is not None:
eval_set.append(( X_holdout, y_holdout))
eval_names.append('holdout')
if 'cat_cols' in params.keys() :
cat_cols = [col for col in params['cat_cols'] if col in X_train.columns]
if len(cat_cols)> 0:
categorical_columns = params['cat_cols']
else:
categorical_columns = 'auto'
else:
categorical_columns = 'auto'
self.model.fit(X=X_train, y=y_train,
eval_set=eval_set, eval_names=eval_names,
verbose=params['verbose'], early_stopping_rounds=params['early_stopping_rounds'])
self.best_score_ = self.model.best_score_
self.feature_importances_ = self.model.feature_importances_
def predict_proba(self, X_test):
if self.model.objective == 'binary':
return self.model.predict_proba(X_test, num_iteration=self.model.best_iteration_)[:, 1]
else:
return self.model.predict_proba(X_test, num_iteration=self.model.best_iteration_ ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | X_test['type'] = 'test'<concatenate> | class MainTransformer(BaseEstimator, TransformerMixin):
def __init__(self, convert_cyclical: bool = False, create_interactions: bool = False, n_interactions: int = 20):
self.convert_cyclical = convert_cyclical
self.create_interactions = create_interactions
self.feats_for_interaction = None
self.n_interactions = n_interactions
def fit(self, X, y=None):
if self.create_interactions:
pass
return self
def transform(self, X, y=None):
data = copy.deepcopy(X)
return data
def fit_transform(self, X, y=None, **fit_params):
data = copy.deepcopy(X)
self.fit(data)
return self.transform(data)
class FeatureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, main_cat_features: list = None, num_cols: list = None):
self.main_cat_features = main_cat_features
self.num_cols = num_cols
def fit(self, X, y=None):
self.num_cols = [col for col in X.columns if 'sum' in col or 'mean' in col or 'max' in col or 'std' in col
or 'attempt' in col]
return self
def transform(self, X, y=None):
data = copy.deepcopy(X)
return data
def fit_transform(self, X, y=None, **fit_params):
data = copy.deepcopy(X)
self.fit(data)
return self.transform(data ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | df = pd.concat([X, X_test] )<count_values> | class ClassifierModel(object):
def __init__(self, columns: list = None, model_wrapper=None):
self.columns = columns
self.model_wrapper = model_wrapper
self.result_dict = {}
self.train_one_fold = False
self.preprocesser = None
def fit(self, X: pd.DataFrame, y,
X_holdout: pd.DataFrame = None, y_holdout=None,
folds=None,
params: dict = None,
eval_metric='auc',
cols_to_drop: list = None,
preprocesser=None,
transformers: dict = None,
adversarial: bool = False,
plot: bool = True):
self.cols_to_drop = cols_to_drop
if folds is None:
folds = KFold(n_splits=3, random_state=42)
self.train_one_fold = True
self.columns = X.columns if self.columns is None else self.columns
self.feature_importances = pd.DataFrame(columns=['feature', 'importance'])
self.trained_transformers = {k: [] for k in transformers}
self.transformers = transformers
self.models = []
self.folds_dict = {}
self.eval_metric = eval_metric
n_target = 1 if len(set(y.values)) == 2 else len(set(y.values))
self.oof = np.zeros(( len(X), n_target))
self.n_target = n_target
X = X[self.columns]
if X_holdout is not None:
X_holdout = X_holdout[self.columns]
if preprocesser is not None:
self.preprocesser = preprocesser
self.preprocesser.fit(X, y)
X = self.preprocesser.transform(X, y)
self.columns = X.columns.tolist()
if X_holdout is not None:
X_holdout = self.preprocesser.transform(X_holdout)
for fold_n,(train_index, valid_index)in enumerate(folds.split(X, y)) :
if X_holdout is not None:
X_hold = X_holdout.copy()
else:
X_hold = None
self.folds_dict[fold_n] = {}
if params['verbose']:
print(f'Fold {fold_n + 1} started at {time.ctime() }')
self.folds_dict[fold_n] = {}
X_train, X_valid = X.iloc[train_index], X.iloc[valid_index]
y_train, y_valid = y.iloc[train_index], y.iloc[valid_index]
if self.train_one_fold:
X_train = X[self.original_columns]
y_train = y
X_valid = None
y_valid = None
datasets = {'X_train': X_train, 'X_valid': X_valid, 'X_holdout': X_hold, 'y_train': y_train}
X_train, X_valid, X_hold = self.transform_(datasets, cols_to_drop)
self.folds_dict[fold_n]['columns'] = X_train.columns.tolist()
model = copy.deepcopy(self.model_wrapper)
if adversarial:
X_new1 = X_train.copy()
if X_valid is not None:
X_new2 = X_valid.copy()
elif X_holdout is not None:
X_new2 = X_holdout.copy()
X_new = pd.concat([X_new1, X_new2], axis=0)
y_new = np.hstack(( np.zeros(( X_new1.shape[0])) , np.ones(( X_new2.shape[0]))))
X_train, X_valid, y_train, y_valid = train_test_split(X_new, y_new)
model.fit(X_train, y_train, X_valid, y_valid, X_hold, y_holdout, params=params)
self.folds_dict[fold_n]['scores'] = model.best_score_
if self.oof.shape[0] != len(X):
self.oof = np.zeros(( X.shape[0], self.oof.shape[1]))
if not adversarial:
self.oof[valid_index] = model.predict_proba(X_valid ).reshape(-1, n_target)
fold_importance = pd.DataFrame(list(zip(X_train.columns, model.feature_importances_)) ,
columns=['feature', 'importance'])
self.feature_importances = self.feature_importances.append(fold_importance)
self.models.append(model)
self.feature_importances['importance'] = self.feature_importances['importance'].astype(float)
self.calc_scores_()
if plot:
print(classification_report(y,(self.oof > 0.5)* 1))
fig, ax = plt.subplots(figsize=(16, 12))
plt.subplot(2, 2, 1)
self.plot_feature_importance(top_n=25)
plt.subplot(2, 2, 2)
self.plot_metric()
plt.subplot(2, 2, 3)
g = sns.heatmap(confusion_matrix(y,(self.oof > 0.5)* 1), annot=True, cmap=plt.cm.Blues,fmt="d")
g.set(ylim=(-0.5, 4), xlim=(-0.5, 4), title='Confusion matrix')
plt.subplot(2, 2, 4)
plt.hist(self.oof)
plt.xticks(range(self.n_target), range(self.n_target))
plt.title('Distribution of oof predictions');
def transform_(self, datasets, cols_to_drop):
for name, transformer in self.transformers.items() :
transformer.fit(datasets['X_train'], datasets['y_train'])
datasets['X_train'] = transformer.transform(datasets['X_train'])
if datasets['X_valid'] is not None:
datasets['X_valid'] = transformer.transform(datasets['X_valid'])
if datasets['X_holdout'] is not None:
datasets['X_holdout'] = transformer.transform(datasets['X_holdout'])
self.trained_transformers[name].append(transformer)
if cols_to_drop is not None:
cols_to_drop = [col for col in cols_to_drop if col in datasets['X_train'].columns]
self.cols_to_drop = cols_to_drop
datasets['X_train'] = datasets['X_train'].drop(cols_to_drop, axis=1)
if datasets['X_valid'] is not None:
datasets['X_valid'] = datasets['X_valid'].drop(cols_to_drop, axis=1)
if datasets['X_holdout'] is not None:
datasets['X_holdout'] = datasets['X_holdout'].drop(cols_to_drop, axis=1)
return datasets['X_train'], datasets['X_valid'], datasets['X_holdout']
def calc_scores_(self):
print()
datasets = [k for k, v in [v['scores'] for k, v in self.folds_dict.items() ][0].items() if len(v)> 0]
self.scores = {}
for d in datasets:
scores = [v['scores'][d][self.eval_metric] for k, v in self.folds_dict.items() ]
print(f"CV mean score on {d}: {np.mean(scores):.4f} +/- {np.std(scores):.4f} std.")
self.scores[d] = np.mean(scores)
def predict(self, X_test, averaging: str = 'usual'):
full_prediction = np.zeros(( X_test.shape[0], self.oof.shape[1]))
if self.preprocesser is not None:
X_test = self.preprocesser.transform(X_test)
for i in range(len(self.models)) :
X_t = X_test.copy()
for name, transformers in self.trained_transformers.items() :
X_t = transformers[i].transform(X_t)
if self.cols_to_drop:
cols_to_drop = [col for col in self.cols_to_drop if col in X_t.columns]
X_t = X_t.drop(cols_to_drop, axis=1)
y_pred = self.models[i].predict_proba(X_t[self.folds_dict[i]['columns']] ).reshape(-1, full_prediction.shape[1])
if full_prediction.shape[0] != len(y_pred):
full_prediction = np.zeros(( y_pred.shape[0], self.oof.shape[1]))
if averaging == 'usual':
full_prediction += y_pred
elif averaging == 'rank':
full_prediction += pd.Series(y_pred ).rank().values
return full_prediction / len(self.models)
def plot_feature_importance(self, drop_null_importance: bool = True, top_n: int = 10):
top_feats = self.get_top_features(drop_null_importance, top_n)
feature_importances = self.feature_importances.loc[self.feature_importances['feature'].isin(top_feats)]
feature_importances['feature'] = feature_importances['feature'].astype(str)
top_feats = [str(i)for i in top_feats]
sns.barplot(data=feature_importances, x='importance', y='feature', orient='h', order=top_feats)
plt.title('Feature importances')
def get_top_features(self, drop_null_importance: bool = True, top_n: int = 10):
grouped_feats = self.feature_importances.groupby(['feature'])['importance'].mean()
if drop_null_importance:
grouped_feats = grouped_feats[grouped_feats != 0]
return list(grouped_feats.sort_values(ascending=False ).index)[:top_n]
def plot_metric(self):
full_evals_results = pd.DataFrame()
for model in self.models:
evals_result = pd.DataFrame()
for k in model.model.evals_result_.keys() :
evals_result[k] = model.model.evals_result_[k][self.eval_metric]
evals_result = evals_result.reset_index().rename(columns={'index': 'iteration'})
full_evals_results = full_evals_results.append(evals_result)
full_evals_results = full_evals_results.melt(id_vars=['iteration'] ).rename(columns={'value': self.eval_metric,
'variable': 'dataset'})
full_evals_results[self.eval_metric] = np.abs(full_evals_results[self.eval_metric])
sns.lineplot(data=full_evals_results, x='iteration', y=self.eval_metric, hue='dataset')
plt.title('Training progress' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | df.type.value_counts()<categorify> | data_dict = {}
for i in glob.glob('/kaggle/input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/*'):
name = i.split('/')[-1].split('.')[0]
if name != 'MTeamSpellings':
data_dict[name] = pd.read_csv(i)
else:
data_dict[name] = pd.read_csv(i, encoding='cp1252' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | le = LabelEncoder()<data_type_conversions> | data_dict['MNCAATourneySeeds'] = data_dict['MNCAATourneySeeds'].loc[data_dict['MNCAATourneySeeds']['Season'] <= 2014]
data_dict['MNCAATourneySeeds']['Seed'] = data_dict['MNCAATourneySeeds']['Seed'].apply(lambda x: int(x[1:3]))
data_dict['MNCAATourneySeeds'] = data_dict['MNCAATourneySeeds'][['Season', 'TeamID', 'Seed']]
data_dict['MNCAATourneyCompactResults'] = data_dict['MNCAATourneyCompactResults'][['Season','WTeamID', 'LTeamID']]
data_dict['MNCAATourneyCompactResults'] = data_dict['MNCAATourneyCompactResults'].loc[data_dict['MNCAATourneyCompactResults']['Season'] <= 2014]
df = pd.merge(data_dict['MNCAATourneyCompactResults'], data_dict['MNCAATourneySeeds'],
how='left', left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'])
df = pd.merge(df, data_dict['MNCAATourneySeeds'], how='left', left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'])
df = df.drop(['TeamID_x', 'TeamID_y'], axis=1)
df.columns = ['Season', 'WTeamID', 'LTeamID', 'WSeed', 'LSeed']
df.head() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | df[['Sex','Ticket','Cabin','Embarked']] = df[['Sex','Ticket','Cabin','Embarked']].apply(lambda x: le.fit_transform(x.astype('str')) )<drop_column> | team_win_score = data_dict['MRegularSeasonCompactResults'].groupby(['Season', 'WTeamID'] ).agg({'WScore':['sum', 'count']} ).reset_index()
team_win_score.columns = ['Season', 'WTeamID', 'WScore_sum', 'WScore_count']
team_loss_score = data_dict['MRegularSeasonCompactResults'].groupby(['Season', 'LTeamID'] ).agg({'LScore':['sum', 'count']} ).reset_index()
team_loss_score.columns = ['Season', 'LTeamID', 'LScore_sum', 'LScore_count']
df = pd.merge(df, team_win_score, how='left', left_on=['Season', 'WTeamID'], right_on=['Season', 'WTeamID'])
df = pd.merge(df, team_loss_score, how='left', left_on=['Season', 'LTeamID'], right_on=['Season', 'LTeamID'])
df = pd.merge(df, team_loss_score, how='left', left_on=['Season', 'WTeamID'], right_on=['Season', 'LTeamID'])
df = pd.merge(df, team_win_score, how='left', left_on=['Season', 'LTeamID_x'], right_on=['Season', 'WTeamID'])
df.drop(['LTeamID_y', 'WTeamID_y'], axis=1, inplace=True)
df.head() | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | X = df[df.type == "train"].drop("type", axis = 1)
X.head()<drop_column> | df['x_score'] = df['WScore_sum_x'] + df['LScore_sum_y']
df['y_score'] = df['WScore_sum_y'] + df['LScore_sum_x']
df['x_count'] = df['WScore_count_x'] + df['LScore_count_y']
df['y_count'] = df['WScore_count_y'] + df['LScore_count_x'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | X_test_orig = df[df.type == "test"].drop("type", axis = 1)
X_test_orig.head()<train_model> | df_win = df.copy()
df_los = df.copy()
df_win = df_win[['WSeed', 'LSeed', 'x_score', 'y_score', 'x_count', 'y_count']]
df_los = df_los[['LSeed', 'WSeed', 'y_score', 'x_score', 'y_count', 'x_count']]
df_win.columns = ['Seed_1', 'Seed_2', 'Score_1', 'Score_2', 'Count_1', 'Count_2']
df_los.columns = ['Seed_1', 'Seed_2', 'Score_1', 'Score_2', 'Count_1', 'Count_2'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | X_train, X_test, y_train, y_test= train_test_split(X, y, test_size=0.3, random_state=42)
xg_cl = xgb.XGBClassifier(objective='binary:logistic', n_estimators=10, seed=42)
xg_cl.fit(X_train,y_train)
preds = xg_cl.predict(X_test)
accuracy = float(np.sum(preds==y_test[['Survived']].values.ravel())) /y_test.shape[0]
print("accuracy: %f" %(accuracy))<choose_model_class> | df_win['Seed_diff'] = df_win['Seed_1'] - df_win['Seed_2']
df_win['Score_diff'] = df_win['Score_1'] - df_win['Score_2']
df_los['Seed_diff'] = df_los['Seed_1'] - df_los['Seed_2']
df_los['Score_diff'] = df_los['Score_1'] - df_los['Score_2']
df_win['Count_diff'] = df_win['Count_1'] - df_win['Count_2']
df_win['Mean_score1'] = df_win['Score_1'] / df_win['Count_1']
df_win['Mean_score2'] = df_win['Score_2'] / df_win['Count_2']
df_win['Mean_score_diff'] = df_win['Mean_score1'] - df_win['Mean_score2']
df_los['Count_diff'] = df_los['Count_1'] - df_los['Count_2']
df_los['Mean_score1'] = df_los['Score_1'] / df_los['Count_1']
df_los['Mean_score2'] = df_los['Score_2'] / df_los['Count_2']
df_los['Mean_score_diff'] = df_los['Mean_score1'] - df_los['Mean_score2'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | gbm_param_grid = {
'num_rounds': [1,5, 10, 15, 20],
'eta_vals' : [0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9],
'colsample_bytree': [0.3,0.4, 0.5, 0.7, 0.9],
'n_estimators': [5,10,15,20,25],
'max_depth': range(2, 20)
}
gbm = xgb.XGBClassifier(objective='binary:logistic', seed=42)
randomized_accuracy = RandomizedSearchCV(param_distributions=gbm_param_grid, estimator = gbm, scoring = "accuracy", n_iter = 5, cv = 4, verbose = 1)
randomized_accuracy.fit(X,y)
print("Best parameters found: ", randomized_accuracy.best_params_)
print("Best Accuracy Score: ", np.sqrt(np.abs(randomized_accuracy.best_score_)))
<predict_on_test> | df_win['result'] = 1
df_los['result'] = 0
data = pd.concat(( df_win, df_los)).reset_index(drop=True ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | y_predicted = randomized_accuracy.best_estimator_.predict(X_test_orig )<create_dataframe> | for col in ['Score_1', 'Score_2', 'Count_1', 'Count_2', 'Score_diff', 'Count_diff']:
print(col)
data[col] = data[col].fillna(0 ).astype(int ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | sub = pd.DataFrame({"PassengerId":test.PassengerId, "Survived":y_predicted} )<save_to_csv> | n_fold = 5
folds = RepeatedStratifiedKFold(n_splits=n_fold)
| Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | sub.to_csv('submission.csv', index = False)
sub.head()<import_modules> | X = data.drop(['result'], axis=1)
y = data['result'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn.preprocessing import PowerTransformer<load_from_csv> | param = {'n_estimators':10000,
'num_leaves': 400,
'min_child_weight': 0.034,
'feature_fraction': 0.379,
'bagging_fraction': 0.418,
'min_data_in_leaf': 106,
'objective': 'binary',
'max_depth': -1,
'learning_rate': 0.007,
"boosting_type": "gbdt",
"metric": 'binary_logloss',
"verbosity": 10,
'reg_alpha': 0.3899,
'reg_lambda': 0.648,
'random_state': 47,
'task':'train', 'nthread':-1,
'verbose': 100,
'early_stopping_rounds': 30,
'eval_metric': 'binary_logloss'
}
cat_cols = []
mt = MainTransformer(create_interactions=False)
ft = FeatureTransformer()
transformers = {'ft': ft}
lgb_model = ClassifierModel(model_wrapper=LGBWrapper())
lgb_model.fit(X=X, y=y, folds=folds, params=param, preprocesser=mt, transformers=transformers,
eval_metric='binary_logloss', cols_to_drop=None, plot=True ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | train = pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/train.csv")
test_x = pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/test.csv")
train.columns<prepare_x_and_y> | test = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv')
test = test.drop(['Pred'], axis=1)
test['Season'] = test['ID'].apply(lambda x: int(x.split('_')[0]))
test['Team1'] = test['ID'].apply(lambda x: int(x.split('_')[1]))
test['Team2'] = test['ID'].apply(lambda x: int(x.split('_')[2]))
test = pd.merge(test, data_dict['MNCAATourneySeeds'], how='left', left_on=['Season', 'Team1'], right_on=['Season', 'TeamID'])
test = pd.merge(test, data_dict['MNCAATourneySeeds'], how='left', left_on=['Season', 'Team2'], right_on=['Season', 'TeamID'])
test = pd.merge(test, team_win_score, how='left', left_on=['Season', 'Team1'], right_on=['Season', 'WTeamID'])
test = pd.merge(test, team_loss_score, how='left', left_on=['Season', 'Team2'], right_on=['Season', 'LTeamID'])
test = pd.merge(test, team_loss_score, how='left', left_on=['Season', 'Team1'], right_on=['Season', 'LTeamID'])
test = pd.merge(test, team_win_score, how='left', left_on=['Season', 'Team2'], right_on=['Season', 'WTeamID'])
test['seed_diff'] = test['Seed_x'] - test['Seed_y'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | train_x = train.drop("SalePrice",axis=1)
train_y = train["SalePrice"]
all_data = pd.concat([train_x,test_x],axis=0,sort=True)
train_ID = train['Id']
test_ID = test_x['Id']
all_data.drop("Id", axis = 1, inplace = True)
print("train_x: "+str(train_x.shape))
print("train_y: "+str(train_y.shape))
print("test_x: "+str(test_x.shape))
print("all_data: "+str(all_data.shape))<sort_values> | test['x_score'] = test['WScore_sum_x'] + test['LScore_sum_y']
test['y_score'] = test['WScore_sum_y'] + test['LScore_sum_x']
test['x_count'] = test['WScore_count_x'] + test['LScore_count_y']
test['y_count'] = test['WScore_count_y'] + test['WScore_count_x'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | all_data_na = all_data.isnull().sum() [all_data.isnull().sum() >0].sort_values(ascending=False)
all_data_na<sort_values> | test = test[['Seed_x', 'Seed_y', 'x_score', 'y_score', 'x_count', 'y_count']]
test.columns = ['Seed_1', 'Seed_2', 'Score_1', 'Score_2', 'Count_1', 'Count_2'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | na_col_list = all_data.isnull().sum() [all_data.isnull().sum() >0].index.tolist()
all_data[na_col_list].dtypes.sort_values()
<data_type_conversions> | test['Seed_diff'] = test['Seed_1'] - test['Seed_2']
test['Score_diff'] = test['Score_1'] - test['Score_2']
test['Seed_diff'] = test['Seed_1'] - test['Seed_2']
test['Score_diff'] = test['Score_1'] - test['Score_2']
test['Count_diff'] = test['Count_1'] - test['Count_2']
test['Mean_score1'] = test['Score_1'] / test['Count_1']
test['Mean_score2'] = test['Score_2'] / test['Count_2']
test['Mean_score_diff'] = test['Mean_score1'] - test['Mean_score2']
test['Count_diff'] = test['Count_1'] - test['Count_2']
test['Mean_score1'] = test['Score_1'] / test['Count_1']
test['Mean_score2'] = test['Score_2'] / test['Count_2']
test['Mean_score_diff'] = test['Mean_score1'] - test['Mean_score2'] | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | all_data['LotFrontage'] = all_data.groupby('Neighborhood')['LotFrontage'].transform(lambda x: x.fillna(x.median()))
float_list = all_data[na_col_list].dtypes[all_data[na_col_list].dtypes == "float64"].index.tolist()
obj_list = all_data[na_col_list].dtypes[all_data[na_col_list].dtypes == "object"].index.tolist()
all_data[float_list] = all_data[float_list].fillna(0)
all_data[obj_list] = all_data[obj_list].fillna("None")
all_data.isnull().sum() [all_data.isnull().sum() > 0]<data_type_conversions> | test_preds = lgb_model.predict(test ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | all_data['MSSubClass'] = all_data['MSSubClass'].apply(str)
all_data['YrSold'] = all_data['YrSold'].astype(str)
all_data['MoSold'] = all_data['MoSold'].astype(str )<filter> | submission_df = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MSampleSubmissionStage1_2020.csv')
submission_df['Pred'] = test_preds
submission_df | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,982,339 | <feature_engineering><EOS> | submission_df.to_csv('submission.csv', index=False ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,985,375 | <SOS> metric: logloss Kaggle data source: google-cloud-ncaa-march-madness-2020-division-1-mens-tournament<count_values> | import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.model_selection import GridSearchCV | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,985,375 | all_data.dtypes.value_counts()<categorify> | tourney_result = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MNCAATourneyCompactResults.csv')
tourney_seed = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MNCAATourneySeeds.csv' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,985,375 | all_data = pd.get_dummies(all_data,columns=cal_list)
all_data.shape<import_modules> | tourney_result = tourney_result.drop(['DayNum', 'WScore', 'LScore', 'WLoc', 'NumOT'], axis=1)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,985,375 | from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.metrics import mean_squared_error
import xgboost as xgb
from sklearn.model_selection import GridSearchCV
import lightgbm as lgb<split> | tourney_result = pd.merge(tourney_result, tourney_seed, left_on=['Season', 'WTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Seed':'WSeed'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result = pd.merge(tourney_result, tourney_seed, left_on=['Season', 'LTeamID'], right_on=['Season', 'TeamID'], how='left')
tourney_result.rename(columns={'Seed':'LSeed'}, inplace=True)
tourney_result = tourney_result.drop('TeamID', axis=1)
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,985,375 | train_x, valid_x, train_y, valid_y = train_test_split(
train_x,
train_y,
test_size=0.3,
random_state=0 )<train_model> | def get_seed(x):
return int(x[1:3])
tourney_result['WSeed'] = tourney_result['WSeed'].map(lambda x: get_seed(x))
tourney_result['LSeed'] = tourney_result['LSeed'].map(lambda x: get_seed(x))
tourney_result | Google Cloud & NCAA® ML Competition 2020-NCAAM |
7,985,375 | dtrain = xgb.DMatrix(train_x, label=train_y)
dvalid = xgb.DMatrix(valid_x,label=valid_y)
num_round = 5000
evallist = [(dvalid, 'eval'),(dtrain, 'train')]
evals_result = {}
param = {
'max_depth': 3,
'eta': 0.01,
'objective': 'reg:squarederror',
}
bst = xgb.train(
param, dtrain,
num_round,
evallist,
evals_result=evals_result,
early_stopping_rounds = 1000 )<save_to_csv> | season_result = pd.read_csv('.. /input/google-cloud-ncaa-march-madness-2020-division-1-mens-tournament/MDataFiles_Stage1/MRegularSeasonCompactResults.csv' ) | Google Cloud & NCAA® ML Competition 2020-NCAAM |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.