Kaggle competition: Quora Insincere Questions Classification
learner.save('ResNet34_256_1' )<compute_test_metric>
from numpy import array
from numpy import asarray
from numpy import zeros
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers import Dropout
from keras.layers import Bidirectional
from keras.layers import CuDNNGRU
from keras.layers.embeddings import Embedding
def sigmoid_np(x):
return 1.0/(1.0 + np.exp(-x))
preds,y = learner.TTA()
preds = np.stack(preds, axis=-1)
 preds = sigmoid_np(preds)
 pred = preds.max(axis=-1 )<compute_test_metric>
df_train = pd.read_csv(".. /input/train.csv" )
th = np.array([0.50,0.56,0.50,0.50,0.50,0.47,0.39,0.56,0.36,0.45,
0.41,0.48,0.45,0.44,0.63,0.50,0.38,0.33,0.45,0.41,
0.33,0.49,0.43,0.52,0.51,0.48,0.43,0.1])
 print(f1_score(y, pred>0.5, average='macro'),f1_score(y, pred>th, average='macro'))<concatenate>
df_test = pd.read_csv(".. /input/test.csv" )
preds_t,y_t = learner.TTA(is_test=True)
 preds_t = np.stack(preds_t, axis=-1)
 preds_t = sigmoid_np(preds_t)
 pred_t = preds_t.max(axis=-1 )<define_variables>
tokenizer = Tokenizer()
tokenizer.fit_on_texts(df_train['question_text'] )
pred_list = []
for line in pred_t:
s = ' '.join(list([str(i)for i in np.nonzero(line>th_t)[0]]))
pred_list.append(s )<save_to_csv>
vocab_size = len(tokenizer.word_index)+ 1
sample_df = pd.read_csv(SAMPLE)
 sample_list = list(sample_df.Id)
 pred_dic = dict(( key, value)for(key, value)
 in zip(learner.data.test_ds.fnames,pred_list))
pred_list_cor = [pred_dic[id] for id in sample_list]
df = pd.DataFrame({'Id':sample_list,'Predicted':pred_list_cor})
 df.to_csv('protein_classification.csv', header=True, index=False )<init_hyperparams>
ts_train=tokenizer.texts_to_sequences(df_train['question_text'] )
def xgboost_prediction(train,labels,test):
params = {}
params["objective"] = "reg:linear"
params["eta"] = 0.01
params["min_child_weight"] = 100
params["subsample"] = 0.6
params["colsample_bytree"] = 0.7
params["scale_pos_weight"] = 1.0
params["silent"] = 1
params["max_depth"] = 9
paramslist = list(params.items())
 offset = 4000
num_rounds = 10000
xgb_test = xgb.DMatrix(test)
 xgb_train = xgb.DMatrix(train[offset:,:], label=labels[offset:])
 xgb_value = xgb.DMatrix(train[:offset,:], label=labels[:offset])
 listforprint = [(xgb_train, 'train'),(xgb_value, 'value')]
model = xgb.train(paramslist, xgb_train, num_rounds, listforprint, early_stopping_rounds=120)
 prediction1 = model.predict(xgb_test,ntree_limit=model.best_iteration)
 train = train[::-1,:]
labels = np.log(labels[::-1])
 xgb_train = xgb.DMatrix(train[offset:,:], label=labels[offset:])
 xgb_value = xgb.DMatrix(train[:offset,:], label=labels[:offset])
 listforprint = [(xgb_train, 'train'),(xgb_value, 'value')]
model = xgb.train(paramslist, xgb_train, num_rounds, listforprint, early_stopping_rounds=120)
 prediction2 = model.predict(xgb_test,ntree_limit=model.best_iteration)
 prediction =(prediction1)*1.4 +(prediction2)*8.6
return prediction
train = pd.read_csv('.. /input/train.csv', index_col=0)
 test = pd.read_csv('.. /input/test.csv', index_col=0)
 labels = train.Hazard
train.drop('Hazard', axis=1, inplace=True)
 train_temp = train
test_temp = test
train_temp.drop('T2_V10', axis=1, inplace=True)
 train_temp.drop('T2_V7', axis=1, inplace=True)
 train_temp.drop('T1_V13', axis=1, inplace=True)
 train_temp.drop('T1_V10', axis=1, inplace=True)
 test_temp.drop('T2_V10', axis=1, inplace=True)
 test_temp.drop('T2_V7', axis=1, inplace=True)
 test_temp.drop('T1_V13', axis=1, inplace=True)
 test_temp.drop('T1_V10', axis=1, inplace=True)
 columns = train.columns
test_index = test.index
train_temp = np.array(train_temp)
 test_temp = np.array(test_temp)
 for i in range(train_temp.shape[1]):
le = preprocessing.LabelEncoder()
le.fit(list(train_temp[:,i])+ list(test_temp[:,i]))
train_temp[:,i] = le.transform(train_temp[:,i])
 test_temp[:,i] = le.transform(test_temp[:,i])
 train_temp = train_temp.astype(float)
 test_temp = test_temp.astype(float)
 prediction1 = xgboost_prediction(train_temp,labels,test_temp)
 train = train.T.to_dict().values()
test = test.T.to_dict().values()
vec = DictVectorizer()
train = vec.fit_transform(train)
 test = vec.transform(test)
 prediction2 = xgboost_prediction(train,labels,test)
 prediction = prediction1 + prediction2
prediction = pd.DataFrame({"Id": test_index, "Hazard": prediction})
 prediction = prediction.set_index('Id')
 prediction.to_csv('result.csv' )<set_options>
ts_test=tokenizer.texts_to_sequences(df_test['question_text'] )
print('TensorFlow version', tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<define_variables>
X_train_vectorized=pad_sequences(ts_train,maxlen=135,padding='post' )
start_time = datetime.now()
print('Time now is', start_time)
 end_training_by_tdelta = timedelta(seconds=8400)
 this_run_file_prefix = start_time.strftime('%Y%m%d_%H%M_')
 print(this_run_file_prefix)
 IMAGE_SIZE = [224, 224]
EPOCHS = 12
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']<categorify>
X_test_vectorized=pad_sequences(ts_test,maxlen=135,padding='post' )
np.set_printoptions(threshold=15, linewidth=80)
 def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red=False, titlesize=16):
plt.subplot(*subplot)
 plt.axis('off')
 plt.imshow(image)
 if len(title)> 0:
plt.title(title, fontsize=int(titlesize)if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2]+1)
 def display_batch_of_images(databatch, predictions=None):

 images, labels = batch_to_numpy_images_and_labels(databatch)
 if labels is None:
labels = [None for _ in enumerate(images)]
rows = int(math.sqrt(len(images)))
 cols = len(images)//rows
FIGSIZE = 13.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()
def display_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='Reds')
 ax.set_xticks(range(len(CLASSES)))
 ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
 ax.set_yticks(range(len(CLASSES)))
 ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
 titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
 if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
 if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
 if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
plt.show()
def display_training_curves(training, validation, title, subplot):
if subplot%10==1:
plt.subplots(figsize=(10,10), facecolor='
plt.tight_layout()
ax = plt.subplot(subplot)
 ax.set_facecolor('
ax.plot(training)
 ax.plot(validation)
 ax.set_title('model '+ title)
 ax.set_ylabel(title)
 ax.set_xlabel('epoch')
 ax.legend(['train', 'valid.'] )<categorify>
y_train = df_train['target']
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)) 
<categorify>
embeddings_index = {}
f = open('.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt', encoding='utf8')
 for line in f:
values = line.split()
word = ''.join(values[:-300])
 coefs = np.asarray(values[-300:], dtype='float32')
 embeddings_index[word] = coefs
f.close()
print('Loaded %s word vectors.' % len(embeddings_index))
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>
embedding_matrix = zeros(( vocab_size, 300))
for word, i in tokenizer.word_index.items() :
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
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>
model = Sequential()
e = Embedding(vocab_size, 300, weights=[embedding_matrix], input_length=135, trainable=False)
 model.add(e)
 model.add(Bidirectional(LSTM(128, return_sequences=True)))
 model.add(Flatten())
 model.add(Dense(128, activation='sigmoid'))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
 print(model.summary() )
start_time = datetime.now()
this_run_file_prefix = start_time.strftime('%Y%m%d_%H%M_')
 test_vals_pickle_outputs = ['/kaggle/input/efficientnet-with-all-5-imagesets-s2/20200428_0931_tests_vals_0.pkl', '/kaggle/input/densenet-with-all-5-imagesets-s3/20200428_1755_tests_vals_0.pkl', '/kaggle/input/densenet-with-all-5-imagesets-s4/20200429_0633_tests_vals_0.pkl', '/kaggle/input/efficientnet-with-all-5-imagesets-s5/20200430_1549_tests_vals_0.pkl', '/kaggle/input/efficientnet-with-all-5-imagesets-s6/20200430_1554_tests_vals_0.pkl', '/kaggle/input/densenet-with-all-5-imagesets-s7/20200430_1821_tests_vals_0.pkl', '/kaggle/input/densenet-with-all-5-imagesets-s8/20200430_1826_tests_vals_0.pkl', '/kaggle/input/efficientnet-with-all-5-imagesets-s9/20200501_0701_tests_vals_0.pkl', '/kaggle/input/densenet-with-all-5-imagesets-s10/20200501_0705_tests_vals_0.pkl', '/kaggle/input/efficientnet-with-all-5-imagesets-s11/20200502_0517_tests_vals_0.pkl', '/kaggle/input/densenet-with-all-5-imagesets-s12/20200502_0810_tests_vals_0.pkl', '/kaggle/input/efficientnet-with-all-5-imagesets-s13/20200504_1036_tests_vals_0.pkl', '/kaggle/input/densenet-with-all-5-imagesets-s14/20200504_1038_tests_vals_0.pkl', '/kaggle/input/efficientnet-with-all-5-imagesets-s15/20200505_0235_tests_vals_0.pkl', '/kaggle/input/densenet-with-all-5-imagesets-s16/20200505_0237_tests_vals_0.pkl'] 
<load_pretrained>
model.fit(X_train_vectorized, y_train, epochs=3, batch_size=1024, verbose=0 )
def get_results_from_pickle(filename):
pklfile = open(filename, 'rb')
 test_results = pickle.load(pklfile)
 pklfile.close()
return test_results 
<categorify>
predictions = model.predict(X_test_vectorized )
no_of_models = len(test_vals_pickle_outputs)
 cm_correct_labels_results = [0] * no_of_models
cm_predictions_results = [0] * no_of_models
test_ids_results = [0] * no_of_models
val_probabilities = [0] * no_of_models
test_probabilities = [0] * no_of_models
test_predictions = [0] * no_of_models
for j in range(no_of_models):
test_results = get_results_from_pickle(test_vals_pickle_outputs[j])
 [cm_correct_labels_results[j], cm_predictions_results[j], test_ids_results[j], val_probabilities[j], test_probabilities[j]] = test_results
test_predictions[j] = np.argmax(test_probabilities[j], axis = -1)
 for j in range(no_of_models):
cm_labels_compare = cm_correct_labels == cm_correct_labels_results[j]
test_ids_compare = test_ids == test_ids_results[j]
if not cm_labels_compare.all() :
print('Some probelm with cm_correct_labels_results in', j)
 if not test_ids_compare.all() :
print('Some probelm with test_ids_results in', j)
<define_variables>
preds_class =(predictions > 0.33 ).astype(np.int )
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_results[0].shape, cm_correct_labels_results[0])
 print('Predicted labels: ', cm_predictions.shape, cm_predictions )<compute_train_metric>
qid = df_test['qid']
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 
<find_best_params>
submission_df = pd.concat([qid, prediction], axis=1 )
for j in range(no_of_models):
model_predictions = np.argmax(val_probabilities[j], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels_results[0], model_predictions)
 print('For model: {}, f1 score: {:.4f}, precision: {:.4f}, recall: {:.4f}'.format(j, score, precision, recall))<compute_train_metric>
submission_df.to_csv("submission.csv", columns = submission_df.columns, index=False )