kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
4,657,296 | <compute_test_metric><EOS> | output = pd.DataFrame({'PassengerId': X_test.index,
'Survived': preds_test})
output.to_csv('submission.csv', index=False ) | Titanic - Machine Learning from Disaster |
3,238,811 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<split> | warnings.simplefilter(action='ignore', category=FutureWarning)
| Titanic - Machine Learning from Disaster |
3,238,811 | gkf = GroupKFold(n_splits=5 ).split(X=df_train.question_body, groups=df_train.question_body)
outputs = compute_output_arrays(df_train, output_categories)
inputs = compute_input_arays(df_train, input_categories, train_add_features,tokenizer, MAX_SEQUENCE_LENGTH)
test_inputs = compute_input_arays(df_test, input_catego... | train = pd.read_csv('.. /input/train.csv')
test = pd.read_csv('.. /input/test.csv')
print(train.shape)
print(test.shape ) | Titanic - Machine Learning from Disaster |
3,238,811 | histories = []
count = 1
for fold,(train_idx, valid_idx)in enumerate(gkf):
if fold < 3:
K.clear_session()
model = bert_model()
train_inputs = [inputs[i][train_idx] for i in range(len(inputs)) ]
train_outputs = outputs[train_idx]
valid_inputs = [inputs[i][valid_idx] for i in range(len(test_inputs)) ]
valid_outputs = out... | test.drop(['Ticket','Cabin'],axis=1, inplace=True)
test.set_index('PassengerId',inplace=True)
train.drop(['Ticket','Cabin'],axis=1, inplace=True)
train.set_index('PassengerId',inplace=True)
train.head() | Titanic - Machine Learning from Disaster |
3,238,811 | test_predictions = [histories[i].test_predictions for i in range(len(histories)) ]
test_predictions = [np.average(test_predictions[i], axis=0)for i in range(len(test_predictions)) ]
test_predictions = np.mean(test_predictions, axis=0)
df_sub.iloc[:, 1:] = test_predictions
df_sub.to_csv('submission.csv', index=False )<... | test['title'] = test.Name.str.extract('([A-Za-z]+)\.')
test['title'].replace(['Mlle','Mme','Ms','Major','Lady','Countess','Jonkheer','Col','Rev','Capt','Sir','Don','Dona','Dr'],['Miss','Miss','Miss','Mr','Mrs','Mrs','Other','Other','Other','Mr','Mr','Mr','Miss','Mr'],inplace=True)
test = pd.concat([test.drop(['title'... | Titanic - Machine Learning from Disaster |
3,238,811 | import pandas as pd<import_modules> | features_numeric = ['Age','SibSp','Parch','Fare']
features_label = ['Pclass','Sex','Embarked']
test = test.fillna(test[features_numeric].mean())
test = test.fillna(test[features_label].mode().iloc[0])
train = train.fillna(train[features_numeric].mean())
train = train.fillna(train[features_label].mode().iloc[0])
tra... | Titanic - Machine Learning from Disaster |
3,238,811 | import pandas as pd<load_from_csv> | test = pd.concat([test.drop(['Sex'],axis=1), pd.get_dummies(test[['Sex']], drop_first=True)], axis=1)
train = pd.concat([train.drop(['Sex'],axis=1), pd.get_dummies(train[['Sex']], drop_first=True)], axis=1)
test = pd.concat([test.drop(['Embarked'],axis=1), pd.get_dummies(test[['Embarked']], drop_first=True)], axis=1)... | Titanic - Machine Learning from Disaster |
3,238,811 | limit = 20_000_000
usecols = ['ip', 'app', 'device', 'os', 'channel', 'click_time', 'is_attributed']<load_from_csv> | Titanic - Machine Learning from Disaster | |
3,238,811 | competition_data = pd.read_csv('.. /input/talkingdata-adtracking-fraud-detection/train.csv', nrows=limit, usecols=usecols, parse_dates=['click_time'] )<count_values> | X,y = train.drop(['Survived'],axis=1), train['Survived']
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
print(X.shape)
print(X_train.shape)
print(X_test.shape)
print(y.shape)
print(y_train.shape)
print(y_test.shape ) | Titanic - Machine Learning from Disaster |
3,238,811 | competition_data['is_attributed'].value_counts()<count_values> | classifiers = [
KNeighborsClassifier(3), SVC(probability=True), DecisionTreeClassifier() , RandomForestClassifier() , AdaBoostClassifier() ,
GradientBoostingClassifier() , GaussianNB() , LinearDiscriminantAnalysis() , QuadraticDiscriminantAnalysis() , LogisticRegression() ,
XGBClassifier()
]
log_cols = ["Classifier", "... | Titanic - Machine Learning from Disaster |
3,238,811 | competition_data['is_attributed'].value_counts(normalize=True )<load_from_csv> | xgb = XGBClassifier()
xgb.fit(X_train, y_train, early_stopping_rounds=50, eval_metric='auc', eval_set=[(X_train, y_train),(X_test, y_test)] ) | Titanic - Machine Learning from Disaster |
3,238,811 | click_data = pd.read_csv('.. /input/feature-engineering-data/train_sample.csv', nrows=limit, usecols=usecols, parse_dates=['click_time'] )<count_values> | survivors = xgb.predict(test)
submission = pd.DataFrame({'PassengerId':test.index,'Survived':survivors})
submission.head() | Titanic - Machine Learning from Disaster |
3,238,811 | <count_values><EOS> | submission.to_csv('Titanic_Survivors_Predictions.csv',index=False ) | Titanic - Machine Learning from Disaster |
2,722,461 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<load_from_csv> | warnings.filterwarnings("ignore" ) | Titanic - Machine Learning from Disaster |
2,722,461 | competition_test_data = pd.read_csv('.. /input/talkingdata-adtracking-fraud-detection/test.csv', parse_dates=['click_time'] )<data_type_conversions> | df = pd.read_csv('.. /input/train.csv')
df.head() | Titanic - Machine Learning from Disaster |
2,722,461 | clicks = click_data.copy()
clicks['day'] = clicks['click_time'].dt.day.astype('uint8')
clicks['hour'] = clicks['click_time'].dt.hour.astype('uint8')
clicks['minute'] = clicks['click_time'].dt.minute.astype('uint8')
clicks['second'] = clicks['click_time'].dt.second.astype('uint8' )<data_type_conversions> | test_df = pd.read_csv('.. /input/test.csv')
test_df.head() | Titanic - Machine Learning from Disaster |
2,722,461 | competition_test_data = competition_test_data.copy()
competition_test_data['day'] = competition_test_data['click_time'].dt.day.astype('uint8')
competition_test_data['hour'] = competition_test_data['click_time'].dt.hour.astype('uint8')
competition_test_data['minute'] = competition_test_data['click_time'].dt.minute.ast... | test_df.drop(['PassengerId'],axis=1,inplace=True)
test_df.head() | Titanic - Machine Learning from Disaster |
2,722,461 |
<categorify> | concated_df = pd.concat([train_df,test_df])
concated_df.head() | Titanic - Machine Learning from Disaster |
2,722,461 | unknown_value = -1
cat_features = ['ip', 'app', 'device', 'os', 'channel']
for feature in cat_features:
encoder = preprocessing.LabelEncoder()
encoder.fit(clicks[feature])
le_dict = dict(zip(encoder.classes_, encoder.transform(encoder.classes_)))
encoded = clicks[feature].apply(lambda x: le_dict.get(x, unknown_value)... | from sklearn import preprocessing as prep | Titanic - Machine Learning from Disaster |
2,722,461 | train_ip_labels_unknowns = sum(clicks['ip_labels'] == unknown_value)
train_ip_labels_unknowns<filter> | le = prep.LabelEncoder()
concated_df.Sex =le.fit_transform(concated_df.Sex)
df.Sex[0:10] | Titanic - Machine Learning from Disaster |
2,722,461 | compet_test_ip_labels_unknowns = sum(competition_test_data['ip_labels'] == unknown_value)
compet_test_ip_labels_unknowns<define_variables> | concated_df.drop(['Cabin'],axis=1,inplace=True)
concated_df.head() | Titanic - Machine Learning from Disaster |
2,722,461 | my_own_metrics={'limit': min(limit, clicks.shape[0]),
'competition_test_data':competition_test_data.shape[0],
'train ip_labels unknowns': train_ip_labels_unknowns,
'compet_test ip_labels unknowns':compet_test_ip_labels_unknowns}
my_own_metrics<sort_values> | NameSplit = concated_df.Name.str.split('[,.]')
NameSplit.head() | Titanic - Machine Learning from Disaster |
2,722,461 | feature_cols = ['day', 'hour', 'minute', 'second',
'ip_labels', 'app_labels', 'device_labels',
'os_labels', 'channel_labels']
valid_fraction = 0.1
clicks_srt = clicks.sort_values('click_time')
valid_rows = int(len(clicks_srt)* valid_fraction)
train = clicks_srt[:-valid_rows * 2]
valid = clicks_srt[-valid_rows * 2:-va... | titles = [str.strip(name[1])for name in NameSplit.values]
titles[:10] | Titanic - Machine Learning from Disaster |
2,722,461 | dtrain = lgb.Dataset(train[feature_cols], label=train['is_attributed'])
dvalid = lgb.Dataset(valid[feature_cols], label=valid['is_attributed'])
dtest = lgb.Dataset(test[feature_cols], label=test['is_attributed'])
param = {'num_leaves': 64, 'objective': 'binary'}
param['metric'] = 'auc'
num_round = 1000
<train_model... | concated_df['Title'] = titles
concated_df.head() | Titanic - Machine Learning from Disaster |
2,722,461 | validation_metrics = {}
bst = lgb.train(param,
dtrain,
num_round,
valid_sets=[dvalid],
early_stopping_rounds=10,
evals_result=validation_metrics,
verbose_eval=10 )<count_values> | concated_df.Title.values[concated_df.Title.isin(['Mme', 'Mmle'])] = 'Mmle' | Titanic - Machine Learning from Disaster |
2,722,461 | bst.num_trees()<compute_train_metric> | concated_df.Title.values[concated_df.Title.isin(['Capt', 'Don', 'Major', 'Sir'])] = 'Sir'
concated_df.Title.values[concated_df.Title.isin(['Dona', 'Lady', 'the Countess', 'Jonkheer'])] = 'Lady' | Titanic - Machine Learning from Disaster |
2,722,461 | ypred = bst.predict(test[feature_cols])
score = metrics.roc_auc_score(test['is_attributed'], ypred)
print(f"Test score: {score}" )<feature_engineering> | concated_df.Title = le.fit_transform(concated_df.Title)
concated_df.head() | Titanic - Machine Learning from Disaster |
2,722,461 | my_own_metrics['test score'] = score<define_variables> | concated_df['FamilySize'] = concated_df.SibSp.values + concated_df.Parch.values + 1 | Titanic - Machine Learning from Disaster |
2,722,461 | feature_cols + ['click_id']<create_dataframe> | concated_df['Surname'] = surnames
concated_df['FamilyID'] = concated_df.Surname.str.cat(concated_df.FamilySize.astype(str),sep='')
concated_df.head() | Titanic - Machine Learning from Disaster |
2,722,461 | competition_test_data = competition_test_data[feature_cols + ['click_id']]<predict_on_test> | concated_df.FamilyID.values[concated_df.FamilySize.values <= 2] = 'Small'
concated_df.head() | Titanic - Machine Learning from Disaster |
2,722,461 | competition_predictions = bst.predict(competition_test_data[feature_cols] )<create_dataframe> | concated_df.FamilyID.value_counts() | Titanic - Machine Learning from Disaster |
2,722,461 | competition_predictions_df = pd.DataFrame(competition_predictions, columns=['is_attributed'])
competition_predictions_df<prepare_output> | freq = list(dict(zip(concated_df.FamilyID.value_counts().index.tolist() , concated_df.FamilyID.value_counts().values)).items())
type(freq ) | Titanic - Machine Learning from Disaster |
2,722,461 | competition_predictions_df['click_id'] = competition_test_data['click_id']
competition_predictions_df = competition_predictions_df[['click_id', 'is_attributed']]
competition_predictions_df<count_values> | freq[freq[:,1].astype(int)<= 2].shape | Titanic - Machine Learning from Disaster |
2,722,461 | competition_predictions_df['is_attributed'].value_counts().sort_index()<save_to_csv> | freq = freq[freq[:,1].astype(int)<= 2] | Titanic - Machine Learning from Disaster |
2,722,461 | competition_predictions_df.to_csv('submission.csv', index=False )<find_best_params> | concated_df.FamilyID.values[concated_df.FamilyID.isin(freq[:,0])] = 'Small'
concated_df.FamilyID.value_counts() | Titanic - Machine Learning from Disaster |
2,722,461 | my_own_metrics['private score'] = 0.83173
my_own_metrics['public score'] = 0.82499
my_own_metrics<import_modules> | concated_reduce['Age'].fillna(concated_reduce['Age'].median() , inplace=True)
concated_reduce['Fare'].fillna(concated_reduce['Fare'].median() , inplace=True ) | Titanic - Machine Learning from Disaster |
2,722,461 | import os
import gc
from operator import methodcaller
import numpy as np
import pandas as pd
from sklearn.preprocessing import RobustScaler as RobustScaler
from scipy.stats import skew, norm
from scipy.stats import boxcox_normmax, boxcox
from scipy.special import boxcox1p
import lightgbm as lgb
from lightgbm import LGB... | train_final = concated_reduce.iloc[:891].copy()
test_final = concated_reduce.iloc[891:].copy() | Titanic - Machine Learning from Disaster |
2,722,461 | g_enable_log = True
def log(log_str):
if g_enable_log:
print(log_str)
def g() :
return gc.collect()
def delete(*obj_list):
for obj in obj_list:
del obj
gc_cnt = g()
if gc_cnt > 0:
log("unreachable_obj_found: {}".format(gc_cnt))
def init_robust_boxcox() :
def robust_boxcox(data:pd.Series, lmbda=None):
if lmbda is None:... | X = train_final.values
X | Titanic - Machine Learning from Disaster |
2,722,461 |
<categorify> | y = surv_col.values
y | Titanic - Machine Learning from Disaster |
2,722,461 | g_scaler_dict = {}
g_boxcox_lmbda_dict = {}
def box_cox_trans(df, fea_name, sv_policy):
df[fea_name] = df[fea_name].astype('float64'); g()
df.loc[df[fea_name] <= 0,(fea_name)] = 0.000001
if sv_policy == 'new_and_save':
df[fea_name], lmbda = robust_boxcox(df[fea_name]); g()
g_boxcox_lmbda_dict[fea_name] = lmbda
elif s... | test_data = test_final.values
test_data | Titanic - Machine Learning from Disaster |
2,722,461 | def add_features(df, is_boxcox=False, is_scaler=False, save_transformer='reuse'):
sv = save_transformer
bc = is_boxcox
s = None;
if is_scaler:
s = RobustScaler()
df = add_grp_nxt_clk_intv(df, ['ip','os','device','app'], bc=None,scl=s,sv=sv);g()
df = add_grp_count(df, ['dd','hh','app','channel'], bc=bc,scl=s,sv=sv);g(... | from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout | Titanic - Machine Learning from Disaster |
2,722,461 | g_categorical_features = ['app', 'device', 'os', 'channel', 'hh']
g_non_train_columns = ['click_time', 'dd', 'ip']
def get_file_spec(is_test_file):
dtypes = {'ip':'uint32','app':'uint16','device':'uint8','os':'uint16',
'channel':'uint16','is_attributed':'int8','click_id':'int32'}
date_columns = ['click_time']
test_file... | model = Sequential()
model.add(Dense(32, init = 'uniform', activation='relu', input_dim = 10))
model.add(Dense(64, init = 'uniform', activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(64, init = 'uniform', activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(12, init = 'uniform', activation='relu'))
mod... | Titanic - Machine Learning from Disaster |
2,722,461 | def read_data_file(file_path, is_test_file):
print('read file [is_test_file={}]: {}'.format(is_test_file, file_path))
dtypes, date_columns, file_columns = get_file_spec(is_test_file)
df = pd.read_csv(file_path, parse_dates=date_columns,usecols=file_columns,dtype=dtypes)
df['dd'] = pd.to_datetime(df.click_time ).dt.da... | model.fit(X,y, epochs=500, batch_size = 64, verbose = 1 ) | Titanic - Machine Learning from Disaster |
2,722,461 | def prep_data_set_full_data() :
log_template="append bkt {}: train.shape={}; vldt.shape={}; test.shape={}"
df_train, df_vldt, df_test = process_ip_bucket(
ip_bucket=0, is_down_sample=g_is_down_sample,
majority_multiply=g_majority_multiply,
tsfm_sv_policy='new_and_save')
print(log_template.format(0, df_train.shape, df... | pred = model.predict(test_data ) | Titanic - Machine Learning from Disaster |
2,722,461 | def default_model() :
lgb_default = LGBMClassifier()
return lgb_default.set_params(
objective = 'binary',
metric = 'auc',
boosting_type = 'gbdt',
verbose = 1,
nthread = 4,
iid = False,
two_round = True
)
def gbtd_base_001() :
return default_model().set_params(
subsample = 0.8,
subsample_freq = 1,
subsample_for_bin ... | outputBin = np.zeros(0)
for i in pred:
if i <=.5:
outputBin = np.append(outputBin, 0)
else:
outputBin = np.append(outputBin, 1)
output = np.array(outputBin ).astype(int ) | Titanic - Machine Learning from Disaster |
2,722,461 | g_fit_params = {
'categorical_feature' : g_categorical_features,
'early_stopping_rounds' : 25,
'verbose' : 10,
'eval_metric' : 'auc'
}<train_model> | d = {'PassengerId':pessengerId, 'Survived':output} | Titanic - Machine Learning from Disaster |
2,722,461 | g_base_model = g_base_models['gbdt_base_001']<split> | final_df = pd.DataFrame(data=d ) | Titanic - Machine Learning from Disaster |
2,722,461 | with timer_memory('prep_feature_target_full_data'):
X_train, y_train, g_X_vldt, g_y_vldt, g_df_test = prep_feature_target_full_data()<train_model> | final = final_df.to_csv('new_result.csv',index=False)
final | Titanic - Machine Learning from Disaster |
2,722,461 | with timer_memory('fit_model'):
g_model_fitted = fit_model(X_train, y_train, g_X_vldt, g_y_vldt, g_base_model )<save_to_csv> | rf = RandomForestClassifier(n_estimators=350, max_depth=15, random_state=42)
print("train accuracy: {} ".format(rf.fit(X, y ).score(X, y)))
| Titanic - Machine Learning from Disaster |
2,722,461 | def predict_and_submit(model_fitted, num_iteration):
sub = pd.DataFrame()
sub['click_id'] = g_df_test.index
sub['click_id'] = sub['click_id'].astype('int')
pred_prob = model_fitted.predict_proba(X=g_df_test, num_iteration=num_iteration)
sub['is_attributed'] = pred_prob[:,1].reshape(-1,1)
sub.to_csv('submit.csv', ind... | rf_pred = rf.predict(test_data ) | Titanic - Machine Learning from Disaster |
2,722,461 | with timer_memory('predict_and_sumit'):
submit = predict_and_submit(g_model_fitted, g_model_fitted.best_iteration_)
submit.head()<predict_on_test> | r = {'PassengerId':pessengerId, 'Survived':rf_pred} | Titanic - Machine Learning from Disaster |
2,722,461 | g_y_pred_proba_vldt = g_model_fitted.predict_proba(X=g_X_vldt, num_iteration=g_model_fitted.best_iteration_)[:,1]
g_y_pred_label_vldt = g_model_fitted.predict(X=g_X_vldt, num_iteration=g_model_fitted.best_iteration_)
g_y_vldt.value_counts()<compute_train_metric> | final_rf = pd.DataFrame(data=r ) | Titanic - Machine Learning from Disaster |
2,722,461 | report = classification_report(g_y_vldt, g_y_pred_label_vldt, target_names=['is_not_attributed','is_attributed'])
print(report )<merge> | final_rf = final_df.to_csv('random_forest_result.csv',index=False)
final_rf | Titanic - Machine Learning from Disaster |
10,638,803 | df_plot = random_down_sample(
g_X_vldt.merge(g_y_vldt, left_index=True, right_index=True),
majority_multiply=g_majority_multiply, target_col_name='is_attributed',
minority_val = 1, majority_val = 0); g()
df_plot['is_attributed'].value_counts()<train_on_grid> | train=pd.read_csv(".. /input/titanic/train.csv")
test=pd.read_csv(".. /input/titanic/test.csv" ) | Titanic - Machine Learning from Disaster |
10,638,803 | def grid_search(X_train, y_train, X_vldt, y_vldt, base_model, param_grid):
estimator_lst,grid_point_lst,precision_lst,recall_lst,f1_lst,auc_lst=[],[],[],[],[],[]
for grid_point in list(ParameterGrid(param_grid)) :
print(f'----- grid_point:
{grid_point}')
base_model = base_model.set_params(**grid_point)
base_model = b... | ( train.isnull() ["Cabin"]==(train["Pclass"]==1)).value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | import csv
import time
from csv import DictReader
from math import exp, log, sqrt
from numba import jit
import pandas as pd
from random import randint<define_variables> | ( test.isnull() ["Cabin"]==(test["Pclass"]==1)).value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | data_path = ".. /input/"
train = data_path+'train.csv'
train_s = data_path+'train_sample.csv'
test = data_path+'test.csv'
submission = 'submission.csv'<init_hyperparams> | train["Cabin"].fillna("NC",inplace=True)
test["Cabin"].fillna("NC",inplace=True ) | Titanic - Machine Learning from Disaster |
10,638,803 | alpha = 0.011
beta = 0.000000001
L1 = 0.0000001
L2 = 0.0001<init_hyperparams> | train["Cabin"].isnull().value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | D = 2 ** 26
interaction = False<define_variables> | test["Cabin"].isnull().value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | epoch = 2
holdday = ''<choose_model_class> | train["Embarked"].fillna(train["Embarked"].mode() [0],inplace=True)
test["Fare"].fillna(test["Fare"].median() ,inplace=True ) | Titanic - Machine Learning from Disaster |
10,638,803 | class ftrl_proximal(object):
def __init__(self, alpha, beta, L1, L2, D):
self.alpha = alpha
self.beta = beta
self.L1 = L1
self.L2 = L2
self.D = D
self.n = [0.] * D
self.z = [0.] * D
self.w = {}
def _indices(self, x):
yield 0
for index in x:
yield index
def predict(self, x):
alpha = self.alpha
beta = self.beta
L1 ... | def get_title(name):
title_search=re.search('([A-Za-z]+)\.',name)
if(title_search):
return title_search.group(1)
return ""
train["Title"]=train["Name"].apply(get_title)
test["Title"]=test["Name"].apply(get_title)
train.head() | Titanic - Machine Learning from Disaster |
10,638,803 | def temps(df):
date, time = df['click_time'].split(' ')
hour = time.split(':')[0]
h=int(hour)
df["Nuit"]=0
df["Matin"]=0
df["Apres-midi"]=0
df["Soir"]=0
if(h>=18):
df["Soir"]=1
if(h>=0 and h<8):
df["Nuit"]=1
if(h>=8 and h<12):
df["Matin"]=1
if(h>=12 and h<18):
df["Apres-midi"]=1<compute_test_metric> | train["Title"].value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | learner = ftrl_proximal(alpha, beta, L1, L2, D )<predict_on_test> | train["Title"]=train["Title"].replace(['Dr','Rev','Major','Col','Capt','Sir','Don','Lady','Countess','Jonkheer'],'Super')
train["Title"]=train["Title"].replace(['Mlle','Ms'],'Miss')
train["Title"]=train["Title"].replace('Mme','Mrs')
train["Title"].value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | start_time = time.time()
for e in range(epoch):
for t, x, y, _ in data(train, D):
p = learner.predict(x)
learner.update(x, p, y)
if t%1000000 == 0:
print("ligne: %sM ; %sMin "%(int(t/1e+6), '%0.0f'%(( time.time() -start_time)/60)) )<save_to_csv> | test["Title"].value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | start_time = time.time()
with open(submission, 'w')as outfile:
outfile.write('click_id,is_attributed
')
for t, x, y, click_id in data(test, D):
p = learner.predict(x)
outfile.write('%s,%s
' %(click_id, str(p)))
if t%1000000 == 0:
print("Test Rows Processed: %sM ; %ss "%(int(t/1e+6), '%0.0f'%(time.time() -start_time)... | test["Title"]=test["Title"].replace('Ms','Miss')
test["Title"]=test["Title"].replace(["Col","Rev","Dr","Dona"],"Super")
test["Title"].value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | pd.set_option('display.max_columns', 100 )<define_variables> | train.drop("Name",axis=1,inplace=True)
train.head() | Titanic - Machine Learning from Disaster |
10,638,803 | VALIDATE = False
VALID_SIZE = 0.90
VALIDATE_KFOLDS = True
NUMBER_KFOLDS = 5
SAMPLE = True
RANDOM_STATE = 2018
MAX_ROUNDS = 1000
EARLY_STOP = 50
OPT_ROUNDS = 650
skiprows = range(1,109903891)
nrows = 75000000
SAMPLE_SIZE = 1
output_filename = 'submission.csv'
IS_LOCAL = False
if(IS_LOCAL):
PATH = '.. /input/talkingdata... | test.drop("Name",axis=1,inplace=True)
test.head() | Titanic - Machine Learning from Disaster |
10,638,803 | dtypes = {
'ip' : 'uint32',
'app' : 'uint16',
'device' : 'uint16',
'os' : 'uint16',
'channel' : 'uint16',
'is_attributed' : 'uint8',
'click_id' : 'uint32'
}
train_cols = ['ip','app','device','os', 'channel', 'click_time', 'is_attributed']
if SAMPLE:
trainset = pd.read_csv(PATH+"train_sample.csv", dtype=dtypes, usecols=... | train=pd.get_dummies(train,columns=["Sex","Title","Embarked"])
train.head() | Titanic - Machine Learning from Disaster |
10,638,803 | def missing_data(data):
total = data.isnull().sum().sort_values(ascending = False)
percent =(data.isnull().sum() /data.isnull().count() *100 ).sort_values(ascending = False)
return pd.concat([total, percent], axis=1, keys=['Total', 'Percent'] )<count_missing_values> | test=pd.get_dummies(test,columns=["Sex","Title","Embarked"])
test.head() | Titanic - Machine Learning from Disaster |
10,638,803 | missing_data(trainset )<count_missing_values> | rfr1=RandomForestRegressor()
col_age=["Title_Master","Title_Miss","Title_Mr","Title_Mrs","Title_Super","Fare","Parch","SibSp"]
x_list1=[]
x_list2=[]
for i in range(len(train)) :
if train["Age"].isnull().loc[i]==False:
x_list1.append(i)
else:
x_list2.append(i)
X_agetrain=train.loc[x_list1,col_age]
y_agetrain=train.loc... | Titanic - Machine Learning from Disaster |
10,638,803 | missing_data(testset )<feature_engineering> | train["Age"].isnull().value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | trainset['year'] = pd.to_datetime(trainset.click_time ).dt.year
trainset['month'] = pd.to_datetime(trainset.click_time ).dt.month
trainset['day'] = pd.to_datetime(trainset.click_time ).dt.day
trainset['hour'] = pd.to_datetime(trainset.click_time ).dt.hour
trainset['min'] = pd.to_datetime(trainset.click_time ).dt.minute... | rfr2=RandomForestRegressor()
col_age=["Title_Master","Title_Miss","Title_Mr","Title_Mrs","Title_Super","Fare","Parch","SibSp"]
x_list_1=[]
x_list_2=[]
for i in range(len(test)) :
if test["Age"].isnull().loc[i]==False:
x_list_1.append(i)
else:
x_list_2.append(i)
X_agetest=test.loc[x_list_1,col_age]
y_agetest=test.loc[... | Titanic - Machine Learning from Disaster |
10,638,803 | def show_max_clean(df,gp,agg_name,agg_type,show_max):
del gp
if show_max:
print(agg_name + " max value = ", df[agg_name].max())
df[agg_name] = df[agg_name].astype(agg_type)
gc.collect()
return(df)
def perform_count(df, group_cols, agg_name, agg_type='uint32', show_max=False, show_agg=True):
if show_agg:
print("Aggre... | test["Age"].isnull().value_counts() | Titanic - Machine Learning from Disaster |
10,638,803 | testset['year'] = pd.to_datetime(testset.click_time ).dt.year
testset['month'] = pd.to_datetime(testset.click_time ).dt.month
testset['day'] = pd.to_datetime(testset.click_time ).dt.day
testset['hour'] = pd.to_datetime(testset.click_time ).dt.hour
testset['min'] = pd.to_datetime(testset.click_time ).dt.minute
testset['... | train=pd.get_dummies(train,columns=["Fare_bin","Age_bin"])
test=pd.get_dummies(test,columns=["Fare_bin","Age_bin"])
train.head() | Titanic - Machine Learning from Disaster |
10,638,803 | testset = perform_countuniq(testset, ['ip'], 'channel', 'X0', 'uint8', show_max=True); gc.collect()
testset = perform_cumcount(testset, ['ip', 'device', 'os'], 'app', 'X1', show_max=True); gc.collect()
testset = perform_countuniq(testset, ['ip', 'day'], 'hour', 'X2', 'uint8', show_max=True); gc.collect()
testset = perf... | train.drop(["Age","Fare","Ticket"],axis=1,inplace=True)
test.drop(["Age","Fare","Ticket"],axis=1,inplace=True)
train.head() | Titanic - Machine Learning from Disaster |
10,638,803 | start = datetime.now()
len_train = len(trainset)
gc.collect()
most_freq_hours_in_test_data = [4, 5, 9, 10, 13, 14]
least_freq_hours_in_test_data = [6, 11, 15]
def prep_data(df):
df['hour'] = pd.to_datetime(df.click_time ).dt.hour.astype('uint8')
df['day'] = pd.to_datetime(df.click_time ).dt.day.astype('uint8')
df.dr... | print(train["Cabin"].values.tolist() ) | Titanic - Machine Learning from Disaster |
10,638,803 | trainset = prep_data(trainset)
gc.collect()
params = {
'boosting_type': 'gbdt',
'objective': 'binary',
'metric':'auc',
'learning_rate': 0.1,
'num_leaves': 9,
'max_depth': 5,
'min_child_samples': 100,
'max_bin': 100,
'subsample': 0.9,
'subsample_freq': 1,
'colsample_bytree': 0.7,
'min_child_weight': 0,
'min_split_gain'... | train["Cabin_encoding"]=train["Pclass"]
for i in range(len(train)) :
if(train["Cabin"].loc[i]=="NC"):
train["Cabin_encoding"].loc[i]=1000
else:
if(len(train["Cabin"].loc[i])>4):
train["Cabin_encoding"].loc[i]=500
elif(len(train["Cabin"].loc[i])>1):
temp=train["Cabin"].loc[i]
train["Cabin_encoding"].loc[i]=(ord(temp[0])... | Titanic - Machine Learning from Disaster |
10,638,803 | if VALIDATE:
train_df, val_df = train_test_split(trainset, test_size=VALID_SIZE, random_state=RANDOM_STATE, shuffle=True)
dtrain = lgb.Dataset(train_df[predictors].values,
label=train_df[target].values,
feature_name=predictors,
categorical_feature=categorical)
del train_df
gc.collect()
dvalid = lgb.Dataset(val_df[pre... | test["Cabin_encoding"]=test["Pclass"]
for i in range(len(test)) :
if(test["Cabin"].loc[i]=="NC"):
test["Cabin_encoding"].loc[i]=1000
else:
if(len(test["Cabin"].loc[i])>4):
test["Cabin_encoding"].loc[i]=500
elif(len(test["Cabin"].loc[i])>1):
temp=test["Cabin"].loc[i]
test["Cabin_encoding"].loc[i]=(ord(temp[0])-ord('A'))... | Titanic - Machine Learning from Disaster |
10,638,803 | test_cols = ['ip','app','device','os', 'channel', 'click_time', 'click_id']
test_df = prep_data(testset)
gc.collect()
sub = pd.DataFrame()
sub['click_id'] = test_df['click_id']
sub['is_attributed'] = model.predict(test_df[predictors])
sub.to_csv(output_filename, index=False, float_format='%.9f')
<define_variables> | train.drop("Cabin",axis=1,inplace=True)
train.head() | Titanic - Machine Learning from Disaster |
10,638,803 | FILENO= 1
debug=0
<merge> | test.drop("Cabin",axis=1,inplace=True)
test.head() | Titanic - Machine Learning from Disaster |
10,638,803 | def do_agg(df, group_cols, agg_type='uint8', show_max=False, show_agg=True):
agg_name='{}_agg'.format('_'.join(group_cols))
if show_agg:
print("
Aggregating by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols].groupby(group_cols ).size().rename(agg_name ).to_frame().reset_index()
df = df.merge(gp, on=gr... | train["Cabin_encoding"]=train["Cabin_encoding"]/1000
train.info() | Titanic - Machine Learning from Disaster |
10,638,803 | def do_count(df, group_cols, counted, agg_type='uint8', show_max=False, show_agg=True):
agg_name= '{}_by_{}_count'.format(( '_'.join(group_cols)) ,(counted))
if show_agg:
print("
Counting ", counted, " by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols+[counted]].groupby(group_cols)[counted].count().re... | train.head()
test["Cabin_encoding"]=test["Cabin_encoding"]/1000 | Titanic - Machine Learning from Disaster |
10,638,803 | def do_countuniq(df, group_cols, counted, agg_type='uint8', show_max=False, show_agg=True):
agg_name= '{}_by_{}_countuniq'.format(( '_'.join(group_cols)) ,(counted))
if show_agg:
print("
Counting unqiue ", counted, " by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols+[counted]].groupby(group_cols)[coun... | X=train.drop(["Survived","PassengerId"],axis=1)
y=train["Survived"]
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=100 ) | Titanic - Machine Learning from Disaster |
10,638,803 | def do_cumcount(df, group_cols, counted,agg_type='uint16', show_max=False, show_agg=True):
agg_name= '{}_by_{}_cumcount'.format(( '_'.join(group_cols)) ,(counted))
if show_agg:
print("
Cumulative count by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols+[counted]].groupby(group_cols)[counted].cumcount()... | ids=test["PassengerId"]
Xtest=test.drop(["PassengerId"],axis=1)
pred_1=lr.predict(Xtest)
pred_2=ranF.predict(Xtest)
pred_3=abc.predict(Xtest)
pred_4=gbc.predict(Xtest)
pred_5=clf.predict(Xtest)
pred=[]
for i in range(len(pred_1)) :
l_0=1
l_1=1
if(pred_1[i]==0):
l_0*=p1[0,0]
l_1*=p1[1,0]
else:
l_0*=p1[0,1]
l_1*=p1... | Titanic - Machine Learning from Disaster |
10,638,803 | def do_mean(df, group_cols, counted, agg_type='float16', show_max=False, show_agg=True):
agg_name= '{}_by_{}_mean'.format(( '_'.join(group_cols)) ,(counted))
if show_agg:
print("
Calculating mean of ", counted, " by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols+[counted]].groupby(group_cols)[counted]... | Survived=pd.Series(pred_5)
output=pd.concat([ids,Survived],axis=1)
output.columns=["PassengerId","Survived"] | Titanic - Machine Learning from Disaster |
10,638,803 | <drop_column><EOS> | output.to_csv("submission.csv",index=False)
output.head() | Titanic - Machine Learning from Disaster |
5,636,558 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<define_variables> | np.random.seed(42 ) | Titanic - Machine Learning from Disaster |
5,636,558 | nrows=184903891-1
nchunk=12000000
val_size=1000000
frm=nrows-84903891
if debug:
frm=0
nchunk=100000
val_size=10000
to=frm+nchunk
sub=DO(frm,to,FILENO )<define_variables> | train_data = pd.read_csv('/kaggle/input/titanic/train.csv', index_col=0)
test_data = pd.read_csv('/kaggle/input/titanic/test.csv',index_col=0)
train_data.head() | Titanic - Machine Learning from Disaster |
5,636,558 | FILENO= 24
debug=0
<merge> | X = train_data.drop(columns=['Survived'])
y = train_data.Survived | Titanic - Machine Learning from Disaster |
5,636,558 | def do_count(df, group_cols, agg_type='uint32', show_max=False, show_agg=True):
agg_name='{}count'.format('_'.join(group_cols))
if show_agg:
print("
Aggregating by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols][group_cols].groupby(group_cols ).size().rename(agg_name ).to_frame().reset_index()
df = df... | train_data[train_data.Age <= 15].Survived.value_counts(normalize=True ) | Titanic - Machine Learning from Disaster |
5,636,558 | def do_countuniq(df, group_cols, counted, agg_type='uint32', show_max=False, show_agg=True):
agg_name= '{}_by_{}_countuniq'.format(( '_'.join(group_cols)) ,(counted))
if show_agg:
print("
Counting unqiue ", counted, " by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols+[counted]].groupby(group_cols)[cou... | print(train_data[train_data.Sex == 'male'].Survived.value_counts(normalize=True))
print('-'*40)
print(train_data[train_data.Sex == 'female'].Survived.value_counts(normalize=True)) | Titanic - Machine Learning from Disaster |
5,636,558 | def do_cumcount(df, group_cols, counted,agg_type='uint16', show_max=False, show_agg=True):
agg_name= '{}_by_{}_cumcount'.format(( '_'.join(group_cols)) ,(counted))
if show_agg:
print("
Cumulative count by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols+[counted]].groupby(group_cols)[counted].cumcount()... | train_data.groupby('Pclass' ).Survived.value_counts(normalize=True, sort=False ) | Titanic - Machine Learning from Disaster |
5,636,558 | def do_mean(df, group_cols, counted, agg_type='float16', show_max=False, show_agg=True):
agg_name= '{}_by_{}_mean'.format(( '_'.join(group_cols)) ,(counted))
if show_agg:
print("
Calculating mean of ", counted, " by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols+[counted]].groupby(group_cols)[counted]... | ranks = X['Name'].str.extract(r'\b(\w+)\.')
ranks[0].value_counts() | Titanic - Machine Learning from Disaster |
5,636,558 | def do_var(df, group_cols, counted, agg_type='float16', show_max=False, show_agg=True):
agg_name= '{}_by_{}_var'.format(( '_'.join(group_cols)) ,(counted))
if show_agg:
print("
Calculating variance of ", counted, " by ", group_cols , '...and saved in', agg_name)
gp = df[group_cols+[counted]].groupby(group_cols)[counte... | ranks[train_data.Age.isna() ][0].value_counts() | Titanic - Machine Learning from Disaster |
5,636,558 | if debug:
print('*** debug parameter set: this is a test run for debugging purposes ***')
def lgb_modelfit_nocv(params, dtrain, dvalid, predictors, target='target', objective='binary', metrics='auc',
feval=None, early_stopping_rounds=50, num_boost_round=3000, verbose_eval=10, categorical_features=None):
lgb_params = {... | missing_age_ranks = ranks[train_data.Age.isna() ][0].value_counts().index.values
missing_age_ranks | Titanic - Machine Learning from Disaster |
5,636,558 | def DO(frm,to,fileno):
dtypes = {
'ip' : 'uint32',
'app' : 'uint16',
'device' : 'uint8',
'os' : 'uint16',
'channel' : 'uint16',
'is_attributed' : 'uint8',
'click_id' : 'uint32',
}
print('loading train data...',frm,to)
train_df = pd.read_csv(".. /input/train.csv", parse_dates=['click_time'], skiprows=range(1,frm), nrow... | age_na_fills = {}
for rank in missing_age_ranks:
age_na_fills[rank] = round(train_data[(ranks == rank ).values].Age.mean())
age_na_fills | Titanic - Machine Learning from Disaster |
5,636,558 | nrows=184903891-1
nchunk=25000000
val_size=2500000
frm=nrows-85000000
if debug:
frm=0
nchunk=100000
val_size=10000
to=frm+nchunk
sub=DO(frm,to,FILENO )<set_options> | def fill_age_na(data, age_na_fills, ranks):
data['Age'] = data.apply(lambda row: age_na_fills.get(ranks[row.name], 29)if np.isnan(row['Age'])else row['Age'], axis=1 ) | Titanic - Machine Learning from Disaster |
5,636,558 | %matplotlib inline
pd.pandas.set_option('display.max_columns',None)
<import_modules> | class AgeFillNa(BaseEstimator, TransformerMixin):
def __init__(self, age_na_fills=None):
self.age_na_fills = age_na_fills
def fit(self, X, y=None):
return self
def transform(self, X):
output = X.copy()
ranks = X['Name'].str.extract(r'\b(\w+)\.')
if self.age_na_fills is not None:
fill_age_na(output, self.age_na_fills, ... | Titanic - Machine Learning from Disaster |
5,636,558 | from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.svm import SVR
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import RobustScaler
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics imp... | prepare_pipeline = Pipeline([
('age_fill_na', AgeFillNa(age_na_fills)) ,
('selector', DataFrameSelector(columns_to_drop)) ,
('label_enc', MultiColumnLabelEncoder(columns=columns_to_encode)) ,
('imputer', SimpleImputer(strategy="mean")) ,
('std_scaler', StandardScaler()),
] ) | Titanic - Machine Learning from Disaster |
5,636,558 | elasticnet_alphas = [5e-5, 1e-4, 5e-4, 1e-3]
elasticnet_l1ratios = [0.8, 0.85, 0.9, 0.95, 1]
lasso_alphas = [5e-5, 1e-4, 5e-4, 1e-3]
ridge_alphas = [13.5, 14, 14.5, 15, 15.5]
MODELS = {
"elasticnet" : make_pipeline(RobustScaler() , ElasticNetCV(max_iter=1e7, alphas=elasticnet_alphas, l1_ratio=elasticnet_l1ratios)) ,
"l... | X = prepare_pipeline.fit_transform(train_data.drop(columns=['Survived'])) | Titanic - Machine Learning from Disaster |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.