Kaggle competition: Quora Insincere Questions Classification
<SOS> metric: FScore_1 Kaggle data source: quora-insincere-questions-classification<categorify>
tqdm.pandas(desc='Progress')
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels = 3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'class': tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'id': tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled = True, ordered = False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_saturation(image, 0, 2)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled = True)
 dataset = dataset.map(data_augment, num_parallel_calls = AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered = False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered = False):
dataset = load_dataset(TEST_FILENAMES, labeled = False, ordered = ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<define_variables>
EMBEDDINGS_PATH = '.. /input/embeddings/'
EMBEDDING_FILE_GLOVE = f'{EMBEDDINGS_PATH}/glove.840B.300d/glove.840B.300d.txt'
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset)
<create_dataframe>
embed_size = 300
max_features = 120000
maxlen = 50
batch_size = 1024
n_epochs = 2
SEED = 1006
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset)
<choose_model_class>
def seed_everything(seed=SEED):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
seed_everything()
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, restore_best_weights = True )<choose_model_class>
os.environ['OMP_NUM_THREADS'] = '4'
def create_VGG16_model() :
pretrained_model = tf.keras.applications.VGG16(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
df_train = pd.read_csv(".. /input/train.csv")
 df_test = pd.read_csv(".. /input/test.csv" )
def create_Xception_model() :
pretrained_model = tf.keras.applications.Xception(include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
np.random.seed(SEED)
 trn_idx = np.random.permutation(len(df_train))
df_train = df_train.iloc[trn_idx]
df = pd.concat([df_train ,df_test],sort=True )
def create_DenseNet_model() :
pretrained_model = tf.keras.applications.DenseNet201(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '
'·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…',
'“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─',
'▒', '：', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞',
'∙', '）', '↓', '、', '│', '（', '»', '，', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ]
def clean_text(x):
x = str(x)
 for punct in puncts:
x = x.replace(punct, f' {punct} ')
 return x
df_train["question_text"] = df_train["question_text"].progress_apply(lambda x: clean_text(x))
df_test["question_text"] = df_test["question_text"].apply(lambda x: clean_text(x))
def create_EfficientNet_model() :
pretrained_model = efficientnet.EfficientNetB7(weights = 'noisy-student', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
def clean_numbers(x):
x = re.sub('[0-9]{5,}', '
x = re.sub('[0-9]{4}', '
x = re.sub('[0-9]{3}', '
x = re.sub('[0-9]{2}', '
return x
df_train["question_text"] = df_train["question_text"].progress_apply(lambda x: clean_numbers(x))
df_test["question_text"] = df_test["question_text"].apply(lambda x: clean_numbers(x))
def create_InceptionV3_model() :
pretrained_model = tf.keras.applications.InceptionV3(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
specials = {'\u200b': ' ', '…': '...', '\ufeff': '', 'करना': '', 'है': ''}
def clean_special_chars(text):
for s in specials:
text = text.replace(s, specials[s])
 return text
df_train["question_text"] = df_train["question_text"].progress_apply(lambda x: clean_special_chars(x))
df_test["question_text"] = df_test["question_text"].apply(lambda x: clean_special_chars(x))
def create_ResNet152_model() :
pretrained_model = tf.keras.applications.ResNet152V2(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
df_train["question_text"] = df_train["question_text"].apply(lambda x: x.lower())
 df_test["question_text"] = df_test["question_text"].apply(lambda x: x.lower() )
def create_MobileNetV2_model() :
pretrained_model = tf.keras.applications.MobileNetV2(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
list_sentences_train = df_train['question_text']
list_sentences_test = df_test['question_text']
list_sentences_combined = list_sentences_train.append(list_sentences_test, ignore_index=True)
 tokenizer = Tokenizer(num_words=max_features, filters='\t
')
 tokenizer.fit_on_texts(list(list_sentences_combined))
list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)
 list_tokenized_test = tokenizer.texts_to_sequences(list_sentences_test )
def create_InceptionResNetV2_model() :
pretrained_model = tf.keras.applications.InceptionResNetV2(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<define_variables>
train_x = pad_sequences(list_tokenized_train, maxlen=maxlen)
 test_x = pad_sequences(list_tokenized_test, maxlen=maxlen)
 train_y = df_train['target'].values
no_of_models = 1
models = [0] * no_of_models
start_model = 0
end_model = 1
model_indx_0 = start_model
val_probabilities = [0] * no_of_models
test_probabilities = [0] * no_of_models
all_probabilities = [0] * no_of_models<choose_model_class>
start = time.time()
def get_coefs(word, *arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.rstrip().rsplit(' ')) for o in open(EMBEDDING_FILE_GLOVE))
end = time.time()
print(end-start )
with strategy.scope() :
for j in range(no_of_models):
models[j] = create_EfficientNet_model()
models[0].summary()<load_pretrained>
all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
emb_mean,emb_std
def write_history(j):
history_dict = [0] * no_of_models
for i in range(j + 1):
if(historys[i] != 0):
history_dict[i] = historys[i].history
filename = './' + this_run_file_prefix + 'model_history_' + str(j)+ '.pkl'
pklfile = open(filename, 'ab')
 pickle.dump(history_dict, pklfile)
 pklfile.close()<define_search_space>
word_index = tokenizer.word_index
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in word_index.items() :
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
EPOCHS = 50
historys = [0] * no_of_models
finished_models = 0
for j in range(start_model, end_model):
start_training = datetime.now()
print(start_training)
 time_from_start_program_tdelta = start_training - start_time
if time_from_start_program_tdelta > end_training_by_tdelta:
print(j, 'time limit for doing training over, get out')
 break
print('LR_EXP_DECAY:', LR_EXP_DECAY, '.LR_MAX:', LR_MAX)
 historys[j] = models[j].fit(get_training_dataset() , steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, validation_data = get_validation_dataset() , callbacks = [lr_callback, early_stop])
 write_history(j)
 filename = this_run_file_prefix + 'models_' + str(j)+ '.h5'
models[j].save(filename)
 gc.collect()
finished_models = j + 1
print(datetime.now())
<categorify>
seed_everything()
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp)
 x = Bidirectional(LSTM(50, return_sequences=True, dropout=0.1, recurrent_dropout=0.1))(x)
 x = GlobalMaxPool1D()(x)
 x = Dense(50, activation="relu" )(x)
 x = Dropout(0.1 )(x)
 x = Dense(1, activation="sigmoid" )(x)
 model = Model(inputs=inp, outputs=x)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'] )
cmdataset = get_validation_dataset(ordered = True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()<categorify>
def train_validate_test_split(df, df_y, train_percent=.6, validate_percent=.2, random_state=10):
np.random.seed(random_state)
 perm = np.random.permutation(len(df))
m = len(df)
 train_end = int(train_percent * m)
 validate_end = int(validate_percent * m)+ train_end
train = df[perm[:train_end]]
validate = df[perm[train_end:validate_end]]
test = df[perm[validate_end:]]
train_y = df_y[perm[:train_end]]
validate_y = df_y[perm[train_end:validate_end]]
test_y = df_y[perm[validate_end:]]
return train, validate, test, train_y, validate_y, test_y, perm
test_ds = get_test_dataset(ordered = True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
<define_variables>
seed_everything()
X_tra, X_val, X_test, y_tra, y_val, y_test, permutation = train_validate_test_split(train_x, train_y,
train_percent=0.95, validate_percent=0.04, random_state=SEED+2 )
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset)
 images, labels = next(batch )<predict_on_test>
seed_everything()
model.fit(X_tra, y_tra, batch_size=batch_size, epochs=n_epochs, validation_data=(X_val, y_val)) ;
print(datetime.now())
 for j in range(start_model, end_model):
val_probabilities[j] = models[j].predict(images_ds)
 test_probabilities[j] = models[j].predict(test_images_ds)
 all_probabilities[j] = models[j].predict(images)
 print(datetime.now())
<find_best_params>
train_preds = model.predict(X_tra, batch_size=1024)
 print(len(train_preds))
for j in range(start_model, finished_models):
display_training_curves(historys[j].history['loss'], historys[j].history['val_loss'], 'loss', 211)
 display_training_curves(historys[j].history['sparse_categorical_accuracy'], historys[j].history['val_sparse_categorical_accuracy'], 'accuracy', 212)
 for j in range(start_model, finished_models):
print('model number:', j, ', Train Accuracy:', max(historys[j].history['sparse_categorical_accuracy']), ', Validation Accuracy:', max(historys[j].history['val_sparse_categorical_accuracy']))
for j in range(start_model, finished_models):
print('model number:', j, ', Train Loss:', min(historys[j].history['loss']), ', Validation Loss:', min(historys[j].history['val_loss'])) 
<define_variables>
def bestThresshold(train_y,train_preds):
tmp = [0,0,0]
delta = 0
for tmp[0] in tqdm(np.arange(0.1, 0.501, 0.01)) :
tmp[1] = f1_score(train_y, np.array(train_preds)>tmp[0])
 if tmp[1] > tmp[2]:
delta = tmp[0]
tmp[2] = tmp[1]
print('best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, tmp[2]))
return delta
delta = bestThresshold(y_tra,train_preds )
cm_probabilities = np.zeros(( val_probabilities[0].shape))
for j in range(no_of_models):
cm_probabilities = cm_probabilities + val_probabilities[j]
cm_predictions = np.argmax(cm_probabilities, axis = -1)
 print('Correct labels: ', cm_correct_labels.shape, cm_correct_labels)
 print('Predicted labels: ', cm_predictions.shape, cm_predictions )<compute_train_metric>
val_preds = model.predict(X_val, batch_size=1024)
 print(len(val_preds))
print(f1_score(y_val, np.array(val_preds)>delta))
def getFitPrecisionRecall(correct_labels, predictions):
score = f1_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 precision = precision_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 recall = recall_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 return score, precision, recall 
<compute_test_metric>
test_preds = model.predict(X_test, batch_size=1024)
 print(len(test_preds))
print(f1_score(y_test, np.array(test_preds)>delta))
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels = range(len(CLASSES)))
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, cm_predictions)
 cmat =(cmat.T / cmat.sum(axis = -1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<define_variables>
final_preds = model.predict(test_x, batch_size=1024 )
def create_submission_file(filename, probabilities):
predictions = np.argmax(probabilities, axis = -1)
 print('Generating submission file...', filename)
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt(filename, np.rec.fromarrays([test_ids, predictions]), fmt = ['%s', '%d'], delimiter = ',', header = 'id,label', comments = '')
<define_variables>
submission = df_test[['qid']].copy()
submission['prediction'] =(final_preds > delta ).astype(int)
 submission.to_csv('submission.csv', index=False )
probabilities = np.zeros(( test_probabilities[0].shape))
for j in range(no_of_models):
probabilities = probabilities + test_probabilities[j]
filename = this_run_file_prefix + 'submission.csv'
create_submission_file(filename, probabilities)
 create_submission_file('submission.csv', probabilities)
<find_best_params>
predicted = pd.DataFrame(train_preds)
 predicted.columns = ['predicted']
predicted.to_csv('train_preds.csv', index=False )
def combine_two(correct_labels, probability_0, probability_1):
print('Start.', datetime.now())
 alphas0_to_try = np.linspace(0, 1, 101)
 best_score = -1
best_alpha0 = -1
best_alpha1 = -1
best_precision = -1
best_recall = -1
best_val_predictions = None
for alpha0 in alphas0_to_try:
alpha1 = 1.0 - alpha0
probabilities = alpha0 * probability_0 + alpha1 * probability_1
predictions = np.argmax(probabilities, axis = -1)
 score, precision, recall = getFitPrecisionRecall(correct_labels, predictions)
 if score > best_score:
best_alpha0 = alpha0
best_alpha1 = alpha1
best_score = score
best_precision = precision
best_recall = recall
best_val_predictions = predictions
return best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall<define_search_space>
df_train_preproc = df_train
df_train_preproc.to_csv('df_train_preprocessed.csv' )
def combine_three(correct_labels, probability_0, probability_1, probability_2):
print('Start.', datetime.now())
 alphas0_to_try = np.linspace(0, 1, 101)
 alphas1_to_try = np.linspace(0, 1, 101)
 best_score = -1
best_alpha0 = -1
best_alpha1 = -1
best_alpha2 = -1
best_precision = -1
best_recall = -1
best_val_predictions = None
for alpha0 in alphas0_to_try:
for alpha1 in alphas1_to_try:
if(alpha0 + alpha1)> 1.0:
break
alpha2 = 1.0 - alpha0 - alpha1
probabilities = alpha0 * probability_0 + alpha1 * probability_1 + alpha2 * probability_2
predictions = np.argmax(probabilities, axis = -1)
 score, precision, recall = getFitPrecisionRecall(correct_labels, predictions)
 if score > best_score:
best_alpha0 = alpha0
best_alpha1 = alpha1
best_alpha2 = alpha2
best_score = score
best_precision = precision
best_recall = recall
best_val_predictions = predictions
return best_alpha0, best_alpha1, best_alpha2, best_val_predictions, best_score, best_precision, best_recall<train_model>
df_train = pd.read_csv(".. /input/train.csv")
 df_train_preproc = pd.read_csv("df_train_preprocessed.csv")
 train_preds = pd.read_csv('train_preds.csv' )
def get_best_combination(no_models, cm_correct_labels, val_probabilities, test_probabilities):
best_fit_score = -10000.0
best_predictions = 0
choose_filename = ''
curr_predictions = np.argmax(val_probabilities[0], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_0.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[0])
 create_submission_file(filename, test_probabilities[0])
 if no_models > 1:
curr_predictions = np.argmax(val_probabilities[1], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_1.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[1])
 create_submission_file(filename, test_probabilities[1])
 if no_models > 2:
curr_predictions = np.argmax(val_probabilities[2], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_2.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[2])
 create_submission_file(filename, test_probabilities[2])
 if no_models > 1:
best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[0], val_probabilities[1])
 print('For indx', [0, 1], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[1]
filename = this_run_file_prefix + 'submission_01.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 if no_models > 2:
best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[0], val_probabilities[2])
 print('For indx', [0, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_02.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[1], val_probabilities[2])
 print('For indx', [1, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[1] + best_alpha1 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_12.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 best_alpha0, best_alpha1, best_alpha2, best_val_predictions, best_score, best_precision, best_recall = combine_three(cm_correct_labels, val_probabilities[0], val_probabilities[1], val_probabilities[2])
 print('For indx', [0, 1, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, 'best_alpha2:', best_alpha2, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[1] + best_alpha2 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_012.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 cmat = confusion_matrix(cm_correct_labels, best_predictions, labels = range(len(CLASSES)))
 cmat =(cmat.T / cmat.sum(axis = -1)).T
display_confusion_matrix(cmat, best_fit_score, precision, recall)
 print('Best score from all combination was', best_fit_score, '.For submission file used is', choose_filename)
 return best_predictions 
<categorify>
y_train = y_tra; y_train[0:10]
best_predictions = cm_predictions
if no_of_models > 1:
bp = get_best_combination(no_of_models, cm_correct_labels, val_probabilities, test_probabilities)
 best_predictions = bp 
<define_variables>
combined = pd.concat([df_train, train_preds], axis=1, sort=False)
 combined.head()
probabilities = np.zeros(( all_probabilities[0].shape))
for j in range(no_of_models):
probabilities = probabilities + all_probabilities[j]
predictions = np.argmax(probabilities, axis =-1)
 display_batch_of_images(( images, labels), predictions )<load_pretrained>
combined['error'] = abs(combined['target'] - combined['predicted'])
 combined.head()
val_probs = [cm_correct_labels, cm_predictions, test_ids, val_probabilities[0], test_probabilities[model_indx_0]]
filename = this_run_file_prefix + 'tests_vals_0.pkl'
pklfile = open(filename, 'ab')
 pickle.dump(val_probs, pklfile)
 pklfile.close()<categorify>
pd.set_option('display.max_colwidth', -1 )
use_correct_labels = cm_correct_labels
use_val_predictions = best_predictions<define_variables>
sorted = combined.sort_values(by=['error'], ascending=False )
correct_labels_cnt = 0
incorrect_labels_cnt = 0
correct_labels = []
incorrect_labels = []
vals_actual_true = {}
vals_tp = {}
vals_fn = {}
vals_fp = {}
for i in range(len(CLASSES)) :
vals_actual_true[i] = 0
vals_tp[i] = 0
vals_fn[i] = 0
vals_fp[i] = 0
for i in range(len(use_correct_labels)) :
correct_label = use_correct_labels[i]
predict_label = use_val_predictions[i]
vals_actual_true[correct_label] = vals_actual_true[correct_label] + 1
if use_val_predictions[i] != use_correct_labels[i]:
incorrect_labels_cnt = incorrect_labels_cnt + 1
incorrect_labels.append(i)
 vals_fn[correct_label] = vals_fn[correct_label] + 1
vals_fp[predict_label] = vals_fp[predict_label] + 1
else:
correct_labels_cnt = correct_labels_cnt + 1
correct_labels.append(i)
 vals_tp[correct_label] = vals_tp[correct_label] + 1
print('Number of correct_labels is {}, incorrect_labels is {}'.format(correct_labels_cnt, incorrect_labels_cnt))
print('Incorrect labels', incorrect_labels)
<define_variables>
pd.options.display.float_format = "{:.8f}".format
def display_my_batch_of_images(databatch, rows = 0, cols = 0, predictions=None):

 images, labels = databatch
if labels is None:
labels = [None for _ in enumerate(images)]
if rows == 0 or cols == 0:
rows = int(math.sqrt(len(images)))
 cols =(len(images)+ rows - 1)//rows
print('Total number of images is {}, rows is {}, cols is {}'.format(len(images), rows, cols))
FIGSIZE = 20.0
SPACING = 0.1
subplot=(rows,cols,1)
 if rows < cols:
plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))
else:
plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))
for i,(image, label)in enumerate(zip(images[:rows*cols], labels[:rows*cols])) :
title = '' if label is None else CLASSES[label]
correct = True
if predictions is not None:
title, correct = title_from_label_and_target(predictions[i], label)
 dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3
subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)
 plt.tight_layout()
if label is None and predictions is None:
plt.subplots_adjust(wspace=0, hspace=0)
 else:
plt.subplots_adjust(wspace=SPACING, hspace=SPACING)
 plt.show() 
<define_variables>
insincere = sorted[sorted['target']==1]
insincere[0:14]
disp_labels = []
disp_predictions = []
for i in range(54):
if i >= incorrect_labels_cnt:
break
id = incorrect_labels[i]
disp_labels.append(use_correct_labels[id])
 disp_predictions.append(use_val_predictions[id])
 print(disp_labels)
 print(disp_predictions)
<load_from_csv>
sorted_increasing = combined.sort_values(by=['error'], ascending=True)
 sorted_increasing[0:10]
val_ids = list(range(len(use_correct_labels)))
 filename = this_run_file_prefix + 'validation_results.csv'
np.savetxt(filename, np.rec.fromarrays([val_ids, use_correct_labels, use_val_predictions]), fmt = ['%d', '%d', '%d'], delimiter = ',', header = 'id,correct_label,predicted_label', comments = '')
 cls_ids = list(range(len(CLASSES)))
 filename = this_run_file_prefix + 'validation_statistics.csv'
np.savetxt(filename, np.rec.fromarrays([cls_ids, list(vals_actual_true.values()), list(vals_tp.values()), list(vals_fn.values()), list(vals_fp.values())]), fmt = ['%d', '%d', '%d', '%d', '%d'], delimiter = ',', header = 'cls_id,actual_true,true_positive,false_negative,false_positive', comments = '')
<import_modules>
combined['question_length']=combined['question_text'].apply(lambda x: len(x))
sorted_len = combined.sort_values(by=['question_length'], ascending=True)
 sorted_len[0:20]
import numpy as np
import pandas as pd
import os 
<set_options>
sorted_len.drop('qid',axis=1 ).iloc[::-1][0:8]
!pip install -q efficientnet
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
sorted_len[sorted_len['qid']=='4d2e2796dd1ced2c8e64']