kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
11,650,794
del pickle gc.collect()<set_options>
optimizer = Adam(learning_rate=0.001, epsilon=1e-07) model.compile(optimizer = optimizer, loss = 'categorical_crossentropy', metrics=['accuracy']) earlyStopping = EarlyStopping(monitor='val_accuracy', patience=10, verbose=0, mode='auto') mcp = ModelCheckpoint('.mdl_wts.hdf5', save_best_only=True, monitor='val_accuracy', mode='auto') reduce_lr_loss = ReduceLROnPlateau(monitor='val_accuracy', factor=0.1, patience=7, verbose=1, epsilon=1e-4, mode='auto')
Digit Recognizer
11,650,794
torch.cuda.is_available()<set_options>
datagen = ImageDataGenerator( rotation_range=5, width_shift_range=0.1, height_shift_range=0.1, shear_range=5, zoom_range=0.1) datagen.fit(X_train )
Digit Recognizer
11,650,794
device = torch.device("cuda" if torch.cuda.is_available() else "cpu" )<choose_model_class>
history = model.fit_generator(datagen.flow(X_train, y_train, batch_size=64), epochs = 100, validation_data =(X_val,y_val), verbose = 1, steps_per_epoch=X_train.shape[0]//64, callbacks = [earlyStopping, mcp, reduce_lr_loss] )
Digit Recognizer
11,650,794
def create_model() : return SAKTModel(n_skill, max_seq=MAX_SEQ, embed_dim=EMBED_SIZE, forward_expansion=1, enc_layers=1, heads=8, dropout=0.1 )<load_pretrained>
model.load_weights(filepath = '.mdl_wts.hdf5' )
Digit Recognizer
11,650,794
model_attention = create_model() try: model_attention.load_state_dict(torch.load("/kaggle/input/attention/attention.pth")) except: model_attention.load_state_dict(torch.load("/kaggle/input/attention/attention.pth", map_location='cpu')) model_attention.to(device )<split>
scores = model.evaluate(X_val, y_val, callbacks = [earlyStopping, mcp, reduce_lr_loss] )
Digit Recognizer
11,650,794
env = riiideducation.make_env() iter_test = env.iter_test() prior_test_df = None prev_test_df = None<feature_engineering>
img_tensor = X_test[5].reshape(-1, 28, 28, 1 )
Digit Recognizer
11,650,794
%%time model_attention.eval() for(test_df, sample_prediction_df)in(iter_test): if(prev_test_df is not None)&(psutil.virtual_memory().percent < 95): print(psutil.virtual_memory().percent) prev_test_df['answered_correctly'] = eval(test_df['prior_group_answers_correct'].iloc[0]) prev_test_df = prev_test_df[prev_test_df.content_type_id == False] prev_group = prev_test_df[['user_id', 'content_id', 'answered_correctly']].groupby('user_id' ).apply(lambda r:( r['content_id'].values, r['answered_correctly'].values)) for prev_user_id in prev_group.index: prev_group_content = prev_group[prev_user_id][0] prev_group_answered_correctly = prev_group[prev_user_id][1] if prev_user_id in group.index: group[prev_user_id] =(np.append(group[prev_user_id][0], prev_group_content), np.append(group[prev_user_id][1], prev_group_answered_correctly)) else: group[prev_user_id] =(prev_group_content, prev_group_answered_correctly) if len(group[prev_user_id][0])> MAX_SEQ: new_group_content = group[prev_user_id][0][-MAX_SEQ:] new_group_answered_correctly = group[prev_user_id][1][-MAX_SEQ:] group[prev_user_id] =(new_group_content, new_group_answered_correctly) prev_test_df = test_df.copy() test_df_attention = test_df.copy() test_df_attention = test_df_attention[test_df_attention.content_type_id == False] test_dataset = TestDataset(group, test_df_attention, n_skill, max_seq=MAX_SEQ) test_dataloader = DataLoader(test_dataset, batch_size=len(test_df_attention), shuffle=False) attention_predictions = [] item = next(iter(test_dataloader)) x = item[0].to(device ).long() target_id = item[1].to(device ).long() with torch.no_grad() : output, _ = model_attention(x, target_id) output = torch.sigmoid(output) output = output[:, -1] attention_predictions.extend(output.cpu().numpy()) if prior_test_df is not None: prior_test_df[target] = eval(test_df['prior_group_answers_correct'].iloc[0]) prior_test_df_lecture = prior_test_df[prior_test_df[target] == -1].reset_index(drop=True) if len(prior_test_df_lecture)> 0: prior_test_df_lecture = pd.merge(prior_test_df_lecture, lectures_df, left_on='content_id', right_on='lecture_id', how='left') user_ids = prior_test_df_lecture['user_id'].values lecture_tags = prior_test_df_lecture['tag'].values for user_id, lecture_tag in zip(user_ids, lecture_tags): user_lectures_count_dict[user_id] += 1 last_lecture_tag_dict[user_id] = lecture_tag prior_test_df = prior_test_df[prior_test_df[target] != -1].reset_index(drop=True) user_ids = prior_test_df['user_id'].values content_ids = prior_test_df['content_id'].values targets = prior_test_df[target].values prior_explanations = prior_test_df['prior_question_had_explanation'].values prior_question_times = prior_test_df['prior_question_elapsed_time'].values tags = prior_test_df['first_tag'].values timestamps = prior_test_df['timestamp'].values timestamp_diffs = prior_test_df['timestamp_diff_last'].values for user_id, content_id, answered_correctly, explanation, prior_question_time, tag, timestamp, timestamp_diff in zip(user_ids, content_ids, targets, prior_explanations, prior_question_times, tags, timestamps, timestamp_diffs): if answered_correctly != 1: answered_correctly = 0 user_sum_dict[user_id] += answered_correctly user_count_dict[user_id] += 1 content_sum_dict[content_id] += answered_correctly content_count_dict[content_id] += 1 explanation_sum_dict[user_id] += explanation explanation_count_dict[user_id] += 1 last_correct_dict[user_id] = answered_correctly prior_questions_time_sum_dict[user_id] += prior_question_time prior_questions_time_count_dict[user_id] += 1 user_tag_agg_sum_dict[user_id, tag] += answered_correctly user_tag_agg_count_dict[user_id, tag] += 1 last_timestamp_dict[user_id] = timestamp user_content_id = str(user_id)+ str(content_id) user_content_id_count_dict[user_content_id] += 1 change_next_out = True if(user_id, 9)not in user_target_window_10_dict: for k in range(10): if(user_id, k)not in user_target_window_10_dict: user_target_window_10_dict[user_id, k] = answered_correctly change_next_out = False break if change_next_out: next_out = user_target_next_out_window_10_dict[user_id] user_target_window_10_dict[user_id, next_out] = answered_correctly next_out += 1 if next_out > 9: next_out = 0 user_target_next_out_window_10_dict[user_id] = next_out else: user_target_next_out_window_10_dict[user_id] = 0 change_next_out = True if(user_id, 9)not in timestamp_diff_window_10_dict: for k in range(10): if(user_id, k)not in timestamp_diff_window_10_dict: timestamp_diff_window_10_dict[user_id, k] = timestamp_diff change_next_out = False break if change_next_out: next_out = timestamp_diff_next_window_10_dict[user_id] timestamp_diff_window_10_dict[user_id, next_out] = timestamp_diff next_out += 1 if next_out > 9: next_out = 0 timestamp_diff_next_window_10_dict[user_id] = next_out else: timestamp_diff_next_window_10_dict[user_id] = 0 test_df['content_id'] = test_df['content_id'].astype('int16') test_df['prior_question_elapsed_time'] = test_df['prior_question_elapsed_time'].apply(lambda x: x/1000) test_df['prior_question_elapsed_time'].fillna(25, inplace=True) test_df['prior_question_elapsed_time'] = test_df['prior_question_elapsed_time'].astype('int16') test_df['prior_question_had_explanation'] = test_df['prior_question_had_explanation'].fillna(False ).astype(int) test_df['timestamp'] = test_df['timestamp'].apply(lambda x: x/1000 ).astype('int32') prior_test_df = test_df.copy() prior_test_df['first_tag'] = 0 prior_test_df['timestamp_diff_last'] = 0 test_df = test_df[test_df['content_type_id'] == 0].reset_index(drop=True) test_df = pd.merge(test_df, questions_df, left_on='content_id', right_on='question_id', how='left') prior_test_df.loc[prior_test_df['content_type_id'] == 0,'first_tag'] = test_df['first_tag'].values user_sum = np.zeros(len(test_df), dtype=np.int32) user_count = np.zeros(len(test_df), dtype=np.int32) content_sum = np.zeros(len(test_df), dtype=np.int32) content_count = np.zeros(len(test_df), dtype=np.int32) user_content_id_count = np.zeros(len(test_df), dtype=np.int16) user_target_window_10_array = np.zeros(len(test_df)) timestamp_diff_window_10_array = np.zeros(len(test_df)) explanation_sum = np.zeros(len(test_df), dtype=np.int32) explanation_count = np.zeros(len(test_df), dtype=np.int32) user_lectures_count = np.zeros(len(test_df), dtype=np.int16) last_lecture_tag_array = np.zeros(len(test_df), dtype=np.int16) prior_questions_time_sum = np.zeros(len(test_df), dtype=np.int32) prior_questions_time_count = np.zeros(len(test_df), dtype=np.int32) last_correct_array = np.zeros(len(test_df), dtype=np.int8) user_tag_sum = np.zeros(len(test_df), dtype=np.int16) user_tag_count = np.zeros(len(test_df), dtype=np.int16) last_timestamp_array = np.zeros(len(test_df), dtype=np.int32) for i,(user_id, content_id, tag)in enumerate(zip(test_df['user_id'].values, test_df['content_id'].values, test_df['first_tag'].values)) : user_sum[i] = user_sum_dict[user_id] user_count[i] = user_count_dict[user_id] content_sum[i] = content_sum_dict[content_id] content_count[i] = content_count_dict[content_id] explanation_sum[i] = explanation_sum_dict[user_id] explanation_count[i] = explanation_count_dict[user_id] user_tag_sum[i] = user_tag_agg_sum_dict[user_id, tag] user_tag_count[i] = user_tag_agg_count_dict[user_id, tag] last_timestamp_array[i] = last_timestamp_dict[user_id] if(user_id)in last_lecture_tag_dict: last_lecture_tag_array[i] = last_lecture_tag_dict[user_id] else: last_lecture_tag_array[i] = -9 if(user_id)in prior_questions_time_sum_dict: prior_questions_time_sum[i] = prior_questions_time_sum_dict[user_id] prior_questions_time_count[i] = prior_questions_time_count_dict[user_id] else: prior_questions_time_sum[i] = 0 prior_questions_time_count[i] = 0 if(user_id)in last_correct_dict: last_correct_array[i] = last_correct_dict[user_id] else: last_correct_array[i] = -1 user_content_id = str(user_id)+ str(content_id) user_content_id_count[i] = user_content_id_count_dict[user_content_id] user_target_10 = 0 for k in range(10): if(user_id, k)in user_target_window_10_dict: user_target_10 += user_target_window_10_dict[user_id, k] else: k -= 1 break if k >= 0: user_target_window_10_array[i] = user_target_10 /(k + 1) else: user_target_window_10_array[i] = -1 timestamp_diff_10 = 0 for k in range(10): if(user_id, k)in timestamp_diff_window_10_dict: timestamp_diff_10 += timestamp_diff_window_10_dict[user_id, k] else: k -= 1 break if k >= 0: timestamp_diff_window_10_array[i] = timestamp_diff_10 /(k + 1) else: timestamp_diff_window_10_array[i] = -1 test_df['timestamp_diff_last'] = test_df['timestamp'].values - last_timestamp_array test_df['timestamp_diff_last'] = test_df['timestamp_diff_last'].astype('int32') prior_test_df.loc[prior_test_df['content_type_id'] == 0,'timestamp_diff_last'] = test_df['timestamp_diff_last'].values test_df['last_correct'] = last_correct_array test_df['last_correct'].fillna(-1, inplace=True) test_df['last_correct'] = test_df['last_correct'].astype('int8') test_df['task_container_id'] = test_df['task_container_id'].astype('int16') test_df['prior_questions_mean_time'] =(prior_questions_time_sum + test_df['prior_question_elapsed_time'].values)/(prior_questions_time_count + 1) test_df['prior_questions_mean_time'].fillna(25, inplace=True) test_df['prior_questions_mean_time'] = test_df['prior_questions_mean_time'].astype('int16') test_df['last_lecture_tag'] = last_lecture_tag_array test_df['last_lecture_tag'].fillna(-9, inplace=True) test_df['last_lecture_tag'] = test_df['last_lecture_tag'].astype('int16') test_df['user_count_lectures'] = user_lectures_count test_df['user_count_lectures'] = test_df['user_count_lectures'].astype('int16') test_df['user_correctness'] = user_sum / user_count test_df['content_id_correctness_total'] = content_sum / content_count test_df['user_correctness'].fillna(-1, inplace=True) test_df['user_correctness'] = test_df['user_correctness'].astype('float32') test_df['content_id_correctness_total'].fillna(0.600382459, inplace=True) test_df['content_id_correctness_total'] = test_df['content_id_correctness_total'].astype('float32') test_df['user_count_questions'] = user_count test_df['user_count_questions'].fillna(0, inplace=True) test_df['user_count_questions'] = test_df['user_count_questions'].astype('int32') test_df['explanation_mean_user'] =(explanation_sum + test_df['prior_question_had_explanation'].values)/(explanation_count + 1) test_df['explanation_mean_user'].fillna(0, inplace=True) test_df['explanation_mean_user'] = test_df['explanation_mean_user'].astype('float32') test_df['content_count'] = content_count test_df['content_sum'] = content_sum test_df['repeated_times'] = user_content_id_count test_df['repeated_times'] = test_df['repeated_times'].astype('int16') test_df['repeated_times_tag'] = user_tag_count test_df['repeated_times_tag'] = test_df['repeated_times_tag'].astype('int16') test_df['user_tag_correctness'] = user_tag_sum / user_tag_count test_df['user_tag_correctness'].fillna(-1, inplace=True) test_df['user_tag_correctness'] = test_df['user_tag_correctness'].astype('float32') test_df['user_correctness_window_10_mean'] = user_target_window_10_array test_df['user_correctness_window_10_mean'].fillna(-1, inplace=True) test_df['user_correctness_window_10_mean'] = test_df['user_correctness_window_10_mean'].astype('float32') test_df['timestamp_diff_last_window_10_mean'] = timestamp_diff_window_10_array test_df['timestamp_diff_last_window_10_mean'].fillna(-1, inplace=True) test_df['timestamp_diff_last_window_10_mean'] = test_df['timestamp_diff_last_window_10_mean'].astype('int32') test_df['user_count_lectures_mean'] = test_df['user_count_lectures'] / test_df['user_count_questions'] test_df['user_count_lectures_mean'].fillna(0, inplace=True) test_df['user_count_lectures_mean'] = test_df['user_count_lectures_mean'].astype('float32') lgbm_predictions = model.predict(test_df[features]) test_df[target] = 0.2 * np.array(attention_predictions)+ 0.8 * lgbm_predictions env.predict(test_df[['row_id', target]]) <import_modules>
for layer in model.layers: if'conv' in layer.name: filters, biases = layer.get_weights() print('Layer: ', layer.name, filters.shape) f_min, f_max = filters.min() , filters.max() filters =(filters - f_min)/(f_max - f_min) print('Filter size:(', filters.shape[0], ',', filters.shape[1], ')') print('Channels in this layer: ', filters.shape[2]) print('Number of filters: ', filters.shape[3]) count = 1 plt.figure(figsize =(18, 4)) for i in range(filters.shape[3]): ax= plt.subplot(4, filters.shape[3]/4, count) ax.set_xticks([]) ax.set_yticks([]) plt.imshow(filters[:,:,0, i], cmap=plt.cm.binary) count+=1 plt.show()
Digit Recognizer
11,650,794
for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) <define_variables>
layer_outputs = [layer.output for layer in model.layers[0:8]] activation_model = models.Model(inputs = model.input, outputs = layer_outputs )
Digit Recognizer
11,650,794
path = Path('/kaggle/input') assert path.exists()<data_type_conversions>
activations = activation_model.predict(img_tensor )
Digit Recognizer
11,650,794
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(len(df), dtype = np.float32) elapsed_time_u_avg = np.zeros(len(df), dtype = np.float32) explanation_u_avg = np.zeros(len(df), dtype = np.float32) timestamp_u_recency_1 = np.zeros(len(df), dtype = np.float32) timestamp_u_recency_2 = np.zeros(len(df), dtype = np.float32) timestamp_u_recency_3 = np.zeros(len(df), dtype = np.float32) timestamp_u_incorrect_recency = np.zeros(len(df), dtype = np.float32) answered_correctly_q_avg = np.zeros(len(df), dtype = np.float32) elapsed_time_q_avg = np.zeros(len(df), dtype = np.float32) explanation_q_avg = np.zeros(len(df), dtype = np.float32) answered_correctly_uq_count = np.zeros(len(df), dtype = np.int32) for num, row in enumerate(df[['user_id', 'answered_correctly', 'content_id', 'prior_question_elapsed_time', 'prior_question_had_explanation', 'timestamp']].values): if answered_correctly_u_count[row[0]] != 0: answered_correctly_u_avg[num] = answered_correctly_u_sum[row[0]] / answered_correctly_u_count[row[0]] elapsed_time_u_avg[num] = elapsed_time_u_sum[row[0]] / answered_correctly_u_count[row[0]] explanation_u_avg[num] = explanation_u_sum[row[0]] / answered_correctly_u_count[row[0]] else: answered_correctly_u_avg[num] = np.nan elapsed_time_u_avg[num] = np.nan explanation_u_avg[num] = np.nan print(timestamp_u[row[0]]) if len(timestamp_u[row[0]])== 0: timestamp_u_recency_1[num] = np.nan timestamp_u_recency_2[num] = np.nan timestamp_u_recency_3[num] = np.nan elif len(timestamp_u[row[0]])== 1: timestamp_u_recency_1[num] = row[5] - timestamp_u[row[0]][0] timestamp_u_recency_2[num] = np.nan timestamp_u_recency_3[num] = np.nan elif len(timestamp_u[row[0]])== 2: timestamp_u_recency_1[num] = row[5] - timestamp_u[row[0]][1] timestamp_u_recency_2[num] = row[5] - timestamp_u[row[0]][0] timestamp_u_recency_3[num] = np.nan elif len(timestamp_u[row[0]])== 3: timestamp_u_recency_1[num] = row[5] - timestamp_u[row[0]][2] timestamp_u_recency_2[num] = row[5] - timestamp_u[row[0]][1] timestamp_u_recency_3[num] = row[5] - timestamp_u[row[0]][0] if len(timestamp_u_incorrect[row[0]])== 0: timestamp_u_incorrect_recency[num] = np.nan else: timestamp_u_incorrect_recency[num] = row[5] - timestamp_u_incorrect[row[0]][0] if answered_correctly_q_count[row[2]] != 0: answered_correctly_q_avg[num] = answered_correctly_q_sum[row[2]] / answered_correctly_q_count[row[2]] elapsed_time_q_avg[num] = elapsed_time_q_sum[row[2]] / answered_correctly_q_count[row[2]] explanation_q_avg[num] = explanation_q_sum[row[2]] / answered_correctly_q_count[row[2]] else: answered_correctly_q_avg[num] = np.nan elapsed_time_q_avg[num] = np.nan explanation_q_avg[num] = np.nan answered_correctly_uq_count[num] = answered_correctly_uq[row[0]][row[2]] answered_correctly_u_count[row[0]] += 1 elapsed_time_u_sum[row[0]] += row[3] explanation_u_sum[row[0]] += int(row[4]) if len(timestamp_u[row[0]])== 3: timestamp_u[row[0]].pop(0) timestamp_u[row[0]].append(row[5]) else: timestamp_u[row[0]].append(row[5]) answered_correctly_q_count[row[2]] += 1 elapsed_time_q_sum[row[2]] += row[3] explanation_q_sum[row[2]] += int(row[4]) answered_correctly_uq[row[0]][row[2]] += 1 if update: answered_correctly_u_sum[row[0]] += row[1] if row[1] == 0: if len(timestamp_u_incorrect[row[0]])== 1: timestamp_u_incorrect[row[0]].pop(0) timestamp_u_incorrect[row[0]].append(row[5]) else: timestamp_u_incorrect[row[0]].append(row[5]) answered_correctly_q_sum[row[2]] += row[1] user_df = pd.DataFrame({'answered_correctly_u_avg': answered_correctly_u_avg, 'elapsed_time_u_avg': elapsed_time_u_avg, 'explanation_u_avg': explanation_u_avg, 'answered_correctly_q_avg': answered_correctly_q_avg, 'elapsed_time_q_avg': elapsed_time_q_avg, 'explanation_q_avg': explanation_q_avg, 'answered_correctly_uq_count': answered_correctly_uq_count, 'timestamp_u_recency_1': timestamp_u_recency_1, 'timestamp_u_recency_2': timestamp_u_recency_2, 'timestamp_u_recency_3': timestamp_u_recency_3, 'timestamp_u_incorrect_recency': timestamp_u_incorrect_recency}) df.reset_index(drop=True, inplace=True) user_df.reset_index(drop=True, inplace=True) df = pd.concat([df, user_df], axis=1) return df <feature_engineering>
results = np.argmax(model.predict(X_test), axis=1) results = pd.Series(results, name = "Label") results.head(2 )
Digit Recognizer
11,650,794
<load_from_csv><EOS>
submission.to_csv("CNN_MNIST_results.csv",index=False )
Digit Recognizer
11,821,654
<SOS> metric: categorizationaccuracy Kaggle data source: digit-recognizer<define_variables>
import numpy as np import pandas as pd import matplotlib.pyplot as plt import random from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.utils import np_utils
Digit Recognizer
11,821,654
gbm = lgb.Booster(model_file='.. /input/lightgbmmodel/model.txt' )<load_from_disk>
( X_train, y_train),(X_test, y_test)= mnist.load_data() print("X_train shape", X_train.shape) print("y_train shape", y_train.shape) print("X_test shape", X_test.shape) print("y_test shape", y_test.shape )
Digit Recognizer
11,821,654
json_file = ".. /input/lightgbm-features-dicts/lightgbm_features_dicts.json" f = open(json_file) features_dicts = json.load(f )<drop_column>
test_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv', delimiter = ',', header = 0, usecols = [x for x in range(0, 784)] )
Digit Recognizer
11,821,654
del f<data_type_conversions>
X_train = X_train.reshape(60000, 784) X_test = X_test.reshape(10000, 784) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 print("Training matrix shape", X_train.shape) print("Testing matrix shape", X_test.shape )
Digit Recognizer
11,821,654
def change_type(temp): result = defaultdict(int) for k,v in temp.items() : key = float(k) value = int(float(v)) result[key] =value return result answered_correctly_u_count = change_type(answered_correctly_u_count_) answered_correctly_u_sum = change_type(answered_correctly_u_sum_) elapsed_time_u_sum = change_type(elapsed_time_u_sum_) explanation_u_sum = change_type(explanation_u_sum_) answered_correctly_q_count = change_type(answered_correctly_q_count_) answered_correctly_q_sum = change_type(answered_correctly_q_sum_) elapsed_time_q_sum = change_type(elapsed_time_q_sum_) explanation_q_sum = change_type(explanation_q_sum_) del answered_correctly_u_count_ del answered_correctly_u_sum_ del elapsed_time_u_sum_ del explanation_u_sum_ del answered_correctly_q_count_ del answered_correctly_q_sum_ del elapsed_time_q_sum_ del explanation_q_sum_<categorify>
no_classes = 10 Y_train = np_utils.to_categorical(y_train, no_classes) Y_test = np_utils.to_categorical(y_test, no_classes )
Digit Recognizer
11,821,654
def change_answered_correctly_uq_type(t): result = defaultdict(lambda: defaultdict(int)) for k,v in t.items() : key = float(k) temp = defaultdict(int) for k1,v1 in v.items() : k1 = float(k1) temp[k1] = v1 result[key] = temp return result answered_correctly_uq = change_answered_correctly_uq_type(answered_correctly_uq_) del answered_correctly_uq_<categorify>
model = Sequential()
Digit Recognizer
11,821,654
def changetolist(t): result = defaultdict(list) for k,v in t.items() : key = float(k) value = list(v) result[key] = value return result timestamp_u = changetolist(timestamp_u_) timestamp_u_incorrect = changetolist(timestamp_u_incorrect_) del timestamp_u_ del timestamp_u_incorrect_<define_variables>
model.add(Dense(512, input_shape=(784,)) )
Digit Recognizer
11,821,654
TARGET = 'answered_correctly' FEATURES = ['answered_correctly_u_avg', 'explanation_u_avg', 'elapsed_time_u_avg', 'answered_correctly_q_avg', 'explanation_q_avg', 'elapsed_time_q_avg', 'answered_correctly_uq_count', 'timestamp_u_recency_1', 'timestamp_u_recency_2', 'timestamp_u_recency_3', 'timestamp_u_incorrect_recency'] prior_question_elapsed_time_mean = 25423.810042960366 env = riiideducation.make_env() iter_test = env.iter_test() set_predict = env.predict previous_test_df = None for(test_df, sample_prediction_df)in iter_test: if previous_test_df is not None: previous_test_df[TARGET] = eval(test_df["prior_group_answers_correct"].iloc[0]) update_features(previous_test_df, answered_correctly_u_sum, answered_correctly_q_sum, timestamp_u_incorrect) previous_test_df = test_df.copy() test_df = test_df[test_df['content_type_id'] == 0].reset_index(drop = True) test_df['prior_question_had_explanation'] = test_df.prior_question_had_explanation.fillna(False ).astype('int8') test_df['prior_question_elapsed_time'].fillna(prior_question_elapsed_time_mean, inplace = True) test_df = pd.merge(test_df, questions_df[['question_id', 'part']], left_on = 'content_id', right_on = 'question_id', how = 'left') test_df[TARGET] = 0 test_df = add_features(test_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 = False) test_df[TARGET] = gbm.predict(test_df[FEATURES],num_iteration=gbm.best_iteration) set_predict(test_df[['row_id', TARGET]]) print('Job Done' )<import_modules>
model.add(Activation('relu'))
Digit Recognizer
11,821,654
import riiideducation import numpy as np import pandas as pd from tqdm import tqdm<compute_test_metric>
model.add(Dropout(0.2))
Digit Recognizer
11,821,654
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 - learning_rate_beta(nb_previous_answers)*( is_good_answer - probability_of_good_answer(theta, beta, left_asymptote) ) def learning_rate_theta(nb_answers): return max(0.3 /(1 + 0.01 * nb_answers), 0.04) def learning_rate_beta(nb_answers): return 1 /(1 + 0.05 * nb_answers) def probability_of_good_answer(theta, beta, left_asymptote): return left_asymptote +(1 - left_asymptote)* sigmoid(theta - beta) def sigmoid(x): return 1 /(1 + np.exp(-x))<find_best_params>
model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.2))
Digit Recognizer
11,821,654
def estimate_parameters(answers_df, granularity_feature_name='content_id'): item_parameters = { granularity_feature_value: {"beta": 0, "nb_answers": 0} for granularity_feature_value in np.unique(answers_df[granularity_feature_name]) } student_parameters = { student_id: {"theta": 0, "nb_answers": 0} for student_id in np.unique(answers_df.student_id) } print("Parameter estimation is starting...") for student_id, item_id, left_asymptote, answered_correctly in tqdm( zip(answers_df.student_id.values, answers_df[granularity_feature_name].values, answers_df.left_asymptote.values, answers_df.answered_correctly.values) ): theta = student_parameters[student_id]["theta"] beta = item_parameters[item_id]["beta"] item_parameters[item_id]["beta"] = get_new_beta( answered_correctly, beta, left_asymptote, theta, item_parameters[item_id]["nb_answers"], ) student_parameters[student_id]["theta"] = get_new_theta( answered_correctly, beta, left_asymptote, theta, student_parameters[student_id]["nb_answers"], ) item_parameters[item_id]["nb_answers"] += 1 student_parameters[student_id]["nb_answers"] += 1 print(f"Theta & beta estimations on {granularity_feature_name} are completed.") return student_parameters, item_parameters<define_search_space>
model.add(Dense(10)) model.add(Activation('softmax'))
Digit Recognizer
11,821,654
def update_parameters(answers_df, student_parameters, item_parameters, granularity_feature_name='content_id'): for student_id, item_id, left_asymptote, answered_correctly in tqdm(zip( answers_df.student_id.values, answers_df[granularity_feature_name].values, answers_df.left_asymptote.values, answers_df.answered_correctly.values) ): if student_id not in student_parameters: student_parameters[student_id] = {'theta': 0, 'nb_answers': 0} if item_id not in item_parameters: item_parameters[item_id] = {'beta': 0, 'nb_answers': 0} theta = student_parameters[student_id]['theta'] beta = item_parameters[item_id]['beta'] student_parameters[student_id]['theta'] = get_new_theta( answered_correctly, beta, left_asymptote, theta, student_parameters[student_id]['nb_answers'] ) item_parameters[item_id]['beta'] = get_new_beta( answered_correctly, beta, left_asymptote, theta, item_parameters[item_id]['nb_answers'] ) student_parameters[student_id]['nb_answers'] += 1 item_parameters[item_id]['nb_answers'] += 1 return student_parameters, item_parameters<compute_train_metric>
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'] )
Digit Recognizer
11,821,654
def estimate_probas(test_df, student_parameters, item_parameters, granularity_feature_name='content_id'): probability_of_success_list = [] for student_id, item_id, left_asymptote in tqdm( zip(test_df.student_id.values, test_df[granularity_feature_name].values, test_df.left_asymptote.values) ): theta = student_parameters[student_id]['theta'] if student_id in student_parameters else 0 beta = item_parameters[item_id]['beta'] if item_id in item_parameters else 0 probability_of_success_list.append(probability_of_good_answer(theta, beta, left_asymptote)) return probability_of_success_list<define_variables>
history = model.fit(X_train, Y_train, batch_size=128, epochs=10, verbose=1 )
Digit Recognizer
11,821,654
compute_estimations = False nb_rows_training = None<load_from_csv>
score = model.evaluate(X_test, Y_test) print('Test accuracy:', score[1] )
Digit Recognizer
11,821,654
if compute_estimations: training = pd.read_csv( filepath_or_buffer="/kaggle/input/riiid-test-answer-prediction/train.csv", usecols=["content_id", "user_id", "answered_correctly"], dtype={'answered_correctly': "int8"}, nrows=nb_rows_training ) training.rename(columns={'user_id': 'student_id'}, inplace=True) training = training[training.answered_correctly != -1] training['left_asymptote'] = 1/4 print(f"Dataset of shape {training.shape}") print(f"Columns are {list(training.columns)}") student_parameters, item_parameters = estimate_parameters(training) else: student_data = pd.read_csv('.. /input/thetas-20201217/thetas_20201217.csv', index_col='student_id') student_parameters = student_data.to_dict('index') print(f"Successfully read student parameter file and converted to dict.") content_data = pd.read_csv('.. /input/betas-content-id-20201217/betas_content_id_20201217.csv', index_col='content_id') item_parameters = content_data.to_dict('index') print(f"Successfully read item parameter file and converted to dict." )<categorify>
results = model.predict(test_data )
Digit Recognizer
11,821,654
def format_test_df(test_df): test_copy = test_df.copy() test_copy = test_copy[test_copy['content_type_id'] == 0] test_copy['left_asymptote'] = 1/4 test_copy = test_copy.rename(columns={'user_id': 'student_id'}) return test_copy<predict_on_test>
results = np.argmax(results,axis = 1) results = pd.Series(results,name="Label") submission = pd.concat([pd.Series(range(1,28001),name = "ImageId"),results],axis = 1) submission.to_csv("submission.csv",index=False )
Digit Recognizer
11,821,654
<compute_test_metric><EOS>
predicted_classes = model.predict_classes(X_test) correct_indices = np.nonzero(predicted_classes == y_test)[0] incorrect_indices = np.nonzero(predicted_classes != y_test)[0]
Digit Recognizer
12,529,129
<SOS> metric: categorizationaccuracy Kaggle data source: digit-recognizer<import_modules>
np.random.seed(1) get_ipython().magic('matplotlib inline') print(tf.__version__ )
Digit Recognizer
12,529,129
import matplotlib.pyplot as plt import seaborn as sns from sklearn.ensemble import RandomForestRegressor<load_from_csv>
train_path=".. /input/digit-recognizer/train.csv" test_path=".. /input/digit-recognizer/test.csv" train = pd.read_csv(train_path) test= pd.read_csv(test_path) print(train.shape) print(test.shape) train.head()
Digit Recognizer
12,529,129
np.random.seed(seed=1234) skiprows = np.random.rand(55 * 10 ** 7)> 0.02 skiprows[0] = False df_ = pd.read_csv("/kaggle/input/new-york-city-taxi-fare-prediction/train.csv", skiprows=lambda x: skiprows[x]) df_.head()<define_variables>
x = x.values.reshape(-1,28,28,1) print("x shape: ",x.shape) y = to_categorical(y, num_classes = 10) print("y shape: ",y.shape) print(y[10]) plt.imshow(-x[10][:,:,0],cmap='gray') plt.axis(False) plt.show()
Digit Recognizer
12,529,129
lon_min, lon_max = -75, -72 lat_min, lat_max = 40, 43<feature_engineering>
X_train, X_val, Y_train, Y_val = train_test_split(x, y, test_size = 0.2, random_state=1) print("x_train shape",X_train.shape) print("x_val shape",X_val.shape) print("y_train shape",Y_train.shape) print("y_val shape",Y_val.shape )
Digit Recognizer
12,529,129
df = df_.copy() df = df.drop(columns=["key"]) df["date"] = df["pickup_datetime"].apply(lambda x: x.split() [0]) df["time"] = df["pickup_datetime"].apply(lambda x: x.split() [1]) df = df.drop("pickup_datetime", axis=1) df["year"] = df["date"].apply(lambda x: int(x.split("-")[0])) df["month"] = df["date"].apply(lambda x: int(x.split("-")[1])) df["day"] = df["date"].apply(lambda x: int(x.split("-")[2])) df = df.drop("date", axis=1) df["time"] = df["time"].apply(lambda x: int(x[:2])* 60 + int(x[3:5])) df["befor_shock"] =(( df["year"] <= 2011)|(( df["year"] <= 2012)&(df["month"] <= 8)) ).apply(int) df = df[ (~df["dropoff_longitude"].isnull())& (~df["dropoff_latitude"].isnull()) ] df = df[ (lon_min < df["pickup_longitude"])& (df["pickup_longitude"] < lon_max)& (lat_min < df["pickup_latitude"])& (df["pickup_latitude"] < lat_max)& (lon_min < df["dropoff_longitude"])& (df["dropoff_longitude"] < lon_max)& (lat_min < df["dropoff_latitude"])& (df["dropoff_latitude"] < lat_max) ] df.head()<prepare_x_and_y>
datagen = ImageDataGenerator(rotation_range = 10, zoom_range = 0.1, width_shift_range = 0.1, height_shift_range = 0.1, horizontal_flip = False, vertical_flip = False) datagen.fit(X_train )
Digit Recognizer
12,529,129
X = np.array(df.drop( columns=[ "fare_amount", ] )) y = np.array(df["fare_amount"] )<split>
Image = [[0,0,0], [0,1,1], [0,1,2]] kernel = [[-4,0,0], [0,0,0], [0,0,4]] result = signal.convolve(Image,kernel,'valid') result2 = 4*0 + 0*0 + 0*0 + 0*0 + 0*1 + 0*1 + 0*1 + 0*0 + -4*2 print("Result with scipy: {} Result with manual calculs : {}".format(result,result2)) print(" With 'same': {}".format(signal.convolve(Image,kernel,'same'))) print(" With 'padding': {}".format(signal.convolve(Image,kernel,'full')) )
Digit Recognizer
12,529,129
np.random.seed(seed=1234) train_rows = np.random.rand(y.size)> 0.2 X_train, y_train = X[train_rows, :], y[train_rows] X_valid, y_valid = X[~train_rows, :], y[~train_rows]<train_model>
def define_model(actifun="elu",actifundense1="elu",actifundense2="softsign",optimizer="Adam"): model = model = Sequential([ Conv2D(32,(3, 3), padding = 'same', activation = 'relu', input_shape =(28,28,1)) , BatchNormalization() , Conv2D(32,(3, 3), padding = 'same', activation = 'relu'), BatchNormalization() , MaxPool2D(2, 2), Dropout(0.2), Conv2D(64,(3, 3), padding = 'same', activation = 'relu'), BatchNormalization() , Conv2D(64,(3, 3), padding = 'same', activation = 'relu'), BatchNormalization() , MaxPool2D(2, 2), Dropout(0.2), Conv2D(128,(3, 3), padding = 'same', activation = 'relu'), BatchNormalization() , Conv2D(128,(3, 3), padding = 'same', activation = 'relu'), BatchNormalization() , MaxPool2D(2, 2), Dropout(0.2), Flatten() , Dense(256, activation = 'relu'), Dropout(0.25), Dense(10, activation = 'softmax') ]) model.compile(optimizer = optimizer , loss = "categorical_crossentropy", metrics=["accuracy"]) return model model = define_model() model.summary()
Digit Recognizer
12,529,129
model = RandomForestRegressor(max_depth=30, n_estimators=100, n_jobs=-1) model.fit(X_train, y_train) y_valid_pred = model.predict(X_valid) rmse(y_valid, y_valid_pred )<load_from_csv>
%%time X_train_train, X_train_val, Y_train_train, Y_train_val = train_test_split(X_train, Y_train, test_size = 0.3, random_state = 0) models={} history={} optim_list = ["Adam","RMSprop"] lr_sched = ReduceLROnPlateau(monitor = 'val_acc', patience = 10, verbose = 1, factor = 0.1, min_lr = 0.00001) early_stopping = EarlyStopping(monitor = 'val_acc', patience = 10, verbose = 1, mode = 'auto', restore_best_weights = True) epochs=50 batch_size = 200 for optim in optim_list: for fun in ["elu","relu"]: fun1 = fun fun2 = fun print(" ") print(" ") mtype = optim + ' + ' + fun1 + ' + ' + fun2 + ' + ' + "softsign" print(mtype) print(" ") models[mtype] = define_model(fun1,fun2,"softsign",optim) history[mtype] = models[mtype].fit(X_train,Y_train, validation_split=0.2,epochs=epochs ,shuffle=True,steps_per_epoch=X_train.shape[0] // batch_size, callbacks=[lr_sched,early_stopping] )
Digit Recognizer
12,529,129
test = pd.read_csv("/kaggle/input/new-york-city-taxi-fare-prediction/test.csv") test.head()<feature_engineering>
rslts={} k=0 for optim in optim_list: for fun in ["elu","relu"]: fun1 = fun fun2 = fun fun3 = "softsign" mtype = optim + ' + ' + fun1 + ' + ' + fun2 + ' + ' + fun3 rslts[mtype] =(models[mtype].evaluate(X_val, Y_val, verbose = 0)[1]) k=k+1 for item in sorted(rslts.items() , key=lambda x: x[1],reverse=True): print(item[0]) print(item[1]) print(" ") plt.figure(figsize=(30,30)) i=0 fun ="elu" fun1 = fun fun2 = fun fun3 = "softsign" mtype = optim + ' + ' + fun1 + ' + ' + fun2 + ' + ' + fun3 plt.subplot(2,1,i+1) plt.plot(history[mtype].history['loss'], label='loss') plt.plot(history[mtype].history['val_loss'], color='b', label='val_loss') plt.title("mtype") plt.xlabel("Number of Epochs") plt.ylabel("Loss") plt.legend() i = i +1 plt.show()
Digit Recognizer
12,529,129
test["date"] = test["pickup_datetime"].apply(lambda x: x.split() [0]) test["time"] = test["pickup_datetime"].apply(lambda x: x.split() [1]) test = test.drop("pickup_datetime", axis=1) test["year"] = test["date"].apply(lambda x: int(x.split("-")[0])) test["month"] = test["date"].apply(lambda x: int(x.split("-")[1])) test["day"] = test["date"].apply(lambda x: int(x.split("-")[2])) test = test.drop("date", axis=1) test["time"] = test["time"].apply(lambda x: int(x[:2])* 60 + int(x[3:5])) test["before_shock"] =(( test["year"] <= 2011)|(( test["year"] <= 2012)&(test["month"] <= 8)) ).apply(int) test.head()<save_to_csv>
datagen.fit(x) X_train, X_val, Y_train, Y_val = train_test_split(x, y, test_size = 0.1, random_state = 0) lr_sched = ReduceLROnPlateau(monitor = 'val_acc', patience = 10, verbose = 1, factor = 0.1, min_lr = 0.00001) early_stopping = EarlyStopping(monitor = 'val_acc', patience = 10, verbose = 1, mode = 'auto', restore_best_weights = True) epochs=50 batch_size = 200 model = define_model("elu","elu","softsign","RMSprop") history_final = model.fit(datagen.flow(X_train,Y_train, batch_size = batch_size), epochs = epochs, steps_per_epoch = X_train.shape[0] // batch_size, validation_data =(X_val, Y_val), callbacks = [lr_sched, early_stopping] )
Digit Recognizer
12,529,129
X_test = np.array(test.drop(columns=[ "key", ])) y_pred = model.predict(X_test) test["fare_amount"] = y_pred submission= test[["key", "fare_amount"]] submission.to_csv("./submission.csv", index=False )<load_from_csv>
test_path=".. /input/digit-recognizer/test.csv" test = pd.read_csv(test_path) test = test / 255.0 test = test.values.reshape(-1,28,28,1) Y_pred_test = model.predict(test) Y_pred_classes_test = np.argmax(Y_pred_test,axis = 1) np.savetxt('submission.csv', np.c_[range(1,len(test)+1), Y_pred_classes_test], delimiter=',', header = 'ImageId,Label', comments = '', fmt='%d' )
Digit Recognizer
12,445,197
MODE = 1 FUDGE = 2.0 FILE = '.. /input/rfcx-minimal/submission.csv' df = pd.read_csv(FILE) for k in range(24): df.iloc[:,1+k] -= df.iloc[:,1+k].min() df.iloc[:,1+k] /= df.iloc[:,1+k].max() def scale(probs, factor): probs = probs.copy() idx = np.where(probs!=1)[0] odds = factor * probs[idx] /(1-probs[idx]) probs[idx] = odds/(1+odds) return probs d1 = df.iloc[:,1:].mean().values d2 = np.array([113,204,44,923,53,41,3,213,44,23,26,149,255,14,123,222,46,6,474,4,17,18,23,72])/1000. for k in range(24): if MODE==1: d = FUDGE if MODE==2: d = d1[k]/(1-d1[k]) if MODE==3: s = d2[k] / d1[k] else: s =(d2[k]/(1-d2[k])) /d df.iloc[:,k+1] = scale(df.iloc[:,k+1].values,s) df.to_csv('submission_with_pp.csv',index=False )<define_variables>
train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv') test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv' )
Digit Recognizer
12,445,197
save_to_disk = 0<install_modules>
X_train_raw = train.drop(columns=['label'] ).to_numpy() y_train_raw = train['label'].to_numpy()
Digit Recognizer
12,445,197
!pip install resnest > /dev/null<normalization>
x_mean = np.mean(X_train_raw) x_std = np.std(X_train_raw) def standarize(X): return(X - x_mean)/ x_std X_train = np.reshape(X_train_raw,(-1,28,28,1)) X_train = standarize(X_train) y_train_cat = keras.utils.to_categorical(y_train_raw )
Digit Recognizer
12,445,197
def horizontal_flip(img): horizontal_flip_img = img[:, ::-1] return addChannels(horizontal_flip_img) def vertical_flip(img): vertical_flip_img = img[::-1, :] return addChannels(vertical_flip_img) def addNoisy(img): noise_img = util.random_noise(img) return addChannels(noise_img) def contrast_stretching(img): contrast_img = exposure.rescale_intensity(img) return addChannels(contrast_img) def randomGaussian(img): gaussian_img = gaussian(img) return addChannels(gaussian_img) def grayScale(img): gray_img = rgb2gray(img) return addChannels(gray_img) def randomGamma(img): img_gamma = exposure.adjust_gamma(img) return addChannels(img_gamma) def addChannels(img): return np.stack(( img, img, img)) def spec_to_image(spec): spec = resize(spec,(224, 400)) eps=1e-6 mean = spec.mean() std = spec.std() spec_norm =(spec - mean)/(std + eps) spec_min, spec_max = spec_norm.min() , spec_norm.max() spec_scaled = 255 *(spec_norm - spec_min)/(spec_max - spec_min) spec_scaled = spec_scaled.astype(np.uint8) spec_scaled = np.asarray(spec_scaled) return spec_scaled<choose_model_class>
data_generator = keras.preprocessing.image.ImageDataGenerator( rotation_range=10, width_shift_range=0.1, height_shift_range=0.1, zoom_range=0.1 ) data_generator.fit(X_train )
Digit Recognizer
12,445,197
def get_model() : resnet_model = resnest50(pretrained=True) num_ftrs = resnet_model.fc.in_features resnet_model.fc = nn.Linear(num_ftrs, num_birds) resnet_model = resnet_model.to(device) return resnet_model<define_variables>
def make_model() : model = keras.models.Sequential() model.add(keras.layers.Conv2D(32, kernel_size=3,activation='relu',kernel_initializer='he_normal',input_shape=(28, 28, 1))) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Conv2D(32, kernel_size=3,activation='relu')) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Conv2D(32, kernel_size=5, strides=2, padding='same',activation='relu')) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Dropout(0.4)) model.add(keras.layers.Conv2D(64, kernel_size=3, activation ='relu')) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Conv2D(64, kernel_size=3, activation ='relu')) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Conv2D(64, kernel_size=5, strides=2, padding='same',activation='relu')) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Dropout(0.4)) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(128, activation = "relu")) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Dropout(0.4)) model.add(keras.layers.Dense(10, activation = "softmax")) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
Digit Recognizer
12,445,197
class AudioData(Dataset): def __init__(self, X, y, data_type): self.data = [] self.labels = [] self.augs = [ addNoisy, contrast_stretching, randomGaussian, grayScale, randomGamma, vertical_flip, horizontal_flip, addChannels ] self.data_type=data_type for i in range(0, len(X)) : recording_id = X[i] label = y[i] mel_spec = audio_data[recording_id]['original'] self.data.append(mel_spec) self.labels.append(label) def __len__(self): return len(self.data) def __getitem__(self, idx): if self.data_type == "train": aug= random.choice(self.augs) data = aug(self.data[idx]) else: data = addChannels(self.data[idx]) return data, self.labels[idx]<import_modules>
ens_size=16 model = [0]*ens_size for i in range(ens_size): model[i] = make_model()
Digit Recognizer
12,445,197
import torch import torch.nn as nn import copy<init_hyperparams>
history = [0]*ens_size start = time.perf_counter() for i in range(ens_size): callbacks = [keras.callbacks.ModelCheckpoint('/kaggle/working/mdl-{}-of-{}.hdf5' .format(i,ens_size-1),save_best_only=True, monitor='val_accuracy', mode='max')] X_train_ens, X_valid_ens, y_train_ens, y_valid_ens = train_test_split(X_train, y_train_cat, train_size=0.9) train_aug = data_generator.flow(X_train_ens, y_train_ens) history[i] = model[i].fit_generator(train_aug, epochs=40, validation_data=(X_valid_ens, y_valid_ens), callbacks=callbacks, verbose = 0) print("CNN {}: Train accuracy={:0.5f}, Validation accuracy={:0.5f}" .format(i,max(history[i].history['accuracy']),max(history[i].history['val_accuracy']))) stop = time.perf_counter() print(f"{stop - start:0.4f}" )
Digit Recognizer
12,445,197
class Adas(Optimizer): r def __init__(self, params, lr = 0.001, lr2 =.005, lr3 =.0005, beta_1 = 0.999, beta_2 = 0.999, beta_3 = 0.9999, epsilon = 1e-8, **kwargs): if not 0.0 <= lr: raise ValueError("Invalid lr: {}".format(lr)) if not 0.0 <= lr2: raise ValueError("Invalid lr2: {}".format(lr)) if not 0.0 <= lr3: raise ValueError("Invalid lr3: {}".format(lr)) if not 0.0 <= epsilon: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= beta_1 < 1.0: raise ValueError("Invalid beta_1 parameter: {}".format(betas[0])) if not 0.0 <= beta_2 < 1.0: raise ValueError("Invalid beta_2 parameter: {}".format(betas[1])) if not 0.0 <= beta_3 < 1.0: raise ValueError("Invalid beta_3 parameter: {}".format(betas[2])) defaults = dict(lr=lr, lr2=lr2, lr3=lr3, beta_1=beta_1, beta_2=beta_2, beta_3=beta_3, epsilon=epsilon) self._varn = None self._is_create_slots = None self._curr_var = None self._lr = lr self._lr2 = lr2 self._lr3 = lr3 self._beta_1 = beta_1 self._beta_2 = beta_2 self._beta_3 = beta_3 self._epsilon = epsilon super(Adas, self ).__init__(params, defaults) def __setstate__(self, state): super(Adas, self ).__setstate__(state) @torch.no_grad() def _add(self,x,y): x.add_(y) return x @torch.no_grad() def _derivatives_normalizer(self,derivative,beta): steps = self._make_variable(0,() ,derivative.dtype) self._add(steps,1) factor =(1.-(self._beta_1 ** steps)).sqrt() m = self._make_variable(0,derivative.shape,derivative.dtype) moments = self._make_variable(0,derivative.shape,derivative.dtype) m.mul_(self._beta_1 ).add_(( 1 - self._beta_1)* derivative * derivative) np_t = derivative * factor /(m.sqrt() + self._epsilon) return(moments,np_t,lambda: moments.mul_(beta ).add_(( 1 - beta)* np_t)) def _make_variable(self,value,shape,dtype): self._varn += 1 name = 'unnamed_variable' + str(self._varn) if self._is_create_slots: self.state[self._curr_var][name] = torch.full(size=shape,fill_value=value,dtype=dtype,device=self._curr_var.device) return self.state[self._curr_var][name] @torch.no_grad() def _get_updates_universal_impl(self, grad, param): lr = self._make_variable(value = self._lr,shape=param.shape[1:], dtype=param.dtype) moment, deriv, f = self._derivatives_normalizer(grad,self._beta_3) param.add_(- torch.unsqueeze(lr,0)* deriv) lr_deriv = torch.sum(moment * grad,0) f() master_lr = self._make_variable(self._lr2,() ,dtype=torch.float32) m2,d2, f = self._derivatives_normalizer(lr_deriv,self._beta_2) self._add(lr,master_lr * lr * d2) master_lr_deriv2 = torch.sum(m2 * lr_deriv) f() m3,d3,f = self._derivatives_normalizer(master_lr_deriv2,0.) self._add(master_lr,self._lr3 * master_lr * d3) f() @torch.no_grad() def _get_updates_universal(self, param, grad, is_create_slots): self._curr_var = param self._is_create_slots = is_create_slots self._varn = 0 return self._get_updates_universal_impl(grad,self._curr_var.data) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad() : loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adas does not support sparse gradients') self._get_updates_universal(p,grad,len(self.state[p])== 0) return loss<set_options>
X_test = np.reshape(test.to_numpy() ,(-1,28,28,1)) X_test = standarize(X_test )
Digit Recognizer
12,445,197
num_birds = 24 if torch.cuda.is_available() : device=torch.device('cuda:0') else: device=torch.device('cpu' )<train_model>
preds = np.zeros(( X_test.shape[0],10)) for i in range(ens_size): mdl = keras.models.load_model('/kaggle/working/mdl-{}-of-{}.hdf5'.format(i,ens_size-1)) preds = preds + mdl.predict(X_test )
Digit Recognizer
12,445,197
learning_rate = 2e-4 epochs = 20 loss_fn = nn.CrossEntropyLoss() def train(model, loss_fn, train_loader, valid_loader, epochs, optimizer, scheduler): best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 train_losses = [] valid_losses = [] for epoch in tqdm(range(1,epochs+1)) : model.train() batch_losses=[] for i, data in enumerate(train_loader): x, y = data optimizer.zero_grad() x = x.to(device, dtype=torch.float32) y = y.to(device, dtype=torch.long) y_hat = model(x) loss = loss_fn(y_hat, y) loss.backward() batch_losses.append(loss.item()) optimizer.step() train_losses.append(batch_losses) print(f'Epoch - {epoch} Train-Loss : {np.mean(train_losses[-1])}') model.eval() batch_losses=[] trace_y = [] trace_yhat = [] for i, data in enumerate(valid_loader): x, y = data x = x.to(device, dtype=torch.float32) y = y.to(device, dtype=torch.long) y_hat = model(x) loss = loss_fn(y_hat, y) trace_y.append(y.cpu().detach().numpy()) trace_yhat.append(y_hat.cpu().detach().numpy()) batch_losses.append(loss.item()) valid_losses.append(batch_losses) trace_y = np.concatenate(trace_y) trace_yhat = np.concatenate(trace_yhat) accuracy = np.mean(trace_yhat.argmax(axis=1)==trace_y) print(f'Epoch - {epoch} Valid-Loss : {np.mean(valid_losses[-1])} Valid-Accuracy : {accuracy}') scheduler.step(np.mean(valid_losses[-1])) if accuracy > best_acc: best_acc = accuracy best_model_wts = copy.deepcopy(model.state_dict()) model.load_state_dict(best_model_wts) return model<load_from_csv>
submit_pred = np.argmax(preds,axis=1) submit_pred.shape
Digit Recognizer
12,445,197
fft = 2048 hop = 512 sr = 48000 length = 10 * sr with open('/kaggle/input/rfcx-species-audio-detection/train_tp.csv')as f: reader = csv.reader(f) next(reader, None) data = list(reader) fmin = 24000 fmax = 0 for i in range(0, len(data)) : if fmin > float(data[i][4]): fmin = float(data[i][4]) if fmax < float(data[i][6]): fmax = float(data[i][6]) fmin = int(fmin * 0.9) fmax = int(fmax * 1.1) print('Minimum frequency: ' + str(fmin)+ ', maximum frequency: ' + str(fmax)) label_list = [] data_list = [] audio_data = {} for d in data: recording_id = d[0] species_id = int(d[1]) data_list.append(recording_id) label_list.append(species_id) audio_data[recording_id] = {} wav, sr = librosa.load('/kaggle/input/rfcx-species-audio-detection/train/' + recording_id + '.flac', sr=None) t_min = float(d[3])* sr t_max = float(d[5])* sr center = np.round(( t_min + t_max)/ 2) beginning = center - length / 2 if beginning < 0: beginning = 0 ending = beginning + length if ending > len(wav): ending = len(wav) beginning = ending - length slice = wav[int(beginning):int(ending)] spec=librosa.feature.melspectrogram(slice, sr=sr,n_fft=fft,hop_length=hop,fmin=fmin,fmax=fmax) spec_db=librosa.power_to_db(spec,top_db=80) img = spec_to_image(spec_db) audio_data[recording_id]["original"] = img<train_model>
submition = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv') submition['Label'] = submit_pred
Digit Recognizer
12,445,197
nfold = 5 skf = KFold(n_splits=nfold, shuffle=True, random_state=32) for fold_id,(train_index, val_index)in enumerate(skf.split(data_list, label_list)) : print("Fold", fold_id) X_train = np.take(data_list, train_index) y_train = np.take(label_list, train_index, axis = 0) X_val = np.take(data_list, val_index) y_val = np.take(label_list, val_index, axis = 0) train_data = AudioData(X_train, y_train, "train") valid_data = AudioData(X_val, y_val, "valid") train_loader = DataLoader(train_data, batch_size=8, shuffle=True, drop_last=True) valid_loader = DataLoader(valid_data, batch_size=8, shuffle=True, drop_last=True) resnet_model = get_model() optimizer = Adas(resnet_model.parameters() , lr=learning_rate) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=3) resnet_model = train(resnet_model, loss_fn, train_loader, valid_loader, epochs, optimizer, scheduler) torch.save(resnet_model.state_dict() , "model"+str(fold_id)+".pt") del train_data, valid_data, train_loader, valid_loader, resnet_model, X_train, X_val, y_train, y_val<load_pretrained>
submition.to_csv('/kaggle/working/submition_ens3.csv', index=False )
Digit Recognizer
12,468,048
def load_test_file(f): wav, sr = librosa.load('/kaggle/input/rfcx-species-audio-detection/test/' + f, sr=None) segments = len(wav)/ length segments = int(np.ceil(segments)) mel_array = [] for i in range(0, segments): if(i + 1)* length > len(wav): slice = wav[len(wav)- length:len(wav)] else: slice = wav[i * length:(i + 1)* length] spec=librosa.feature.melspectrogram(slice, sr=sr,n_fft=fft,hop_length=hop,fmin=fmin,fmax=fmax) spec_db=librosa.power_to_db(spec,top_db=80) img = spec_to_image(spec_db) mel_spec = np.stack(( img, img, img)) mel_array.append(mel_spec) return mel_array<load_pretrained>
import pandas as pd import numpy as np
Digit Recognizer
12,468,048
del audio_data members = [] for i in range(nfold): model = get_model() model.load_state_dict(torch.load('/kaggle/working/model'+str(i)+'.pt')) model.eval() members.append(model )<save_to_csv>
import pandas as pd import numpy as np
Digit Recognizer
12,468,048
if save_to_disk == 0: for f in os.listdir('/kaggle/working/'): os.remove('/kaggle/working/' + f) print('Starting prediction loop') with open('submission.csv', 'w', newline='')as csvfile: submission_writer = csv.writer(csvfile, delimiter=',') submission_writer.writerow(['recording_id','s0','s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11', 's12','s13','s14','s15','s16','s17','s18','s19','s20','s21','s22','s23']) test_files = os.listdir('/kaggle/input/rfcx-species-audio-detection/test/') print(len(test_files)) for i in range(0, len(test_files)) : data = load_test_file(test_files[i]) data = torch.tensor(data) data = data.float() if torch.cuda.is_available() : data = data.cuda() output_list = [] for m in members: output = m(data) maxed_output = torch.max(output, dim=0)[0] maxed_output = maxed_output.cpu().detach() output_list.append(maxed_output) avg_maxed_output = torch.mean(torch.stack(output_list), dim=0) file_id = str.split(test_files[i], '.')[0] write_array = [file_id] for out in avg_maxed_output: write_array.append(out.item()) submission_writer.writerow(write_array) if i % 100 == 0 and i > 0: print('Predicted for ' + str(i)+ ' of ' + str(len(test_files)+ 1)+ ' files') print('Submission generated' )<install_modules>
import tensorflow as tf from tensorflow import keras
Digit Recognizer
12,468,048
! pip install -q efficientnet<import_modules>
train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv') train.head()
Digit Recognizer
12,468,048
import math, os, re, warnings, random , time from collections import namedtuple import tensorflow as tf import numpy as np import pandas as pd import librosa from kaggle_datasets import KaggleDatasets import matplotlib.pyplot as plt from IPython.display import Audio from tensorflow.keras import Model, layers , optimizers from sklearn.model_selection import KFold import tensorflow.keras.backend as K from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler from tensorflow.keras.layers import GlobalAveragePooling2D, Input, Dense, Dropout, GaussianNoise, concatenate from tensorflow.keras.applications import ResNet50 import efficientnet.keras as efn import seaborn as sns<set_options>
test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv') test.head()
Digit Recognizer
12,468,048
try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print(f'Running on TPU {tpu.master() }') except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) else: strategy = tf.distribute.get_strategy() AUTO = tf.data.experimental.AUTOTUNE REPLICAS = strategy.num_replicas_in_sync print(f'REPLICAS: {REPLICAS}' )<define_variables>
X_train /= 255 test /= 255
Digit Recognizer
12,468,048
def seed_everything(seed=0): random.seed(seed) np.random.seed(seed) tf.random.set_seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) os.environ['TF_DETERMINISTIC_OPS'] = '1' seed = 42 seed_everything(seed) warnings.filterwarnings('ignore' )<define_variables>
X_train = X_train.values.reshape(-1,28,28,1) test = test.values.reshape(-1,28,28,1 )
Digit Recognizer
12,468,048
def count_data_items(filenames): n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames] return np.sum(n) TRAIN_DATA_DIR = 'rfcx-audio-detection' TRAIN_GCS_PATH = KaggleDatasets().get_gcs_path(TRAIN_DATA_DIR) FILENAMES = tf.io.gfile.glob(TRAIN_GCS_PATH + '/tp*.tfrec') TEST_DATA_DIR = 'rfcx-species-audio-detection' TEST_GCS_PATH = KaggleDatasets().get_gcs_path(TEST_DATA_DIR) TEST_FILES = tf.io.gfile.glob(TEST_GCS_PATH + '/tfrecords/test/*.tfrec') no_of_training_samples = count_data_items(FILENAMES) print('num_training_samples are', no_of_training_samples )<define_variables>
Y_train = to_categorical(y_train,num_classes = 10 )
Digit Recognizer
12,468,048
CUT = 10 TIME = 10 EPOCHS = 25 GLOBAL_BATCH_SIZE = 4 * REPLICAS LEARNING_RATE = 0.0015 WARMUP_LEARNING_RATE = 1e-5 WARMUP_EPOCHS = int(EPOCHS*0.1) PATIENCE = 10 STEPS_PER_EPOCH = 64 N_FOLDS = 5 NUM_TRAINING_SAMPLES = no_of_training_samples class params: sample_rate = 48000 stft_window_seconds: float = 0.025 stft_hop_seconds: float = 0.005 frame_length: int = 1200 mel_bands: int = 256 mel_min_hz: float = 50.0 mel_max_hz: float = 16000.0 log_offset: float = 0.001 patch_bands = mel_bands conv_padding: str = 'same' batchnorm_center: bool = True batchnorm_scale: bool = False batchnorm_epsilon: float = 1e-4 num_classes: int = 24 dropout = 0.40 classifier_activation: str = 'sigmoid' height = mel_bands width = 1024<feature_engineering>
random_seed=2 X_train, X_val, Y_train, Y_val = train_test_split(X_train,Y_train,test_size = 0.1, random_state=random_seed )
Digit Recognizer
12,468,048
feature_description = { 'wav': tf.io.FixedLenFeature([], tf.string), 'recording_id': tf.io.FixedLenFeature([], tf.string), 'target' : tf.io.FixedLenFeature([], tf.float32), 'song_id': tf.io.FixedLenFeature([], tf.float32), 'tmin' : tf.io.FixedLenFeature([], tf.float32), 'fmin' : tf.io.FixedLenFeature([], tf.float32), 'tmax' : tf.io.FixedLenFeature([], tf.float32), 'fmax' : tf.io.FixedLenFeature([], tf.float32), } feature_dtype = { 'wav': tf.float32, 'recording_id': tf.string, 'target': tf.float32, 'song_id': tf.float32, 't_min': tf.float32, 'f_min': tf.float32, 't_max': tf.float32, 'f_max':tf.float32, }<normalization>
from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D from keras.optimizers import RMSprop from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import ReduceLROnPlateau
Digit Recognizer
12,468,048
def waveform_to_log_mel_spectrogram(waveform,target_or_rec_id): window_length_samples = int( round(params.sample_rate * params.stft_window_seconds)) hop_length_samples = int( round(params.sample_rate * params.stft_hop_seconds)) fft_length = 2 ** int(np.ceil(np.log(window_length_samples)/ np.log(2.0))) num_spectrogram_bins = fft_length // 2 + 1 magnitude_spectrogram = tf.abs(tf.signal.stft( signals=waveform, frame_length=params.frame_length, frame_step=hop_length_samples, fft_length= fft_length)) linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix( num_mel_bins=params.mel_bands, num_spectrogram_bins=num_spectrogram_bins, sample_rate=params.sample_rate, lower_edge_hertz=params.mel_min_hz, upper_edge_hertz=params.mel_max_hz) mel_spectrogram = tf.matmul( magnitude_spectrogram, linear_to_mel_weight_matrix) log_mel = tf.math.log(mel_spectrogram + params.log_offset) log_mel = tf.transpose(log_mel) log_mel_spectrogram = tf.reshape(log_mel , [tf.shape(log_mel)[0] ,tf.shape(log_mel)[1],1]) return log_mel_spectrogram, target_or_rec_id<categorify>
cnn = Sequential() cnn.add(Conv2D(filters=32,kernel_size=(5,5),padding='Same',activation='relu', input_shape=(28,28,1))) cnn.add(Conv2D(filters=32,kernel_size=(5,5),padding='Same',activation='relu')) cnn.add(MaxPool2D(pool_size=(2,2))) cnn.add(Dropout(0.25)) cnn.add(Conv2D(filters=64,kernel_size=(3,3),padding='Same',activation='relu')) cnn.add(Conv2D(filters=64,kernel_size=(3,3),padding='Same',activation='relu')) cnn.add(MaxPool2D(pool_size=(2,2), strides=(2,2))) cnn.add(Dropout(0.25)) cnn.add(Flatten()) cnn.add(Dense(units=256, activation='relu')) cnn.add(Dropout(0.25)) cnn.add(Dense(units=10, activation='softmax'))
Digit Recognizer
12,468,048
def frequency_masking(mel_spectrogram): frequency_masking_para = 80, frequency_mask_num = 2 fbank_size = tf.shape(mel_spectrogram) n, v = fbank_size[0], fbank_size[1] for i in range(frequency_mask_num): f = tf.random.uniform([], minval=0, maxval= tf.squeeze(frequency_masking_para), dtype=tf.int32) v = tf.cast(v, dtype=tf.int32) f0 = tf.random.uniform([], minval=0, maxval= tf.squeeze(v-f), dtype=tf.int32) mask = tf.concat(( tf.ones(shape=(n, v - f0 - f,1)) , tf.zeros(shape=(n, f,1)) , tf.ones(shape=(n, f0,1)) , ),1) mel_spectrogram = mel_spectrogram * mask return tf.cast(mel_spectrogram, dtype=tf.float32) def time_masking(mel_spectrogram): time_masking_para = 40, time_mask_num = 1 fbank_size = tf.shape(mel_spectrogram) n, v = fbank_size[0], fbank_size[1] for i in range(time_mask_num): t = tf.random.uniform([], minval=0, maxval=tf.squeeze(time_masking_para), dtype=tf.int32) t0 = tf.random.uniform([], minval=0, maxval= n-t, dtype=tf.int32) mask = tf.concat(( tf.ones(shape=(n-t0-t, v,1)) , tf.zeros(shape=(t, v,1)) , tf.ones(shape=(t0, v,1)) , ), 0) mel_spectrogram = mel_spectrogram * mask return tf.cast(mel_spectrogram, dtype=tf.float32) def random_brightness(image): return tf.image.random_brightness(image, 0.2) def random_gamma(image): return tf.image.random_contrast(image, lower = 0.1, upper = 0.3) def random_flip_right(image): return tf.image.random_flip_left_right(image) def random_flip_up_down(image): return tf.image.random_flip_left_right(image) available_ops = [ frequency_masking , time_masking, random_brightness, random_flip_up_down, random_flip_right ] def apply_augmentation(image, target): num_layers = int(np.random.uniform(low = 0, high = 3)) for layer_num in range(num_layers): op_to_select = tf.random.uniform([], maxval=len(available_ops), dtype=tf.int32) for(i, op_name)in enumerate(available_ops): image = tf.cond( tf.equal(i, op_to_select), lambda selected_func=op_name,: selected_func( image), lambda: image) return image, target<categorify>
optimizer = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0 )
Digit Recognizer
12,468,048
def preprocess(image, target_or_rec_id): image = tf.image.grayscale_to_rgb(image) image = tf.image.resize(image, [params.height,params.width]) image = tf.image.per_image_standardization(image) return image , target_or_rec_id def read_labeled_tfrecord(example_proto): sample = tf.io.parse_single_example(example_proto, feature_description) wav, _ = tf.audio.decode_wav(sample['wav'], desired_channels=1) target = tf.cast(sample['target'],tf.float32) target = tf.squeeze(tf.one_hot([target,], depth = params.num_classes), axis = 0) tmin = tf.cast(sample['tmin'], tf.float32) fmin = tf.cast(sample['fmin'], tf.float32) tmax = tf.cast(sample['tmax'], tf.float32) fmax = tf.cast(sample['fmax'], tf.float32) tmax_s = tmax * tf.cast(params.sample_rate, tf.float32) tmin_s = tmin * tf.cast(params.sample_rate, tf.float32) cut_s = tf.cast(CUT * params.sample_rate, tf.float32) all_s = tf.cast(60 * params.sample_rate, tf.float32) tsize_s = tmax_s - tmin_s cut_min = tf.cast( tf.maximum(0.0, tf.minimum(tmin_s -(cut_s - tsize_s)/ 2, tf.minimum(tmax_s +(cut_s - tsize_s)/ 2, all_s)- cut_s) ), tf.int32 ) cut_max = cut_min + CUT * params.sample_rate wav = tf.squeeze(wav[cut_min : cut_max]) return wav, target def read_unlabeled_tfrecord(example): feature_description = { 'recording_id': tf.io.FixedLenFeature([], tf.string), 'audio_wav': tf.io.FixedLenFeature([], tf.string), } sample = tf.io.parse_single_example(example, feature_description) wav, _ = tf.audio.decode_wav(sample['audio_wav'], desired_channels=1) recording_id = tf.reshape(tf.cast(sample['recording_id'] , tf.string), [1]) def _cut_audio(i): _sample = { 'audio_wav': tf.reshape(wav[i*params.sample_rate*TIME:(i+1)*params.sample_rate*TIME], [params.sample_rate*TIME]), 'recording_id': sample['recording_id'] } return _sample return tf.map_fn(_cut_audio, tf.range(60//TIME), dtype={ 'audio_wav': tf.float32, 'recording_id': tf.string } )<create_dataframe>
cnn.compile(optimizer = optimizer, loss ='categorical_crossentropy', metrics=['accuracy'] )
Digit Recognizer
12,468,048
def load_dataset(filenames, labeled = True, ordered = False , training = True): ignore_order = tf.data.Options() if not ordered: ignore_order.experimental_deterministic = False dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO) dataset = dataset.map(read_labeled_tfrecord , num_parallel_calls = AUTO) dataset = dataset.map(waveform_to_log_mel_spectrogram , num_parallel_calls = AUTO) dataset = dataset.map(preprocess, num_parallel_calls = AUTO) return dataset<prepare_x_and_y>
learning_rate_reduction = ReduceLROnPlateau(moniter = 'val_acc', patience = 3, verbose = 1, factor=0.5, min_lr = 0.00001 )
Digit Recognizer
12,468,048
def get_dataset(filenames, training = True): if training: dataset = load_dataset(filenames , training = True) dataset = dataset.shuffle(256 ).repeat() dataset = dataset.batch(GLOBAL_BATCH_SIZE, drop_remainder = True) else: dataset = load_dataset(filenames , training = False) dataset = dataset.repeat().batch(GLOBAL_BATCH_SIZE) dataset = dataset.prefetch(AUTO) return dataset<groupby>
epochs = 10 batch_size = 86
Digit Recognizer
12,468,048
@tf.function def _one_sample_positive_class_precisions(example): y_true, y_pred = example y_true = tf.reshape(y_true, tf.shape(y_pred)) retrieved_classes = tf.argsort(y_pred, direction='DESCENDING') class_rankings = tf.argsort(retrieved_classes) retrieved_class_true = tf.gather(y_true, retrieved_classes) retrieved_cumulative_hits = tf.math.cumsum(tf.cast(retrieved_class_true, tf.float32)) idx = tf.where(y_true)[:, 0] i = tf.boolean_mask(class_rankings, y_true) r = tf.gather(retrieved_cumulative_hits, i) c = 1 + tf.cast(i, tf.float32) precisions = r / c dense = tf.scatter_nd(idx[:, None], precisions, [y_pred.shape[0]]) return dense class LWLRAP(tf.keras.metrics.Metric): def __init__(self, num_classes, name='lwlrap'): super().__init__(name=name) self._precisions = self.add_weight( name='per_class_cumulative_precision', shape=[num_classes], initializer='zeros', ) self._counts = self.add_weight( name='per_class_cumulative_count', shape=[num_classes], initializer='zeros', ) def update_state(self, y_true, y_pred, sample_weight=None): precisions = tf.map_fn( fn=_one_sample_positive_class_precisions, elems=(y_true, y_pred), dtype=(tf.float32), ) increments = tf.cast(precisions > 0, tf.float32) total_increments = tf.reduce_sum(increments, axis=0) total_precisions = tf.reduce_sum(precisions, axis=0) self._precisions.assign_add(total_precisions) self._counts.assign_add(total_increments) def result(self): per_class_lwlrap = self._precisions / tf.maximum(self._counts, 1.0) per_class_weight = self._counts / tf.reduce_sum(self._counts) overall_lwlrap = tf.reduce_sum(per_class_lwlrap * per_class_weight) return overall_lwlrap def reset_states(self): self._precisions.assign(self._precisions * 0) self._counts.assign(self._counts * 0 )<normalization>
Digit Recognizer
12,468,048
learning_rate_base = LEARNING_RATE total_steps = STEPS_PER_EPOCH * EPOCHS warmup_learning_rate = WARMUP_LEARNING_RATE warmup_steps= WARMUP_EPOCHS * STEPS_PER_EPOCH @tf.function def cosine_decay_with_warmup(global_step, hold_base_rate_steps=0): if total_steps < warmup_steps: raise ValueError('total_steps must be larger or equal to ' 'warmup_steps.') learning_rate = 0.5 * learning_rate_base *(1 + tf.cos( np.pi * (tf.cast(global_step, tf.float32)- warmup_steps - hold_base_rate_steps )/ float(total_steps - warmup_steps - hold_base_rate_steps))) if hold_base_rate_steps > 0: learning_rate = tf.where( global_step > warmup_steps + hold_base_rate_steps, learning_rate, learning_rate_base) if warmup_steps > 0: if learning_rate_base < warmup_learning_rate: raise ValueError('learning_rate_base must be larger or equal to ' 'warmup_learning_rate.') slope =(learning_rate_base - warmup_learning_rate)/ warmup_steps warmup_rate = slope * tf.cast(global_step, tf.float32)+ warmup_learning_rate learning_rate = tf.where(global_step < warmup_steps, warmup_rate, learning_rate) return tf.where(global_step > total_steps, 0.0, learning_rate, name='learning_rate') rng = [i for i in range(int(EPOCHS * STEPS_PER_EPOCH)) ] WARMUP_STEPS = int(WARMUP_EPOCHS * STEPS_PER_EPOCH) y = [cosine_decay_with_warmup(x)for x in rng] sns.set(style='whitegrid') fig, ax = plt.subplots(figsize=(20, 6)) plt.plot(rng, y )<choose_model_class>
datagen = ImageDataGenerator(featurewise_center=False, samplewise_center=False, featurewise_std_normalization = False, samplewise_std_normalization = False, zca_whitening=False, rotation_range=10, zoom_range=0.1, width_shift_range = 0.1, height_shift_range = 0.1, horizontal_flip = False, vertical_flip = False) datagen.fit(X_train )
Digit Recognizer
12,468,048
class RFCX_MODEL(tf.keras.Model): def __init__(self): super(RFCX_MODEL , self ).__init__() self.gaussian_noise = GaussianNoise(0.05) self.resnet_model = ResNet50(include_top=False, weights='imagenet') self.model_output = GlobalAveragePooling2D() self.dropout = Dropout(params.dropout) self.predictions = Dense(params.num_classes, activation = params.classifier_activation) def call(self, inputs): noisy_input = self.gaussian_noise(inputs) resnet_output = self.resnet_model(noisy_input) x = self.model_output(resnet_output) x = self.dropout(x) x = self.predictions(x) return x<split>
history = cnn.fit_generator(datagen.flow(X_train,Y_train,batch_size=batch_size), epochs =epochs, validation_data =(X_val, Y_val), verbose=2, steps_per_epoch=X_train.shape[0]//batch_size, callbacks = [learning_rate_reduction] )
Digit Recognizer
12,468,048
def train_one_fold(train_dataset, valid_dataset): print('Start fine-tuning!', flush=True) train_dist_dataset = strategy.experimental_distribute_dataset(train_dataset) valid_dist_dataset = strategy.experimental_distribute_dataset(valid_dataset) start_time = epoch_start_time = time.time() print("Steps per epoch:", STEPS_PER_EPOCH) History = namedtuple('History', 'history') history = History(history={'train_loss': [], 'val_loss': [], 'train_lwlrap' : [], 'val_lwlrap' : []}) train_iterator = iter(train_dist_dataset) val_iterator = iter(valid_dist_dataset) steps = 0 best_val_lwlrap = 0 for epoch in range(EPOCHS): print(' EPOCH {:d}/{:d}'.format(epoch+1, EPOCHS)) train_multiple_steps(train_iterator , tf.convert_to_tensor(STEPS_PER_EPOCH)) steps += STEPS_PER_EPOCH if(steps // STEPS_PER_EPOCH)> epoch: val_steps = 0 val_multiple_steps(val_iterator, tf.convert_to_tensor(VAL_STEPS)) val_steps += VAL_STEPS history.history['train_loss'].append(train_loss.result().numpy() /(STEPS_PER_EPOCH)) history.history['val_loss'].append(( val_loss.result().numpy() / val_steps)) history.history['train_lwlrap'].append(train_lwlrap.result().numpy()) history.history['val_lwlrap'].append(val_lwlrap.result().numpy()) epoch_time = time.time() - epoch_start_time print('time: {:0.1f}s'.format(epoch_time), 'train_loss: {:0.4f}'.format(history.history['train_loss'][-1]), 'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]), 'train_lwlrap: {:0.4f}'.format(history.history['train_lwlrap'][-1]), 'val_lwlrap: {:0.4f}'.format(history.history['val_lwlrap'][-1]), 'lr : {:0.6f}'.format(cosine_decay_with_warmup(steps)) ) if history.history['val_lwlrap'][-1] >= best_val_lwlrap: best_val_lwlrap = history.history['val_lwlrap'][-1] model.save_weights(model_path) print(f'Saved model weights at "{model_path}"') patience_cnt = 1 else: patience_cnt += 1 if patience_cnt > PATIENCE: print(f'Epoch {epoch:05d}: early stopping') break epoch_start_time = time.time() train_loss.reset_states() val_loss.reset_states() train_lwlrap.reset_states() val_lwlrap.reset_states() history_list.append(history )<split>
results = cnn.predict(test) results = np.argmax(results,axis = 1) results = pd.Series(results,name="Label" )
Digit Recognizer
12,468,048
<create_dataframe><EOS>
submission = pd.concat([pd.Series(range(1,28001),name = "ImageId"),results],axis = 1) submission.to_csv("cnn_mnist_datagen.csv",index=False)
Digit Recognizer
12,607,235
<SOS> metric: categorizationaccuracy Kaggle data source: digit-recognizer<predict_on_test>
import numpy as np import pandas as pd
Digit Recognizer
12,607,235
test_predict = [] test_data = get_test_dataset(TEST_FILES, training = False) test_audio = test_data.map(lambda frames, recording_id: frames) for fold in range(N_FOLDS): model.load_weights(f'./RFCX_model_fold {fold}.h5') test_predict.append(model.predict(test_audio, verbose = 1))<load_from_csv>
print(tf.__version__ )
Digit Recognizer
12,607,235
SUB = pd.read_csv('.. /input/rfcx-species-audio-detection/sample_submission.csv') predict = np.array(test_predict ).reshape(N_FOLDS, len(SUB), 60 // TIME, params.num_classes) predict = np.mean(np.max(predict ,axis = 2), axis = 0) recording_id = test_data.map(lambda frames, recording_id: recording_id ).unbatch() test_ids = next(iter(recording_id.batch(len(SUB)* 60 // TIME)) ).numpy().astype('U' ).reshape(len(SUB), 60 // TIME) pred_df = pd.DataFrame({ 'recording_id' : test_ids[:, 0], **{f's{i}' : predict[:, i] for i in range(params.num_classes)} } )<save_to_csv>
try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) else: strategy = tf.distribute.get_strategy() print("REPLICAS: ", strategy.num_replicas_in_sync )
Digit Recognizer
12,607,235
pred_df.sort_values('recording_id', inplace = True) pred_df.to_csv('submission.csv', index = False )<import_modules>
EPOCHS = 75 DROP_RATE = 0.4 BATCH_SIZE = 16 * strategy.num_replicas_in_sync RESIZE_SIZE =(224, 224) TTA_COUNT = 10 MODEL_VERSION = 'V17'
Digit Recognizer
12,607,235
import pandas as pd, numpy as np import os<define_variables>
DATA_DIR = '.. /input/digit-recognizer/' def read_df(file_name): file_path = DATA_DIR + file_name data_df = pd.read_csv(file_path) return data_df
Digit Recognizer
12,607,235
paths = [ ".. /input/rfcx-best-performing-public-kernels/kkiller_inference-tpu-rfcx-audio-detection-fast_0861.csv", ".. /input/rfcx-best-performing-public-kernels/submission_khoongweihao_0845.csv", ] weights = np.array([0.6, 0.4]) sum(weights )<define_variables>
train_df = read_df('train.csv') train_df
Digit Recognizer
12,607,235
cols = [f"s{i}" for i in range(24)]<load_from_csv>
IMAGE_SIZE =(28, 28) IMAGE_SHAPE =(*IMAGE_SIZE, 1) def get_images_from(data_df): pixels_df = data_df.loc[ : , 'pixel0':'pixel783' ] pixels_array = pixels_df.to_numpy(dtype=np.uint8) images = pixels_array.reshape(-1, *IMAGE_SHAPE) return images
Digit Recognizer
12,607,235
scores = [] for path in paths: df = pd.read_csv(path ).sort_values("recording_id" ).reset_index(drop=True) score = np.empty(( len(df), 24)) o = df[cols].values.argsort(1) score[np.arange(len(df)) [:, None], o] = np.arange(24)[None] scores.append(score) scores = np.stack(scores) scores.shape<compute_test_metric>
def get_labels_from(data_df): labels = data_df['label'].to_numpy(dtype=np.int32) return labels
Digit Recognizer
12,607,235
sub_score = np.sum(scores*weights[:, None, None], 0) print(sub_score.shape) sub_score<prepare_output>
X = get_images_from(train_df) y = get_labels_from(train_df) print(X.shape) print(y.shape )
Digit Recognizer
12,607,235
sub = pd.DataFrame(sub_score, columns=cols) sub["recording_id"] = df["recording_id"] sub = sub[["recording_id"] + cols] print(sub.shape) sub.head()<save_to_csv>
RESIZE_SHAPE =(*RESIZE_SIZE, 1) def resize_image(orig_np): reshape_np = np.reshape(orig_np, IMAGE_SIZE) orig_im = Image.fromarray(reshape_np) resized_im = orig_im.resize(RESIZE_SIZE, Image.LANCZOS) resized_np = np.asarray(resized_im, dtype=np.uint8) resized_reshaped_np = np.reshape(resized_np, RESIZE_SHAPE) return resized_reshaped_np
Digit Recognizer
12,607,235
sub.to_csv("submission.csv", index=False )<import_modules>
def resize_images(orig_nps): n_images = orig_nps.shape[0] resized_shape =(n_images, *RESIZE_SHAPE) resized_nps = np.empty(resized_shape, dtype=np.uint8) for i in range(n_images): if i % 100 == 0: print('.', end='', flush=True) x_np = orig_nps[i] resized_nps[i] = resize_image(x_np) print() return resized_nps
Digit Recognizer
12,607,235
import numpy as np import pandas as pd import matplotlib.pyplot as plt import cv2 import keras import math<load_from_csv>
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = math.pi * rotation / 180. shear = math.pi * shear / 180. c1 = tf.math.cos(rotation) s1 = tf.math.sin(rotation) one = tf.constant([1],dtype='float32') zero = tf.constant([0],dtype='float32') rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3]) c2 = tf.math.cos(shear) s2 = tf.math.sin(shear) shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3]) zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3]) shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3]) return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))
Digit Recognizer
12,607,235
test = pd.read_csv('.. /input/quickdraw-doodle-recognition/test_simplified.csv') print(test.shape) test.head()<categorify>
def do_transform(image,label): DIM = RESIZE_SIZE[0] XDIM = DIM%2 rot = 10.* tf.random.normal([1],dtype='float32') shr = 5.* tf.random.normal([1],dtype='float32') h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10. w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10. h_shift = DIM * 0.05 * tf.random.normal([1],dtype='float32') w_shift = DIM * 0.05 * tf.random.normal([1],dtype='float32') m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM) y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM]) z = tf.ones([DIM*DIM],dtype='int32') idx = tf.stack([x,y,z]) idx2 = K.dot(m,tf.cast(idx,dtype='float32')) idx2 = K.cast(idx2,dtype='int32') idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2) idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]]) d = tf.gather_nd(image,tf.transpose(idx3)) return tf.reshape(d,[DIM,DIM,1]),label
Digit Recognizer
12,607,235
def img_to_np(img_str, ht, wt, lw, pad): strokes = eval(img_str) ht_ = ht - 2*pad wt_ = wt - 2*pad img = np.zeros(( ht, wt), np.uint8) for s in strokes: sx =(np.array(s[0])* wt_ / 256 ).round().astype('int')+ pad sy =(np.array(s[1])* ht_ / 256 ).round().astype('int')+ pad for i in range(len(sx)- 1): p1 =(sx[i], sy[i]) p2 =(sx[i+1], sy[i+1]) img = cv2.line(img, p1, p2,(255, 0, 0), lw, lineType=cv2.LINE_AA) return img <define_variables>
def randints(shape, minval, maxval): return tf.random.uniform( shape=shape, minval=minval, maxval=maxval+1, dtype=tf.int32 )
Digit Recognizer
12,607,235
test_imgs = np.zeros(shape =(test.shape[0], 64, 64, 1))<feature_engineering>
def make_range_mask(size, start, end): indice = tf.range(size, dtype=tf.int32) start_mask =(start <= indice) end_mask =(indice <= end) range_mask = start_mask & end_mask return range_mask def make_region_mask(image_height, image_width, top, left, bottom, right): row_mask = make_range_mask(image_height, top, bottom) col_mask = make_range_mask(image_width, left, right) region_mask = row_mask[..., tf.newaxis] & col_mask[ tf.newaxis,...] reshaped_region_mask = region_mask[..., tf.newaxis] return reshaped_region_mask
Digit Recognizer
12,607,235
%%time for i, row in test.iterrows() : test_imgs[i,:,:,0] = img_to_np(row.drawing, 64, 64, 1, 2)/ 255 <predict_on_test>
def do_cutout(orig_image, label): mask_ratio = 0.5 image_shape = tf.shape(orig_image) image_height = image_shape[0] image_width = image_shape[1] mask_h = tf.cast(tf.cast(image_height, tf.float32)* mask_ratio, tf.int32) mask_w = tf.cast(tf.cast(image_width, tf.float32)* mask_ratio, tf.int32) mask_value = 0.0 top = randints([], -mask_h // 2, image_height - mask_h // 2) left = randints([], -mask_w // 2, image_width - mask_w // 2) bottom = top + mask_h right = left + mask_w cut_region = make_region_mask( image_height, image_width, top, left, bottom, right) cutout_image = tf.where(cut_region, mask_value, orig_image) return cutout_image, label
Digit Recognizer
12,607,235
%%time probs = cnn.predict(test_imgs) print(probs.shape )<concatenate>
unique_y = np.unique(y) label_count = len(unique_y) print(unique_y) print(label_count )
Digit Recognizer
12,607,235
N_train = probs.shape[0] top_3_probs = np.zeros(shape=(N_train, 3)) for i in range(N_train): p = probs[i, :] top_classes = np.argpartition(p, -3)[-3:] top_classes = top_classes[np.argsort(p[top_classes])] top_classes = np.flip(top_classes) top_probs = p[top_classes] top_3_probs[i,:] = top_probs print(top_3_probs[:10, :].round(2)) print(top_3_probs.shape) plt.figure(figsize=[10,6]) for i in range(3): plt.subplot(3,1,i+1) plt.hist(top_3_probs[:,i], color='orchid', edgecolor='k', bins = np.arange(0, 1.01, 0.025)) plt.yscale('log') plt.show()<sort_values>
AUTO = tf.data.experimental.AUTOTUNE def make_dataset( X_np, y_np, transform=False, cutout=False, repeat=False, shuffle=False): def _cast_to_float(x, y): return tf.cast(x, tf.float32), y ds = tf.data.Dataset.from_tensor_slices(( X_np, y_np)) ds = ds.map(_cast_to_float, num_parallel_calls=AUTO) if shuffle: ds = ds.shuffle(2048) if transform: ds = ds.map(do_transform, num_parallel_calls=AUTO) if cutout: ds = ds.map(do_cutout, num_parallel_calls=AUTO) ds = ds.batch(BATCH_SIZE) if repeat: ds = ds.repeat() return ds
Digit Recognizer
12,607,235
N_train = probs.shape[0] predictions = [] t = 0.35 for i in range(N_train): p = probs[i, :] top_classes = np.argpartition(p, -3)[-3:] top_classes = top_classes[np.argsort(p[top_classes])] top_classes = np.flip(top_classes) top_probs = p[top_classes] sel = top_probs > t sel[0] = True predictions.append(top_classes[sel]) print(len(predictions))<load_from_csv>
def make_train_ds(X_np, y_np): ds = make_dataset( X_np, y_np, transform=True, cutout=True, repeat=True, shuffle=True) return ds def make_val_ds(X_np, y_np): ds = make_dataset( X_np, y_np, transform=False, cutout=False, repeat=False, shuffle=False) return ds def make_test_ds(X_np): y_np = np.zeros(X_np.shape[0], dtype=np.int32) ds = make_dataset( X_np, y_np, transform=True, cutout=False, repeat=False, shuffle=False) return ds
Digit Recognizer
12,607,235
submission = pd.read_csv('.. /input/quickdraw-doodle-recognition/sample_submission.csv') submission.head()<load_from_csv>
NFOLD = 5 k_fold = StratifiedKFold(n_splits=NFOLD) fold_index_list = [] for train_index, val_index in k_fold.split(X_resized, y): fold_index_list.append(( train_index, val_index)) def get_fold(fold_i): train_index, val_index = fold_index_list[fold_i] X_train, y_train = X_resized[train_index], y[train_index] X_val, y_val = X_resized[val_index], y[val_index] train_ds = make_train_ds(X_train, y_train) val_ds = make_val_ds(X_val, y_val) return train_ds, val_ds
Digit Recognizer
12,607,235
label_lookup_df = pd.read_csv('.. /input/models-and-submissions/Quick Draw Models/label_lookup.csv') label_lookup = {k:v for k,v in zip(label_lookup_df.index.values, label_lookup_df.label.values)} label_lookup[0]<feature_engineering>
def calc_steps_per_epoch(fold_i): train_index, val_index = fold_index_list[fold_i] steps_per_epoch =(len(train_index)+ BATCH_SIZE - 1)// BATCH_SIZE return steps_per_epoch
Digit Recognizer
12,607,235
%%time for i in range(N_train): classes = predictions[i] words_list = [label_lookup[c] for c in classes] words_string = ' '.join(words_list) submission.loc[i, 'word'] = words_string submission.head()<save_to_csv>
MODEL_INPUT_SHAPE =(*RESIZE_SIZE, 3) def make_model(name): with strategy.scope() : inputs = L.Input(shape=RESIZE_SHAPE, name="input") scaled = L.Lambda(lambda v: v / 255.0, name='scaling' )(inputs) img_input = L.Concatenate(name='concat' )([scaled, scaled, scaled]) x = ResNet50( include_top=False, weights='imagenet', input_shape=MODEL_INPUT_SHAPE, pooling='avg' )(img_input) x = L.Dropout(DROP_RATE, name="dropout" )(x) outputs = L.Dense(label_count, activation='sigmoid', name='classify' )(x) model = M.Model(inputs=inputs, outputs=outputs, name=name) model.compile( optimizer='adam', loss="sparse_categorical_crossentropy", metrics=['accuracy']) return model
Digit Recognizer
12,607,235
submission.to_csv('submission.csv', index=False )<save_to_csv>
LR_START = 0.00001 LR_MAX = 0.00005 * strategy.num_replicas_in_sync LR_MIN = 0.00001 LR_RAMPUP_EPOCHS = min(5, EPOCHS // 5) LR_SUSTAIN_EPOCHS = 0 def lrfn(epoch): if epoch < LR_RAMPUP_EPOCHS: lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS: lr = LR_MAX else: decay_total_epochs = EPOCHS - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS decay_epoch_index = epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS phase = math.pi * decay_epoch_index / decay_total_epochs cosine_decay = 0.5 *(1 + math.cos(phase)) lr =(LR_MAX - LR_MIN)* cosine_decay + LR_MIN return lr def make_lr_callback() : lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = False) return lr_callback rng = [i for i in range(EPOCHS)] lr_y = [lrfn(x)for x in rng] plt.figure(figsize=(10, 4)) plt.plot(rng, lr_y) print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".\ format(lr_y[0], max(lr_y), lr_y[-1]))
Digit Recognizer
12,607,235
submission.to_csv('submission.csv', index=False )<load_pretrained>
def make_best_model_file_path(fold_i): file_name = "best_model_{0}_{1}.hdf5".format(MODEL_VERSION, fold_i) return file_name
Digit Recognizer
12,607,235
pd.set_option('display.max_columns', 100) pd.set_option('display.max_rows', 100) DATA_PATH = '.. /input/jane-street-market-prediction/' NFOLDS = 5 TRAIN = False CACHE_PATH = '.. /input/mlp012003weights' def save_pickle(dic, save_path): with open(save_path, 'wb')as f: pickle.dump(dic, f) def load_pickle(load_path): with open(load_path, 'rb')as f: message_dict = pickle.load(f) return message_dict feat_cols = [f'feature_{i}' for i in range(130)] target_cols = ['action', 'action_1', 'action_2', 'action_3', 'action_4'] f_mean = np.load(f'{CACHE_PATH}/f_mean_online.npy') all_feat_cols = [col for col in feat_cols] all_feat_cols.extend(['cross_41_42_43', 'cross_1_2']) class Model(nn.Module): def __init__(self): super(Model, self ).__init__() self.batch_norm0 = nn.BatchNorm1d(len(all_feat_cols)) self.dropout0 = nn.Dropout(0.2) dropout_rate = 0.2 hidden_size = 256 self.dense1 = nn.Linear(len(all_feat_cols), hidden_size) self.batch_norm1 = nn.BatchNorm1d(hidden_size) self.dropout1 = nn.Dropout(dropout_rate) self.dense2 = nn.Linear(hidden_size+len(all_feat_cols), hidden_size) self.batch_norm2 = nn.BatchNorm1d(hidden_size) self.dropout2 = nn.Dropout(dropout_rate) self.dense3 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm3 = nn.BatchNorm1d(hidden_size) self.dropout3 = nn.Dropout(dropout_rate) self.dense4 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm4 = nn.BatchNorm1d(hidden_size) self.dropout4 = nn.Dropout(dropout_rate) self.dense5 = nn.Linear(hidden_size+hidden_size, len(target_cols)) self.Relu = nn.ReLU(inplace=True) self.PReLU = nn.PReLU() self.LeakyReLU = nn.LeakyReLU(negative_slope=0.01, inplace=True) self.RReLU = nn.RReLU() def forward(self, x): x = self.batch_norm0(x) x = self.dropout0(x) x1 = self.dense1(x) x1 = self.batch_norm1(x1) x1 = self.LeakyReLU(x1) x1 = self.dropout1(x1) x = torch.cat([x, x1], 1) x2 = self.dense2(x) x2 = self.batch_norm2(x2) x2 = self.LeakyReLU(x2) x2 = self.dropout2(x2) x = torch.cat([x1, x2], 1) x3 = self.dense3(x) x3 = self.batch_norm3(x3) x3 = self.LeakyReLU(x3) x3 = self.dropout3(x3) x = torch.cat([x2, x3], 1) x4 = self.dense4(x) x4 = self.batch_norm4(x4) x4 = self.LeakyReLU(x4) x4 = self.dropout4(x4) x = torch.cat([x3, x4], 1) x = self.dense5(x) return x if True: device = torch.device("cuda:0") model_list = [] tmp = np.zeros(len(feat_cols)) for _fold in range(NFOLDS): torch.cuda.empty_cache() model = Model() model.to(device) model_weights = f"{CACHE_PATH}/online_model{_fold}.pth" model.load_state_dict(torch.load(model_weights)) model.eval() model_list.append(model) <choose_model_class>
def make_model_check_point(fold_i): best_model_file_path = make_best_model_file_path(fold_i) return ModelCheckpoint( best_model_file_path, monitor='val_accuracy', mode='max', verbose=0, save_best_only=True, save_weights_only=False, period=1 )
Digit Recognizer
12,607,235
SEED = 1111 np.random.seed(SEED) def create_mlp( num_columns, num_labels, hidden_units, dropout_rates, label_smoothing, learning_rate ): inp = tf.keras.layers.Input(shape=(num_columns,)) x = tf.keras.layers.BatchNormalization()(inp) x = tf.keras.layers.Dropout(dropout_rates[0] )(x) for i in range(len(hidden_units)) : x = tf.keras.layers.Dense(hidden_units[i] )(x) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation(tf.keras.activations.swish )(x) x = tf.keras.layers.Dropout(dropout_rates[i + 1] )(x) x = tf.keras.layers.Dense(num_labels )(x) out = tf.keras.layers.Activation("sigmoid" )(x) model = tf.keras.models.Model(inputs=inp, outputs=out) model.compile( optimizer=tfa.optimizers.RectifiedAdam(learning_rate=learning_rate), loss=tf.keras.losses.BinaryCrossentropy(label_smoothing=label_smoothing), metrics=tf.keras.metrics.AUC(name="AUC"), ) return model epochs = 200 batch_size = 4096 hidden_units = [160, 160, 160] dropout_rates = [0.2, 0.2, 0.2, 0.2] label_smoothing = 1e-2 learning_rate = 1e-3 tf.keras.backend.clear_session() tf.random.set_seed(SEED) clf = create_mlp( len(feat_cols), 5, hidden_units, dropout_rates, label_smoothing, learning_rate ) clf.load_weights('.. /input/jane-street-with-keras-nn-overfit/model.h5') tf_models = [clf]<statistical_test>
initial_weights_file_path = "initial_weights.hdf5" model.save_weights(initial_weights_file_path )
Digit Recognizer
12,607,235
if True: env = janestreet.make_env() env_iter = env.iter_test() for(test_df, pred_df)in tqdm(env_iter): if test_df['weight'].item() > 0: x_tt = test_df.loc[:, feat_cols].values if np.isnan(x_tt.sum()): x_tt = np.nan_to_num(x_tt)+ np.isnan(x_tt)* f_mean cross_41_42_43 = x_tt[:, 41] + x_tt[:, 42] + x_tt[:, 43] cross_1_2 = x_tt[:, 1] /(x_tt[:, 2] + 1e-5) feature_inp = np.concatenate(( x_tt, np.array(cross_41_42_43 ).reshape(x_tt.shape[0], 1), np.array(cross_1_2 ).reshape(x_tt.shape[0], 1), ), axis=1) torch_pred = np.zeros(( 1, len(target_cols))) for model in model_list: torch_pred += model(torch.tensor(feature_inp, dtype=torch.float ).to(device)).sigmoid().detach().cpu().numpy() / NFOLDS torch_pred = np.median(torch_pred) tf_pred = np.median(np.mean([model(x_tt, training = False ).numpy() for model in tf_models],axis=0)) pred = torch_pred * 0.5 + tf_pred * 0.5 pred_df.action = np.where(pred >= 0.5, 1, 0 ).astype(int) else: pred_df.action = 0 env.predict(pred_df )<import_modules>
history_list = [] for fold_i in range(NFOLD): print(" print(" train_ds, val_ds = get_fold(fold_i) steps_per_epoch = calc_steps_per_epoch(fold_i) lr_callback = make_lr_callback() check_point = make_model_check_point(fold_i) model.load_weights(initial_weights_file_path) history = model.fit( train_ds, epochs=EPOCHS, steps_per_epoch=steps_per_epoch, validation_data=val_ds, callbacks=[lr_callback, check_point], verbose=0) history_list.append(history) best_acc = max(history.history['accuracy']) best_val_acc = max(history.history['val_accuracy']) print( "Fold {0}: accuracy={1:.5f}, val_accuracy={2:.5f}".format( fold_i, best_acc, best_val_acc))
Digit Recognizer
12,607,235
import pandas as pd import gc from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import StratifiedKFold<load_from_csv>
test_df = read_df('test.csv') test_df
Digit Recognizer
12,607,235
train = pd.read_csv('/kaggle/input/jane-street-market-prediction/train.csv') train = reduce_mem_usage(train) features = [c for c in train.columns if 'feature' in c] train = train.astype({c: np.float32 for c in train.select_dtypes(include='float16' ).columns}) train = train.fillna(train.mean()) f_mean = np.mean(train[features[1:]].values,axis=0) train = train.query('date > 85' ).reset_index(drop = True) train = train[train.weight != 0]<prepare_x_and_y>
def make_val_pred_file_path(fold_i): file_name = "val_pred_{0}_{1}".format(MODEL_VERSION, fold_i) return file_name
Digit Recognizer