kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
4,851,629
questions_to_tag = questions[['question_id','tags']].set_index('question_id')[['tags']]['tags'].fillna('-1' ).apply(lambda x: [np.int64(elmt)for elmt in x.split(' ')] ).to_dict() questions_to_parts = questions[['question_id','part']].set_index('question_id')['part'].to_dict() lecture_to_type = lectures[['lecture_id','t...
y_scores_xgb = xgboost.predict_proba(x_test)[:, 1] xgb_fpr, xgb_tpr, xgb_thresholds = sklearn.metrics.roc_curve(y_test, y_scores_xgb) xgb_auc = sklearn.metrics.auc(x=xgb_fpr, y=xgb_tpr )
Titanic - Machine Learning from Disaster
4,851,629
def qscore(answer, difficulty): if answer>0: return(2*answer - 1)*difficulty else: return(2*answer - 1)*(1-difficulty) def list_feature_average(n, vals): if len(vals)>n: return np.mean(vals[-n:]) else: return -1 def make_feature_average(count, vals): if count>0: return vals/count else: return -1 def calculate_t...
xgb_acc = xgboost.score(x_test, y_test )
Titanic - Machine Learning from Disaster
4,851,629
def get_new_theta(is_good_answer, beta, left_asymptote, theta, nb_previous_answers): return theta + learning_rate_theta(nb_previous_answers)*( is_good_answer - probability_of_good_answer(theta, beta, left_asymptote) ) def get_new_beta(is_good_answer, beta, left_asymptote, theta, nb_previous_answers): return beta - le...
print('Area Under Curve: {}, Accuracy: {}'.format(xgb_auc, xgb_acc))
Titanic - Machine Learning from Disaster
4,851,629
def create_cache(cache, user_id, ts, ids): if user_id in ids: with open(f'.. /input/riid-cache-6/content/drive/My Drive/riid/{user_id}', 'rb')as f: id_cache = pickle.load(f)[user_id] cache[user_id] = id_cache else: cache[user_id] = {} cache[user_id]['previous_content_type_id'] = -1 cache[user_id]['previous_part'] = -1 ...
lgboost = lgb.LGBMClassifier()
Titanic - Machine Learning from Disaster
4,851,629
def update_cache(cache, arr, batch_size, question_cache): left_asymptote = 1/4 row_id, timestamp, user_id, content_id, content_type_id, task_container_id, prior_question_elapsed_time, prior_question_had_explanation, _, _, answered_correctly,user_answer = arr if not prior_question_elapsed_time: prior_question_elapsed_ti...
threshold = [0.001, 0.01,0.1,0.5]
Titanic - Machine Learning from Disaster
4,851,629
def create_feature(cache, arr, batch_size, question_cache): features = [] row_id, timestamp, user_id, content_id, content_type_id, task_container_id, prior_question_elapsed_time, prior_question_had_explanation, _, _ = arr if not prior_question_elapsed_time: prior_question_elapsed_time=-1 if not prior_question_had_expla...
number_of_features = list(range(1,13))
Titanic - Machine Learning from Disaster
4,851,629
def update_cache_batch(cache, df_arr, question_cache): batch_array = [] task_init = -1 user_id0 = -1 for arr in df_arr: user_id = arr[2] timestamp = arr[1] task_container_id = arr[5] if user_id not in cache.keys() : cache = create_cache(cache, user_id, timestamp, ids) if(task_container_id == task_init)&(user_id == use...
print("Optimal number of features :", np.argmax(np.array(scores_k)) + 1 )
Titanic - Machine Learning from Disaster
4,851,629
def calculate_features(cache, df_arr, question_cache): X = [] batch_array = [] task_init = -1 user_id0 = -1 for arr in df_arr: user_id = arr[2] timestamp = arr[1] task_container_id = arr[5] if user_id not in cache.keys() : cache = create_cache(cache, user_id, timestamp, ids) if(task_container_id == task_init)&(user_id...
print("Optimal number of features : %d" % selector.n_features_ )
Titanic - Machine Learning from Disaster
4,851,629
env = riiideducation.make_env() iter_test = env.iter_test()<data_type_conversions>
threshold = [0.001, 0.01, 0.05, 0.1 , 0.5]
Titanic - Machine Learning from Disaster
4,851,629
p_test_df = pd.DataFrame() cache = {} for idx,(test_df, _)in enumerate(iter_test): test_df['prior_question_had_explanation'] = test_df['prior_question_had_explanation'].astype(float) test_df = test_df.fillna(-1) submit_df = test_df.loc[test_df['content_type_id'] == False, ['row_id']].copy() if not p_test_df.empty: an...
print("Maximum accuracy score is :", np.max(np.array(scores_sfm)) )
Titanic - Machine Learning from Disaster
4,851,629
!pip --quiet install.. /input/python-datatable/datatable-0.11.0-cp37-cp37m-manylinux2010_x86_64.whl !pip install --quiet -r.. /input/treelite-treelite-runtime-version-093/treelite/requirements.txt --no-index --find-links.. /input/treelite-treelite-runtime-version-093/treelite tqdm.tqdm.pandas() %matplotlib inline env =...
print("Optimal threshold :", threshold[np.argmax(np.array(scores_sfm)) ] )
Titanic - Machine Learning from Disaster
4,851,629
dtypes = { "row_id": "int64", "timestamp": "int64", "user_id": "int32", "content_id": "int16", "content_type_id": "boolean", "task_container_id": "int16", "user_answer": "int8", "answered_correctly": "int8", "prior_question_elapsed_time": "float32", "prior_question_had_explanation": "boolean" } data = pd.read_csv(".. /...
selector = sklearn.feature_selection.SelectKBest(k= 11) selector.fit(features, target) lgb_selected_features = selector.get_support()
Titanic - Machine Learning from Disaster
4,851,629
ql = pd.concat([ques, lectures.rename({"lecture_id": "question_id"}, axis=1)], axis=0 ).reset_index(drop=True) ql.tags = ql.tags.fillna(ql.tag) ql.type_of = ql.type_of.fillna("question") ql["content_type_id"] = ql["type_of"] != 'question' ql = ql.fillna(-1) ql = ql.drop("tag", 1) ql = ql.rename({"question_id": "co...
lgboost = lgb.LGBMClassifier() lgboost.fit(features.loc[:,lgb_selected_features], target )
Titanic - Machine Learning from Disaster
4,851,629
lec_count = ql.loc[ql.content_type_id, 'tags'].transform(lambda x: x[0] ).value_counts() ql['lec_available'] =( ql.loc[~ql.content_type_id, 'tags'].transform( lambda x: sum([lec_count.at[i] if i in lec_count.index else 0 for i in x])) )<feature_engineering>
y_scores_lgb = lgboost.predict_proba(x_test.loc[:,lgb_selected_features])[:, 1] lgb_fpr, lgb_tpr, lgb_thresholds = sklearn.metrics.roc_curve(y_test, y_scores_lgb) lgb_auc = sklearn.metrics.auc(x=lgb_fpr, y=lgb_tpr )
Titanic - Machine Learning from Disaster
4,851,629
ql['bundle_q_count'] = ql.groupby("bundle_id")['content_id'].transform('count') ql.loc[ql.content_type_id, 'bundle_q_count'] = -1<categorify>
lgb_acc = lgboost.score(x_test.loc[:,lgb_selected_features], y_test )
Titanic - Machine Learning from Disaster
4,851,629
te = TransactionEncoder() temp = ql[~ql.content_type_id] temp = temp.merge( data[~data.content_type_id].groupby("content_id")['answered_correctly'].agg(['count', 'mean']), on='content_id', how='left') temp['mean'] = temp['mean'].fillna(0.5) temp['count'] = temp['count'].fillna(0) temp = np.hstack([ te.fit_transform...
print('Area Under Curve: {}, Accuracy: {}'.format(lgb_auc, lgb_acc))
Titanic - Machine Learning from Disaster
4,851,629
temp = ql.tags.progress_apply(pd.Series) ql['tagF'] = temp[0] ql['tagS'] = temp[1] ql['tagT'] = temp[2] ql['tagL'] = ql.tags.apply(lambda x: x[-1]) ql[['tagF', 'tagS', 'tagL', 'tagT']] =(ql[['tagF', 'tagS', 'tagL', 'tagT']] + 1 ).fillna(0) ql.sample(5 )<merge>
v = ens.VotingClassifier(estimators=[ ('lr', lr),('NB', nb),('KNN', knn),('SVM', svm),('DT', dt), ('RF', rf),('BG', bg),('AdaBoost', ada),('GBM', gb), ('XGBM', xgboost),('LightGBM', lgboost)], voting='soft', weights= [1,1,1, 1.25, 1.25, 1.25, 1.25, 1.25, 1.75, 1.5, 1.5] )
Titanic - Machine Learning from Disaster
4,851,629
data = data.drop(['part', 'bundle_id'], 1 ).merge(ql, on=['content_id', 'content_type_id'], how='left') data.shape<sort_values>
selector = sklearn.feature_selection.SelectKBest(k= 11) selector.fit(features, target) voting_selected_features = selector.get_support()
Titanic - Machine Learning from Disaster
4,851,629
data = data.sort_values(by=['user_id', 'timestamp']) data['response_time'] =( data.groupby("user_id")['timestamp'] .transform(lambda x: x.diff().replace(0, np.nan) .fillna(method='ffill' ).fillna(0)) )<data_type_conversions>
v.fit(features.loc[:, voting_selected_features], target )
Titanic - Machine Learning from Disaster
4,851,629
data['res_time_avg'] =( data.timestamp - (data.timestamp *(data.task_container_id - 1)/ data.task_container_id) ) data['res_time_avg'] = data['res_time_avg'].replace(np.inf, np.nan) print("Corelation to response_time: ", data.corr() ['response_time'].loc[['res_time_avg']], sep='') print(" Correlation to ans_correc...
y_scores_v = v.predict_proba(features.loc[:, voting_selected_features])[:, 1] v_fpr, v_tpr, v_thresholds = sklearn.metrics.roc_curve(target, y_scores_v) v_auc = sklearn.metrics.auc(x=v_fpr, y=v_tpr )
Titanic - Machine Learning from Disaster
4,851,629
data = data.sort_values(['user_id', 'timestamp']) data = data.merge( (data[~data.content_type_id].groupby(['user_id', 'task_container_id']) [['prior_question_elapsed_time', 'prior_question_had_explanation']] .mean().groupby("user_id" ).shift(-1 ).reset_index() .rename({"prior_question_elapsed_time": 'pqet_shifted',...
v_acc = v.score(x_test.loc[:,voting_selected_features], y_test )
Titanic - Machine Learning from Disaster
4,851,629
data = data.sort_values(by=['user_id', 'timestamp']) cut_off =(1000 * 60 * 60) cut_off = cut_off * 1 data['sessions'] =( data.groupby("user_id")['timestamp'].diff() > cut_off ).groupby(data['user_id'] ).cumsum()<categorify>
print('Area Under Curve: {}, Accuracy: {}'.format(v_auc, v_acc))
Titanic - Machine Learning from Disaster
4,851,629
def post_process(fn0, fn1): fn_processed = fn0.drop(['prior_group_answers_correct', 'prior_group_responses'], 1) fn_processed['answered_correctly'] = eval(fn1['prior_group_answers_correct'].iloc[0]) fn_processed['user_answer'] = eval(fn1['prior_group_responses'].iloc[0]) return fn_processed<load_pretrained>
pd.DataFrame([(lr_auc, lr_acc),(nb_auc, nb_acc),(knn_auc, knn_acc),(dt_auc, dt_acc), (rf_auc, rf_acc),(svm_auc, svm_acc),(bg_auc, bg_acc),(ada_auc, ada_acc), (v_auc, v_acc),(gb_auc, gb_acc),(xgb_auc, xgb_acc),(lgb_auc, lgb_acc)], columns=['AUC', 'Accuracy'], index=['Logistic Regression', 'Naive Bayes', 'KNN', 'Decisi...
Titanic - Machine Learning from Disaster
4,851,629
with open(".. /input/riiid-final-model-inputs/sample-batches.pkl", 'rb')as f: batches = pickle.load(f) print("Batch sizes for each test sample:", list(map(lambda x: x[0].shape[0], batches)) )<compute_train_metric>
y_pred_v = pd.DataFrame(v.predict(unlabelled.loc[:, voting_selected_features]), columns=[ 'Survived'], dtype='int64' )
Titanic - Machine Learning from Disaster
4,851,629
temp = data.loc[~data.content_type_id, "answered_correctly"] for value in [0, 1, 0.5, temp.mean() ]: print("At {:.2f} the score is: {:.3f}".format(value, roc_auc_score(temp, np.full_like(temp, 0))))<compute_test_metric>
v_model = pd.concat([passengerID, y_pred_v], axis=1 )
Titanic - Machine Learning from Disaster
4,851,629
<categorify><EOS>
v_model.to_csv('voting.csv', index= False )
Titanic - Machine Learning from Disaster
1,415,708
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<feature_engineering>
import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.model_selection import GridSearchCV
Titanic - Machine Learning from Disaster
1,415,708
ba = bitarray(15000, endian='little') ba.setall(False) repeat_c = 0 temp = data[~data.content_type_id].loc[data.user_id == np.random.choice(data.user_id.unique()), ['content_id']] for _, c in temp['content_id'].iteritems() : if ba[c]: print(f"{c:<5} was already viewed by the user!") repeat_c += 1 else: ba[c] = 1 if ...
warnings.filterwarnings(action='ignore', category=FutureWarning)
Titanic - Machine Learning from Disaster
1,415,708
@nb.njit def shifted_expanding_mean(arr, keep_last=False): 'keep_last is set to true when we apply this func to pqet_mean.SPECIAL USE CASE!' temp = expanding_mean(arr) if not keep_last: return np.concatenate(( np.array([np.nan]), temp[:-1])) else: return np.concatenate(( np.array([np.nan]), temp)) shifted_expanding_me...
train_data = pd.read_csv(".. /input/train.csv") test_data = pd.read_csv(".. /input/test.csv" )
Titanic - Machine Learning from Disaster
1,415,708
@nb.njit def rt_func(arr, pred=False): temp = np.concatenate(( np.array([np.nan]), arr[1:] - arr[:-1])) temp = np.where(temp == 0, np.nan, temp) mask = np.isnan(temp) idx = np.arange(len(mask)) idx = np.where(mask, 0, idx) rmax, i = idx[0], 0 for i, val in enumerate(idx): if val > rmax: rmax = val idx[i] = rmax temp...
svc_clf = Pipeline([('vect', TfidfVectorizer()), ('transformer', TfidfTransformer()), ('classify', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, random_state=0, max_iter=5, tol=None)) ] )
Titanic - Machine Learning from Disaster
1,415,708
%time data.groupby("user_id")['timestamp'].transform(lambda x: rt_func(x.values)) %time data.groupby("user_id")['timestamp'].transform(lambda x: x.diff().replace(0, np.nan ).fillna(method='ffill' ).fillna(0)) ( data.groupby("user_id")['timestamp'].transform(lambda x: rt_func(x.values)) == data['response_time'] ).all(...
svc_clf.fit(train_data['Name'][:700], train_data['Survived'][:700] )
Titanic - Machine Learning from Disaster
1,415,708
@nb.njit def modify_ac(arr, c_mean): temp = np.where(arr == 0, -1, 1)* c_mean return np.where(temp < 0, temp, 1 - temp )<feature_engineering>
predictions = svc_clf.predict(train_data['Name'][700:] )
Titanic - Machine Learning from Disaster
1,415,708
%%time data['ac_modified'] = modify_ac( data['answered_correctly'].values, data.groupby(["content_id", 'content_type_id'])['answered_correctly'].transform('mean' ).values) data.loc[data.content_type_id, 'ac_modified'] = 0<categorify>
survived_or_not = train_data['Survived'][700:]
Titanic - Machine Learning from Disaster
1,415,708
@nb.njit def fillnshift(arr): mask = np.isnan(arr) idx = np.arange(len(mask)) idx = np.where(mask, 0, idx) rmax, i = idx[0], 0 for i, val in enumerate(idx): if val > rmax: rmax = val idx[i] = rmax arr[mask] = arr[idx[mask]] return np.concatenate(( np.array([np.nan]), arr[:-1]))<normalization>
np.mean(predictions == survived_or_not )
Titanic - Machine Learning from Disaster
1,415,708
@nb.njit def moving_average(arr, n=10, shift=True): mask = np.isnan(arr) ret = np.cumsum(np.where(mask, 0, arr)) ret[n:] = ret[n:] - ret[:-n] counts = np.cumsum(~mask) counts[n:] = counts[n:] - counts[:-n] ret[~mask] /= counts[~mask] ret[mask] = np.nan if shift: ret = np.concatenate(( np.array([np.nan]), ret[:-1])) r...
parameters = {'vect__ngram_range' : [(1, 1),(2, 2),(3 , 3)], 'transformer__use_idf' :(True, False), 'classify__alpha' :(1e-2, 1e-3), }
Titanic - Machine Learning from Disaster
1,415,708
data['up_mean'] = data[~data.content_type_id].groupby(['user_id', 'part'])['ac_modified'].transform( lambda x: shifted_expanding_mean(x.values)) data['up_count'] =(data[~data.content_type_id].groupby(['user_id', 'part'] ).cumcount() / data[~data.content_type_id].groupby("user_id" ).cumcount()) data['up_count'] = data...
gs_clf = GridSearchCV(svc_clf, parameters, n_jobs=-1 )
Titanic - Machine Learning from Disaster
1,415,708
temp = np.random.randint(0, 2, size=int(1e5)).astype('float') temp[0] = np.nan temp = pd.Series(temp) np.testing.assert_allclose( temp.expanding().mean() , shifted_expanding_mean(temp.values[1:], keep_last=True) )<feature_engineering>
gs_clf.fit(train_data['Name'], train_data['Survived'] )
Titanic - Machine Learning from Disaster
1,415,708
data['content_c'] = data.groupby(["content_id", 'content_type_id'])['row_id'].transform("count") data['seen_ratio'] =(data.loc[~data.content_type_id, ['user_id', 'prior_question_had_explanation']] .fillna(False ).astype(float ).groupby("user_id") .transform(lambda x: expanding_mean(x.values))) data['pqet_mean'] =( ...
cv_result = pd.DataFrame(gs_clf.cv_results_ )
Titanic - Machine Learning from Disaster
1,415,708
data['lec_recent'] =( data.loc[data.content_type_id, 'content_type_id'] .reindex(data.index ).groupby(data['user_id']) .fillna(method='ffill', limit=10) .fillna(False ).astype(bool) ) data['uf_bundle'] = data.groupby("user_id")['bundle_id'].transform('first') data['pqetmr_10'] =(data[~data.content_type_id].groupby(...
gs_clf.best_params_
Titanic - Machine Learning from Disaster
1,415,708
data['seen_exp_when_wrong'] =(data['pqhe_shifted'].fillna(False)&(data['answered_correctly'] == 0)).astype(int) data['seen_exp_when_wrong'] =(data[~data.content_type_id].groupby('user_id')['seen_exp_when_wrong'] .transform(lambda x: shifted_expanding_sum(x.values))) data['seen_exp_when_right'] =(data['pqhe_shifted']...
best_model_svc = Pipeline([('vect', TfidfVectorizer()), ('transformer', TfidfTransformer(use_idf=False)) , ('classify', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, random_state=0, max_iter=5, tol=None)) ] )
Titanic - Machine Learning from Disaster
1,415,708
warnings.filterwarnings("ignore", category=UserWarning) train_cols = [ 'repeat_c', 'tagF', 'tagS', 'tagL', 'tagT', 'response_time', 'prior_question_elapsed_time', 'up_mean', 'up_count', 'uq_per_hr', 'uwrong_sum', 'lec_recent', 'pqet_mean', 'seen_ratio', 'tmed', 'up_recency', 'ts_recency_10', 'ts_recency_5', 'timestamp...
best_model_svc.fit(train_data['Name'], train_data['Survived'] )
Titanic - Machine Learning from Disaster
1,415,708
del data, temp, train, val data = temp = train = val = None gc.collect()<load_pretrained>
predictions = best_model_svc.predict(test_data['Name'] )
Titanic - Machine Learning from Disaster
1,415,708
start_time = time.time() LEC_RECENT_ROLL = 10 ROLL_WINDOW = 10 ROLL_WINDOW_PQET = 10 SESSION_DURATION = 15 * 60 * 1000 CHUNKS = 3 SAVE_LOC = f".. /input/riiid-final-model-inputs/model_train_c1.feather" MODEL_LOC = f".. /input/riiid-final-model-inputs/trained_model.txt" if not os.path.exists(SAVE_LOC): data = pd.read_fe...
test_data['Predictions'] = predictions
Titanic - Machine Learning from Disaster
1,415,708
def return_random_slice(batch_size, nrows): front = np.random.choice(nrows - batch_size) rear = front + batch_size return front, rear<define_variables>
kaggle_data = test_data[['PassengerId', 'Predictions']].copy() kaggle_data.rename(columns={'Predictions' : 'Survived'}, inplace=True) kaggle_data.sort_values(by=['PassengerId'] ).to_csv('kaggle_out_svc_names.csv', index=False )
Titanic - Machine Learning from Disaster
3,621,652
def return_chunk_indices(start, end, nrows, chunks=3): 'Maps the indices to chunk indices for data loading' chunk_size =(nrows//chunks) indices = [] start_chunk = start // chunk_size end_chunk =(end-1)// chunk_size start_chunk_start = start - chunk_size * start_chunk end_chunk_end = end - chunk_size * end_chunk start_...
dataset = pd.read_csv('.. /input/train.csv' )
Titanic - Machine Learning from Disaster
3,621,652
%%time ALL_FEATURES = [ 'repeat_c', 'tagF', 'tagS', 'tagL', 'tagT', 'response_time', 'prior_question_elapsed_time', 'up_mean', 'up_count', 'uq_per_hr', 'uwrong_sum', 'lec_recent', 'pqet_mean', 'seen_ratio', 'tmed', 'up_recency', 'ts_recency_10', 'ts_recency_5', 'timestamp', 'task_container_id', 'content_c', 'che_sum', ...
features= [ 'Pclass','Sex','Age','SibSp','Parch','Fare','Embarked'] x = dataset[features] y = dataset['Survived']
Titanic - Machine Learning from Disaster
3,621,652
class ensemble(object): def __init__(self, models, weights=None, treelite=True): self.n_models = len(models) self.models = models self.weights = [1 / self.n_models] * self.n_models if not weights else weights self.cat_cols = ['tagF', 'tagS', 'tagL', 'tagT'] self.treelite = treelite self.feats = ['repeat_c', 'tagF', 't...
x.isnull().sum()
Titanic - Machine Learning from Disaster
3,621,652
%%time start_time = time.time() if not os.path.exists(".. /input/col-sampled-train-dataset/lgb_pred_1.npy"): models = [models[3], models[6]] BATCH_SIZE = int(3.0e7) CHUNKS = list(range(0, N_ROWS, BATCH_SIZE)) print(f"Time Elapsed: {time.time() - start_time:10.2f} s | Predictions will be chunked for", len(CHUNKS), "Chu...
x['Age'] = x['Age'].fillna(x['Age'].median()) x['Embarked']= x['Embarked'].fillna(x['Embarked'].value_counts().index[0] )
Titanic - Machine Learning from Disaster
3,621,652
%%time start_time = time.time() if not os.path.exists(".. /input/col-sampled-train-dataset/lgb2_pred_1.npy"): models = [models[1], models[4]] BATCH_SIZE = int(3.0e7) CHUNKS = list(range(0, N_ROWS, BATCH_SIZE)) print(f"Time Elapsed: {time.time() - start_time:10.2f} s | Predictions will be chunked for", len(CHUNKS), "Ch...
x.isnull().sum()
Titanic - Machine Learning from Disaster
3,621,652
%%time data = pd.read_feather( ".. /input/riiid-train-data-multiple-formats/riiid_train.feather", columns=['content_id', 'content_type_id']) data = data.loc[~data['content_type_id']].iloc[:N_ROWS] data = data.merge( ques[['question_id', 'part']].set_index("question_id"), left_on=['content_id'], right_index=True, how...
LE = LabelEncoder() x['Sex'] = LE.fit_transform(x['Sex']) x['Embarked'] = LE.fit_transform(x['Embarked'] )
Titanic - Machine Learning from Disaster
3,621,652
def df_to_dt_format(df): for i in df.columns: org = str(df[i].dtype) converted = org.lstrip("u") if org != converted: converted = converted[:3] + str(int(converted.lstrip("int")) * 2) df[i] = df[i].astype(converted )<create_dataframe>
y.isnull().sum()
Titanic - Machine Learning from Disaster
3,621,652
df_to_dt_format(data) data = dt.Frame(data )<define_variables>
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.1,random_state =0 )
Titanic - Machine Learning from Disaster
3,621,652
FTRL_COLS = [ 'user_id', 'task_container_id', 'content_c', 'ummr_10_50', 'h_mean_50', 'c_mean_50', 'c_mean_25', 'c_mean_75', 'content_id', 'part', 'lgb_pred', 'lgb_75', 'lgb_50', 'lgb_25' ] INTERACTIONS = None<train_model>
classifier = XGBClassifier(colsample_bylevel= 0.9, colsample_bytree = 0.8, gamma=0.99, max_depth= 5, min_child_weight= 1, n_estimators= 10, nthread= 4, random_state= 2, silent= True) classifier.fit(x_train,y_train) classifier.score(x_test,y_test )
Titanic - Machine Learning from Disaster
3,621,652
%%time ftrl = Ftrl( nepochs=1, interactions=INTERACTIONS, alpha=0.005, double_precision=True, ) ftrl.fit(data[:int(9.5e7), FTRL_COLS], data[:int(9.5e7), ['answered_correctly']] )<compute_train_metric>
test_data = pd.read_csv('.. /input/test.csv') test_x = test_data[features]
Titanic - Machine Learning from Disaster
3,621,652
%%time preds = ftrl.predict(data[int(9.5e7):, FTRL_COLS] ).to_pandas() actual = data[int(9.5e7):, 'answered_correctly'].to_numpy() print("Baseline Score to beat: {:.4f}".format(roc_auc_score( actual, data[int(9.5e7):, 'lgb_pred'].to_pandas() ))) roc_auc_score(actual, preds )<choose_model_class>
test_x.isnull().sum()
Titanic - Machine Learning from Disaster
3,621,652
model = ensemble(models, treelite=False) model, type(model.models[0] )<predict_on_test>
test_x['Age'] = test_x['Age'].fillna(test_x['Age'].median()) test_x['Fare'] = test_x['Fare'].fillna(test_x['Fare'].median() )
Titanic - Machine Learning from Disaster
3,621,652
if not os.path.exists(".. /input/treelite-converted-ensemble-8-models-25m/lgb_pred_final.npy"): temp = pd.read_feather(LOC3 ).iloc[-(N_ROWS - int(9.5e7)) :][model.feature_name() ] lgb_pred = model.predict(temp) del temp gc.collect() else: lgb_pred = np.load(".. /input/treelite-converted-ensemble-8-models-25m/lgb_pred_...
test_x.isnull().sum()
Titanic - Machine Learning from Disaster
3,621,652
data[int(9.5e7):, 'lgb_pred'] = lgb_pred data[int(9.5e7):, 'lgb_75'] = data[int(9.5e7):, dt.f.lgb_pred > 0.75] data[int(9.5e7):, 'lgb_50'] = data[int(9.5e7):, dt.f.lgb_pred > 0.50] data[int(9.5e7):, 'lgb_25'] = data[int(9.5e7):, dt.f.lgb_pred > 0.25] preds = ftrl.predict(data[int(9.5e7):, FTRL_COLS]) print("Baseline S...
test_x['Sex'] = LE.fit_transform(test_x['Sex']) test_x['Embarked'] = LE.fit_transform(test_x['Embarked'] )
Titanic - Machine Learning from Disaster
3,621,652
ol_ftrl = deepcopy(ftrl) ol_ftrl.alpha = 0.005<predict_on_test>
prediction = classifier.predict(test_x )
Titanic - Machine Learning from Disaster
3,621,652
%%time ol_preds = [] preds = [] BATCH_SIZE = 1000 for front in range(int(9.5e7), N_ROWS, BATCH_SIZE): pred = ol_ftrl.predict(data[front:front+BATCH_SIZE, FTRL_COLS] ).to_list() [0] ol_preds.append(pred) pred = ftrl.predict(data[front:front+BATCH_SIZE, FTRL_COLS] ).to_list() [0] preds.append(pred) ol_ftrl.fit(data[fro...
output = pd.DataFrame({'PassengerId': test_data.PassengerId,'Survived': prediction}) output.to_csv('submission.csv', index=False) output.head()
Titanic - Machine Learning from Disaster
2,971,410
actual = data[int(9.5e7):, 'answered_correctly'].to_numpy() print("Baseline Score to beat: {:.4f}".format(roc_auc_score( actual, data[int(9.5e7):, 'lgb_pred'].to_pandas() ))) print(" Model Score Comparison: Online: {:.4f} | Offline: {:.4f}".format( roc_auc_score(actual, np.concatenate(ol_preds)) , roc_auc_score(act...
print('reading input files.. ') data = pd.read_csv('.. /input/train.csv') sampl = pd.read_csv('.. /input/gender_submission.csv' )
Titanic - Machine Learning from Disaster
2,971,410
%%time TREELITE = False if TREELITE: models = [] for model in sorted(glob.glob(".. /input/treelite-converted-ensemble-8-models-25m/tl_*.so")) : models.append(treelite_runtime.Predictor(model, verbose=False, nthread=1)) else: models = [] for file in sorted(glob.glob(".. /input/riiid-final-model-inputs/trained_model_*.tx...
test = pd.read_csv('.. /input/test.csv' )
Titanic - Machine Learning from Disaster
2,971,410
load_from_file = True cat_cols = ['tagF', 'tagS', 'tagT', 'tagL']<load_from_disk>
df = data.append(test, sort = False )
Titanic - Machine Learning from Disaster
2,971,410
start_time = time.time() if not load_from_file: pq_shifted = pd.read_feather( ".. /input/riiid-train-data-multiple-formats/riiid_train.feather", columns=['user_id', 'task_container_id', 'content_type_id', 'prior_question_elapsed_time', 'prior_question_had_explanation']) q_mask = pq_shifted['content_type_id'] == 0 pq_...
totalt = df.isnull().sum().sort_values(ascending=False) percent =(df.isnull().sum() /df.isnull().count() ).sort_values(ascending=False) missing_data = pd.concat([totalt, percent], axis=1, keys=['Total', 'Percent']) missing_data.head(6 )
Titanic - Machine Learning from Disaster
2,971,410
start_time = time.time() LEC_RECENT_ROLL = 10 SESSION_DURATION = 15 * 60 * 1000 if not load_from_file: user_df =(pd.read_feather( ".. /input/riiid-train-data-multiple-formats/riiid_train.feather", columns=['user_id', 'answered_correctly', 'timestamp', 'content_id', 'prior_question_elapsed_time', 'prior_question_had_ex...
ticketNum = pd.DataFrame(df.Ticket.value_counts()) ticketNum.rename(columns = {'Ticket' : 'TicketNum'}, inplace = True) ticketNum['TicketId'] = pd.Categorical(ticketNum.index ).codes ticketNum.loc[ticketNum.TicketNum < 3, 'TicketId'] = -1 df = pd.merge(left = df, right = ticketNum, left_on = 'Ticket', right_index = T...
Titanic - Machine Learning from Disaster
2,971,410
max_q = ques.question_id.max() + 1 def to_ba(indices, max_q=max_q): 'Function to convert indices to bitarray' ba = np.zeros(max_q, dtype=bool) ba[indices] = 1 return bitarray(list(ba)) def parallelize(data, func, num_of_processes=8): data_split = np.array_split(data, num_of_processes) pool = Pool(num_of_processes) d...
df['FamilyName'] = df.Name.apply(lambda x : str.split(x, ',')[0] )
Titanic - Machine Learning from Disaster
2,971,410
start_time = time.time() ROLL_WINDOW = 10 UROLL_NULL_FILL = -2 if not load_from_file: u_roll =(pd.read_feather( ".. /input/riiid-train-data-multiple-formats/riiid_train.feather", columns=['user_id', 'answered_correctly', 'content_id'])) u_roll = u_roll[u_roll.answered_correctly != -1] u_roll = u_roll.groupby("user_id"...
df['FamilySurv'] = 0.5 for _, grup in df.groupby(['FamilyName','Fare']): if len(grup)!= 1: for index, row in grup.iterrows() : smax = grup.drop(index ).Survived.max() smin = grup.drop(index ).Survived.min() pid = row.PassengerId if smax == 1: df.loc[df.PassengerId == pid, 'FamilySurv'] = 1.0 elif smin == 0: df.loc[df.P...
Titanic - Machine Learning from Disaster
2,971,410
start_time = time.time() ROLL_WINDOW_PQET = 10 PQET_ROLL_NULL_FILL = -1 if not load_from_file: pqet_roll =(pd.read_feather( ".. /input/riiid-train-data-multiple-formats/riiid_train.feather", columns=['user_id', 'prior_question_elapsed_time', 'answered_correctly'])) pqet_roll = pqet_roll[pqet_roll.answered_correctly !=...
def CabinNum(data): data.Cabin = data.Cabin.fillna('0') regex = re.compile('\s*(\w+)\s*') data['CabinNum'] = data.Cabin.apply(lambda x : len(regex.findall(x))) CabinNum(df )
Titanic - Machine Learning from Disaster
2,971,410
start_time = time.time() TS_RECENCY_PERIOD = 10 TS_ROLL_NULL_FILL = np.nan if not load_from_file: ts_roll =(pd.read_feather( ".. /input/riiid-train-data-multiple-formats/riiid_train.feather", columns=['user_id', 'timestamp'])) ts_roll = ts_roll.groupby("user_id" ).tail(TS_RECENCY_PERIOD) ts_roll = ts_roll.groupby("us...
df.CabinNum.value_counts()
Titanic - Machine Learning from Disaster
2,971,410
%%time user_df.to_csv("user-df.csv") content_df.to_csv("content-df.csv") u_roll.to_csv("u_roll.csv") repeat_c.to_pickle("repeat-c.pkl") pqet_roll.to_csv("pqet_roll.csv") ts_roll.to_csv("ts_roll.csv") if os.path.exists(".. /input/riiid-final-model-inputs/pq_shifted.feather"): ! cp.. /input/riiid-final-model-inputs...
df.loc[df['Fare'].isnull() ]
Titanic - Machine Learning from Disaster
2,971,410
def insert_lecture(batches): 'A simple function to randomly insert a lecture in between, for debugging purposes!' temp = deepcopy(batches) i = np.random.choice(len(temp)) j = np.random.choice(len(temp[i][0])) print(f"Lecture inserted at {i+1} batch at {j} index!") temp[i][0].iloc[j, 4] = 1 temp[i][0].iloc[j, 3] = np....
df.loc[(df['Age'] >= 60)&(df['Pclass'] ==3)&(df['Sex'] == 'male')&(df['Embarked'] =='S')]
Titanic - Machine Learning from Disaster
2,971,410
SUBMIT = False if not SUBMIT: print("Validation Mode.") iter_test = iter(insert_lecture(batches)) op = [] else: print("Prediction Mode.") iter_test = env.iter_test()<train_model>
df.loc[df['Fare'].isnull() , 'Fare'] = 7
Titanic - Machine Learning from Disaster
2,971,410
%%time i, prev_test = 0, tuple() for i, batch in enumerate(iter_test): if len(prev_test): processed_batch = post_process(prev_test[0], batch[0]) ftrl.fit(dt.Frame(prev_test[1])[:, FTRL_COLS], dt.Frame(processed_batch.loc[q_mask, 'answered_correctly'])) for _, ts, user, content, ans, pqhe, pqet in( processed_batch[[ '...
def FareFunc(data): data['FareCat'] = 0 data.loc[data['Fare'] < 8, 'FareCat'] = 0 data.loc[(data['Fare'] >= 8)&(data['Fare'] < 16),'FareCat' ] = 1 data.loc[(data['Fare'] >= 16)&(data['Fare'] < 30),'FareCat' ] = 2 data.loc[(data['Fare'] >= 30)&(data['Fare'] < 45),'FareCat' ] = 3 data.loc[(data['Fare'] >= 45)&(data['Fare...
Titanic - Machine Learning from Disaster
2,971,410
import gc import os import time import json import psutil import numpy as np import pandas as pd import riiideducation import torch import torch.nn as nn import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score, accuracy_score<set_options>
def FamlSize(data): data['FamlSize'] = 0 data['FamlSize'] = data['SibSp'] + data['Parch'] + 1 FamlSize(df )
Titanic - Machine Learning from Disaster
2,971,410
device='cuda' if torch.cuda.is_available() else 'cpu' print(device )<init_hyperparams>
def LablFunc(data): lsr = {'Title','Cabin'} for i in lsr: le.fit(data[i].astype(str)) data[i] = le.transform(data[i].astype(str)) LablFunc(df )
Titanic - Machine Learning from Disaster
2,971,410
MAX_SEQ=100 MAX_LAG_TIME=2160 MAX_PREV_ELAPSE_TIME=600 n_questions=13523 n_parts=7 n_responses=3 n_lagtimes=2161 n_prev_elapsed=601 d_model=160 nhead=8 dim_feedforward=250 max_lr=0.0025<define_variables>
features = ['Pclass','SibSp','Parch','TicketId','Fare','CabinNum','Title'] def AgeFunc(df): Etr = ETRg(n_estimators = 200, random_state = 2) AgeX_Train = df[features][df.Age.notnull() ] AgeY_Train = df['Age'][df.Age.notnull() ] AgeX_Test = df[features][df.Age.isnull() ] Etr.fit(AgeX_Train,np.ravel(AgeY_Train)) AgePred...
Titanic - Machine Learning from Disaster
2,971,410
class TestDataset(torch.utils.data.Dataset): def __init__(self, test_df, max_seq=100): self.test_df=test_df self.max_seq=max_seq def __len__(self): return len(self.test_df) def __getitem__(self, idx): row=self.test_df.iloc[idx] content_id=row.content_id part=row.part timestamp=row.timestamp prior_question_elapsed_time...
def AgeCat(data): data['AgeCat'] = 0 data.loc[(data['Age'] <= 5), 'AgeCat'] = 0 data.loc[(data['Age'] <= 12)&(data['Age'] > 5), 'AgeCat'] = 1 data.loc[(data['Age'] <= 18)&(data['Age'] > 12), 'AgeCat'] = 2 data.loc[(data['Age'] <= 22)&(data['Age'] > 18), 'AgeCat'] = 3 data.loc[(data['Age'] <= 32)&(data['Age'] > 22), 'Ag...
Titanic - Machine Learning from Disaster
2,971,410
%%time class FFN(nn.Module): def __init__(self, d_model=80, dim_feedforward=512, dropout=0.1): super(FFN, self ).__init__() self.fc1=nn.Linear(d_model, dim_feedforward) self.relu=nn.ReLU() self.fc2=nn.Linear(dim_feedforward, d_model) self.dropout=nn.Dropout(dropout) def forward(self, x): x=self.fc1(x) x=self.relu(x...
df.loc[df['Embarked'].isnull() ]
Titanic - Machine Learning from Disaster
2,971,410
model=KTModel(n_questions, n_parts, n_responses, n_lagtimes=n_lagtimes, n_prev_elapsed=n_prev_elapsed, MAX_SEQ=MAX_SEQ, d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, device=device ).to(device) model.load_state_dict(torch.load('.. /input/saint-v2/sakt_saint(2 ).pth'))<feature_engineering>
def FillEmbk(data): var = 'Embarked' data.loc[(data.Embarked.isnull()),'Embarked']= 'C' FillEmbk(df )
Titanic - Machine Learning from Disaster
2,971,410
def update_group(test_df, prev_test_df): if prev_test_df is None or(psutil.virtual_memory().percent>=90): return prev_answered_correctly=eval(test_df.prior_group_answers_correct.values[0]) prev_test_df['answered_correctly']=prev_answered_correctly prev_test_df=prev_test_df[prev_test_df.content_type_id==0] prev_group=p...
def LablFunc(data): lst = {'Embarked','Sex'} for i in lst: le.fit(data[i].astype(str)) data[i] = le.transform(data[i].astype(str)) LablFunc(df )
Titanic - Machine Learning from Disaster
2,971,410
%%time print('Load Group Data') group=pd.read_pickle('.. /input/saint-group-submission/saint_group.pkl') questions_df=pd.read_csv('.. /input/riiid-test-answer-prediction/questions.csv') questions_df.rename(columns={'question_id': 'content_id'}, inplace=True )<split>
target = data['Survived'].values select_features = ['Pclass', 'Age','AgeCat','SibSp', 'Parch', 'Fare', 'Embarked', 'TicketId', 'CabinNum', 'Title','Cabin', 'FareCat', 'FamlSize','FamilySurv','Sex'] scaler = StandardScaler() dfScaled = scaler.fit_transform(df[select_features]) train = dfScaled[0:891].copy() test = dfSc...
Titanic - Machine Learning from Disaster
2,971,410
env = riiideducation.make_env() iter_test = env.iter_test()<merge>
selector = SelectKBest(f_classif, len(select_features)) selector.fit(train, target) scores = -np.log10(selector.pvalues_) indices = np.argsort(scores)[::-1] print('Features importance:') for i in range(len(scores)) : print('%.2f %s' %(scores[indices[i]], select_features[indices[i]]))
Titanic - Machine Learning from Disaster
2,971,410
%%time prev_test_df=None for(test_df, sample_prediction_df)in iter_test: test_df=test_df[['row_id', 'user_id', 'content_id', 'timestamp', 'content_type_id', 'prior_question_elapsed_time', 'prior_group_answers_correct']].merge( questions_df[['content_id', 'part']],how='left',on='content_id') update_group(test_df, prev...
from sklearn.model_selection import KFold, cross_val_score from sklearn.ensemble import RandomForestClassifier
Titanic - Machine Learning from Disaster
2,971,410
import pandas as pd import numpy as np import gc from sklearn.metrics import roc_auc_score from collections import defaultdict from tqdm.notebook import tqdm import lightgbm as lgb import riiideducation import matplotlib.pyplot as plt import seaborn as sns import psutil import random import os<define_variables>
SrchRFC = RandomForestClassifier(max_depth = 5, min_samples_split = 4, n_estimators = 500, random_state = 20, n_jobs = -1) SrchRFC.fit(train, target )
Titanic - Machine Learning from Disaster
2,971,410
SEED = 123 def seed_everything(seed): random.seed(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) seed_everything(SEED )<data_type_conversions>
prc = SrchRFC.predict(train) accuracy_score(target,prc )
Titanic - Machine Learning from Disaster
2,971,410
def add_features(df, answered_correctly_u_count, answered_correctly_u_sum, elapsed_time_u_sum, explanation_u_sum, timestamp_u, timestamp_u_incorrect, answered_correctly_q_count, answered_correctly_q_sum, elapsed_time_q_sum, explanation_q_sum, answered_correctly_uq, update = True): answered_correctly_u_avg = np.zeros(le...
prdt2 = SrchRFC.predict(test) print('Predicted result: ', prdt2 )
Titanic - Machine Learning from Disaster
2,971,410
<split><EOS>
sampl['Survived'] = pd.DataFrame(prdt2) sampl.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
1,058,030
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<train_model>
%matplotlib inline
Titanic - Machine Learning from Disaster
1,058,030
def train_and_evaluate(train, valid, feature_engineering = False): clfs = list() num=1 TARGET = 'answered_correctly' FEATURES = [ 'prior_question_elapsed_time', 'prior_question_had_explanation', 'part', 'answered_correctly_u_avg', 'elapsed_time_u_avg', 'explanation_u_avg', 'answered_correctly_q_avg', 'elapsed_time_q_av...
train_df = pd.read_csv('.. /input/train.csv') test_df = pd.read_csv('.. /input/test.csv') train_df.head()
Titanic - Machine Learning from Disaster
1,058,030
TARGET, FEATURES, model,clfs = train_and_evaluate(train, valid, feature_engineering = True )<choose_model_class>
train_df.isnull().sum() , print('------'),test_df.isnull().sum()
Titanic - Machine Learning from Disaster
1,058,030
class FFN(nn.Module): def __init__(self, state_size=200): super(FFN, self ).__init__() self.state_size = state_size self.lr1 = nn.Linear(state_size, state_size) self.relu = nn.ReLU() self.lr2 = nn.Linear(state_size, state_size) self.dropout = nn.Dropout(0.2) def forward(self, x): x = self.lr1(x) x = self.relu(x) x...
sex_map = {'male' : 0, 'female' : 1} train_df['Sex'] = train_df['Sex'].replace(sex_map) fare_map = {'Unknown' : 0,'1-20' : 1,'21-41' : 2,'42-60' :3 ,'61-81' : 4,'82-100' : 5,'101+' : 6} train_df['FareGroup'] = train_df['FareGroup'].replace(fare_map )
Titanic - Machine Learning from Disaster
1,058,030
skills = joblib.load("/kaggle/input/riiid-sakt-model-dataset-public/skills.pkl.zip") n_skill = len(skills) group = joblib.load("/kaggle/input/riiid-sakt-model-dataset-public/group.pkl.zip" )<load_pretrained>
def age_imputer(dataf_to_impute,dataf_to_ref): title_age = dataf_to_ref[['Title','Age']][dataf_to_ref['Age'].notnull() ].groupby('Title' ).mean() for Id in dataf_to_impute['PassengerId'][dataf_to_impute['Age'].isnull() ]: for tle in dataf_to_impute['Title'][dataf_to_impute['PassengerId'] == Id]: dataf_to_impute['Age'][...
Titanic - Machine Learning from Disaster
1,058,030
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") SAKT_model = SAKTModel(n_skill, embed_dim=128) try: SAKT_model.load_state_dict(torch.load("/kaggle/input/riiid-sakt-model-dataset-public/sakt_model.pt")) except: SAKT_model.load_state_dict(torch.load("/kaggle/input/riiid-sakt-model-dataset-public/s...
train_df['Age'].isna().sum()
Titanic - Machine Learning from Disaster
1,058,030
def inference(TARGET, FEATURES, model, questions_df, prior_question_elapsed_time_mean, features_dicts): answered_correctly_u_count = features_dicts['answered_correctly_u_count'] answered_correctly_u_sum = features_dicts['answered_correctly_u_sum'] elapsed_time_u_sum = features_dicts['elapsed_time_u_sum'] explanation_u_...
age_map = {'Unknown' : 0, 'Baby' : 1, 'Child' : 2, 'Student' : 3, 'Teenager' : 4, 'Young Adult' : 5, 'Adult' : 6, 'Senior' : 7} train_df['AgeGroup'] = train_df['AgeGroup'].replace(age_map )
Titanic - Machine Learning from Disaster
1,058,030
import pandas as pd import numpy as np import gc import pickle import psutil import joblib from sklearn.metrics import roc_auc_score from collections import defaultdict from tqdm.notebook import tqdm import lightgbm as lgb import riiideducation import matplotlib.pyplot as plt import seaborn as sns import random import ...
Y = train_df['Survived'].values.ravel() X_new = train_df[['Pclass','FareGroup','AgeGroup','SibSpBool','ParchBool','Sex','CabinBool']] X_orig = train_df[['Pclass','Sex','Age','SibSp','Parch','Fare','CabinBool']]
Titanic - Machine Learning from Disaster
1,058,030
TARGET = 'answered_correctly' FEATURES = ['prior_question_elapsed_time', 'prior_question_had_explanation', 'content_field', 'answered_correctly_u_avg', 'elapsed_time_u_avg', 'explanation_u_avg', 'elapsed_time_q_avg', 'explanation_q_avg', 'explanation_qtrue_avg', 'explanation_qfalse_avg', 'beta_q', 'answered_correctly_u...
model_RF = RandomForestClassifier(random_state=0) my_pipeline = make_pipeline(model_RF) scores1_RF = cross_val_score(my_pipeline,X_orig,Y,scoring = 'accuracy',cv=5) scores2_RF = cross_val_score(my_pipeline,X_new,Y,scoring = 'accuracy', cv=5) Y_preds1 = cross_val_predict(my_pipeline,X_orig,Y) print('Score for model...
Titanic - Machine Learning from Disaster
1,058,030
SEED = 123 def seed_everything(seed): random.seed(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) seed_everything(SEED )<compute_test_metric>
model = XGBClassifier(random_state=0) my_pipeline = make_pipeline(model) scores1_XG = cross_val_score(my_pipeline,X_orig,Y,scoring = 'accuracy',cv=5) scores2_XG = cross_val_score(my_pipeline,X_new,Y,scoring = 'accuracy', cv=5) Y_preds1 = cross_val_predict(my_pipeline,X_orig,Y) print('Score for model with original ...
Titanic - Machine Learning from Disaster
1,058,030
def get_new_theta(is_good_answer, beta, theta, nb_previous_answers): return theta + learning_rate_theta(nb_previous_answers)*( is_good_answer - probability_of_good_answer(theta, beta) ) def get_new_beta(is_good_answer, beta, theta, nb_previous_answers): return beta - learning_rate_beta(nb_previous_answers)*( is_good...
model = SVC(random_state=0, gamma="auto") my_pipeline = make_pipeline(model) scores1_SV = cross_val_score(my_pipeline,X_orig,Y,scoring = 'accuracy',cv=5) scores2_SV = cross_val_score(my_pipeline,X_new,Y,scoring = 'accuracy', cv=5) Y_preds1 = cross_val_predict(my_pipeline,X_orig,Y) print('Score for model with origi...
Titanic - Machine Learning from Disaster
1,058,030
def add_train_features(df, answered_correctly_u_count, answered_correctly_u_sum, elapsed_time_u_sum, explanation_u_sum, timestamp_u, timestamp_u_incorrect, latest_u_theta, answered_correctly_q_count, answered_correctly_q_sum, elapsed_time_q_sum, explanation_q_sum, explanation_qtrue_sum, explanation_qtrue_count, latest_...
test_df1 = test_df test_df1['Age'].isna().sum()
Titanic - Machine Learning from Disaster
1,058,030
def add_features(df, answered_correctly_u_count, answered_correctly_u_sum, elapsed_time_u_sum, explanation_u_sum, timestamp_u, timestamp_u_incorrect, latest_u_theta, answered_correctly_q_count, answered_correctly_q_sum, elapsed_time_q_sum, explanation_q_sum, explanation_qtrue_sum, explanation_qtrue_count, latest_q_beta...
bins = [-1,0 ,5 ,12 , 18, 24, 35, 60, np.inf] labels = ['Unknown','Baby','Child','Student','Teenager','Young Adult','Adult','Senior'] test_df1['AgeGroup'] = pd.cut(test_df1['Age'],bins,labels = labels) age_map = {'Unknown' : 0, 'Baby' : 1, 'Child' : 2, 'Student' : 3, 'Teenager' : 4, 'Young Adult' : 5, 'Adult' : 6, 'Se...
Titanic - Machine Learning from Disaster