Kaggle competition: Quora Insincere Questions Classification
print(mnli, '
')
 print('The split names in MNLI dataset:')
 for k in mnli:
print(' ', k)
 print("
mnli['train'] is ", type(mnli['train']))
mnli['train']<define_variables>
import pandas as pd
import numpy as np
import operator
import re
import gc
import pickle
from keras.preprocessing.text import Tokenizer
from sklearn.preprocessing import StandardScaler
print('The number of training examples in mnli dataset:', mnli['train'].num_rows)
 print('The number of validation examples in mnli dataset - part 1:', mnli['validation_matched'].num_rows)
 print('The number of validation examples in mnli dataset - part 2:', mnli['validation_mismatched'].num_rows, '
')
 print('The class names in mnli dataset:', mnli['train'].features['label'].names)
 print('The feature names in mnli dataset:', list(mnli['train'].features.keys()), '
')
 for elt in mnli['train']:
print('premise:', elt['premise'])
 print('hypothesis:', elt['hypothesis'])
 print('label:', elt['label'])
 print('label name:', mnli['train'].features['label'].names[elt['label']])
 print('idx', elt['idx'])
 print('-' * 80)
 if elt['idx'] >= 10:
break<create_dataframe>
np.random.seed(201942 )
mnli_train_df = pd.DataFrame(mnli['train'])
 mnli_valid_1_df = pd.DataFrame(mnli['validation_matched'])
 mnli_valid_2_df = pd.DataFrame(mnli['validation_mismatched'])
 mnli_train_df = mnli_train_df[['premise', 'hypothesis', 'label']]
mnli_valid_1_df = mnli_valid_1_df[['premise', 'hypothesis', 'label']]
mnli_valid_2_df = mnli_valid_2_df[['premise', 'hypothesis', 'label']]
mnli_train_df['lang_abv'] = 'en'
mnli_valid_1_df['lang_abv'] = 'en'
mnli_valid_2_df['lang_abv'] = 'en'<define_variables>
def load_embed(file):
def get_coefs(word, *arr):
return word, np.asarray(arr, dtype='float32')
 if file == '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec':
embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(file)if len(o)> 100)
 else:
embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(file, encoding='latin'))
return embeddings_index
snli = nlp.load_dataset(path='snli')
 print('The number of training examples in snli dataset:', snli['train'].num_rows)
 print('The number of validation examples in snli dataset:', snli['validation'].num_rows, '
')
 print('The class names in snli dataset:', snli['train'].features['label'].names)
 print('The feature names in snli dataset:', list(snli['train'].features.keys()), '
')
 for idx, elt in enumerate(snli['train']):
print('premise:', elt['premise'])
 print('hypothesis:', elt['hypothesis'])
 print('label:', elt['label'])
 print('label name:', snli['train'].features['label'].names[elt['label']])
 print('-' * 80)
 if idx >= 10:
break<create_dataframe>
def index_embs(embeddings_index, word_index, NUM_WORDS, fileName):
all_embs = np.stack(embeddings_index.values())
 emb_mean, emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
embedding_matrix = np.random.normal(emb_mean, emb_std,(NUM_WORDS, embed_size))
for word, i in word_index.items() :
if i >= NUM_WORDS: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
np.save(fileName, embedding_matrix)
 print(fileName + " embedding matrix saved!")
 del(embeddings_index)
 del(word_index)
 del(embedding_matrix)
 gc.collect()
snli_train_df = pd.DataFrame(snli['train'])
 snli_valid_df = pd.DataFrame(snli['validation'])
 snli_train_df = snli_train_df[['premise', 'hypothesis', 'label']]
snli_valid_df = snli_valid_df[['premise', 'hypothesis', 'label']]
snli_train_df['lang_abv'] = 'en'
snli_valid_df['lang_abv'] = 'en'<create_dataframe>
def check_coverage(vocab, embeddings_index):
known_words = {}
unknown_words = {}
nb_known_words = 0
nb_unknown_words = 0
for word in vocab.keys() :
try:
known_words[word] = embeddings_index[word]
nb_known_words += vocab[word]
except:
unknown_words[word] = vocab[word]
nb_unknown_words += vocab[word]
pass
print('Found embeddings for {:.2%} of vocab'.format(len(known_words)/ len(vocab)))
 print('Found embeddings for {:.2%} of all text'.format(nb_known_words /(nb_known_words + nb_unknown_words)))
 unknown_words = sorted(unknown_words.items() , key=operator.itemgetter(1)) [::-1]
return unknown_words
xnli = nlp.load_dataset(path='xnli')
 print('The number of validation examples in xnli dataset:', xnli['validation'].num_rows, '
')
 print('The class names in xnli dataset:', xnli['validation'].features['label'].names)
 print('The feature names in xnli dataset:', list(xnli['validation'].features.keys()), '
')
 for idx, elt in enumerate(xnli['validation']):
print('premise:', elt['premise'])
 print('hypothesis:', elt['hypothesis'])
 print('label:', elt['label'])
 print('label name:', xnli['validation'].features['label'].names[elt['label']])
 print('-' * 80)
 if idx >= 3:
break<create_dataframe>
def build_vocab(texts, num_words):
tokenizer = Tokenizer(num_words=NUM_WORDS, filters="")
 tokenizer.fit_on_texts(texts)
 with open('tokenizer.pickle', 'wb')as handle:
pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)
 print("
Keras text tokenizer has been saved as tokenizer.pickle")
 return tokenizer.word_index
buffer = {
'premise': [],
'hypothesis': [],
'label': [],
'lang_abv': []
}
for x in xnli['validation']:
label = x['label']
for idx, lang in enumerate(x['hypothesis']['language']):
hypothesis = x['hypothesis']['translation'][idx]
premise = x['premise'][lang]
buffer['premise'].append(premise)
 buffer['hypothesis'].append(hypothesis)
 buffer['label'].append(label)
 buffer['lang_abv'].append(lang)
 xnli_valid_df = pd.DataFrame(buffer)
 xnli_valid_df = xnli_valid_df[['premise', 'hypothesis', 'label', 'lang_abv']]<install_modules>
def add_lower(embedding, vocab):

 count = 0
for word in vocab:
if word in embedding and word.lower() not in embedding:
embedding[word.lower() ] = embedding[word]
count += 1
print(f"Added {count} words to embedding" )
!pip install -q efficientnet<import_modules>
def known_contractions(embed):
known = []
for contract in contraction_mapping:
if contract in embed:
known.append(contract)
 return known
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg19 import VGG19
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2
from tensorflow.keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201
from tensorflow.keras.applications.xception import Xception
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.applications.resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from tensorflow.keras.applications.nasnet import NASNetLarge
from efficientnet.tfkeras import EfficientNetB7, EfficientNetL2, EfficientNetB0, EfficientNetB1<set_options>
def clean_contractions(text, mapping):
specials = ["’", "‘", "´", "`"]
for s in specials:
text = text.replace(s, "'")
 text = ' '.join([mapping[t] if t in mapping else t for t in text.split(" ")])
 return text
%matplotlib inline
print("Tensorflow version " + tf.__version__ )<feature_engineering>
def unknown_punct(embed, punct):
unknown = ''
for p in punct:
if p not in embed:
unknown += p
unknown += ' '
return unknown
AUTO = tf.data.experimental.AUTOTUNE<define_variables>
def clean_special_chars(text, punct, mapping):
for p in mapping:
text = text.replace(p, mapping[p])
 for p in punct:
text = text.replace(p, f' {p} ')
 specials = {'\u200b': ' ', '…': '...', '\ufeff': '', 'करना': '', 'है': ''}
for s in specials:
text = text.replace(s, specials[s])
 return text
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 MORE_IMAGES_GCS_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec' )<define_variables>
def get_mappings() :

 mispell_dict = {'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization'}
punct = "/-'?!.,
punct_mapping = {"‘": "'", "₹": "e", "´": "'", "°": "", "€": "e", "™": "tm", "√": " sqrt ", "×": "x", "²": "2", "—": "-", "–": "-", "’": "'", "_": "-", "`": "'", '“': '"', '”': '"', '“': '"', "£": "e", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi', }
contraction_mapping = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have" }
return mispell_dict, contraction_mapping, punct_mapping, punct
IMAGE_SIZE = [512, 512]
EPOCHS = 20
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')
 MOREIMAGES_PATH_SELECT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
MOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
 INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
 OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
 TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES + IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES
SEED = 2020
NUM_TRAINING_IMAGES = 12753
NUM_TEST_IMAGES = 7382
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE<data_type_conversions>
def correct_spelling(x, dic):
for word in dic.keys() :
x = x.replace(word, dic[word])
 return x
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):
flag = random.randint(1,3)
 coef_1 = random.randint(70, 90)* 0.01
coef_2 = random.randint(70, 90)* 0.01
if flag == 1:
image = tf.image.random_flip_left_right(image, seed=SEED)
 elif flag == 2:
image = tf.image.random_flip_up_down(image, seed=SEED)
 else:
image = tf.image.random_crop(image, [int(IMAGE_SIZE[0]*coef_1), int(IMAGE_SIZE[0]*coef_2), 3],seed=SEED)
 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() :
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=False)
 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))<init_hyperparams>
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
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.75
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:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<choose_model_class>
def add_features(df, textCol, outputFileName):
df_features = pd.DataFrame()
df_features['total_length'] = df[textCol].apply(len)
 df_features['capitals'] = df[textCol].apply(lambda comment: sum(1 for c in comment if c.isupper()))
df_features['caps_vs_length'] = df_features["capitals"] / df_features['total_length']
df_features['num_words'] = df[textCol].str.count('\S+')
 df_features['num_unique_words'] = df[textCol].apply(lambda comment: len(set(w for w in comment.split())))
 df_features['words_vs_unique'] = df_features['num_unique_words'] / df_features['num_words']
df_features = df_features.fillna(0)
 ss = StandardScaler()
df_features = ss.fit_transform(df_features)
 print("
FEATURES DF SAVED TO:")
 print("{0}_features.npy".format(outputFileName))
np.save("{0}_features".format(outputFileName), df_features )
def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
 return Model(inputs=base_model.input, outputs=predictions)
 with strategy.scope() :
model = get_model(DenseNet201)
 model.compile(
 optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
<train_model>
def run_text_preprocessing(df, textCol, outputFileName):
mispell_map, contraction_map, punct_map, punct = get_mappings()
Working on: " + outputFileName)
 ****** WORD COVERAGE BEFORE PREPROCESSING ******")
 df['lowered_question'] = df[textCol].apply(lambda x: x.lower())
 df['treated_question'] = df['lowered_question'].apply(lambda x: clean_contractions(x, contraction_map))
df['treated_question'] = df['treated_question'].apply(lambda x: clean_special_chars(x, punct, punct_map))
df['treated_question'] = df['treated_question'].apply(lambda x: clean_numbers(x))
****** FINAL WORD COVERAGE AFTER PREPROCESSING ******")
 print("
DATAFRAME SAVED TO:")
 print("{0}_processed_text.csv".format(outputFileName))
df.to_csv("{0}_processed_text.csv".format(outputFileName))
del(mispell_map)
 del(contraction_map)
 del(punct_map)
 del(punct)
 gc.collect()
return df
history = model.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback, ModelCheckpoint(filepath='my_ef_net_b7.h5', monitor='val_loss',
save_best_only=True)],
validation_data=get_validation_dataset() ,
workers = 3)
 plt.plot(history.history['sparse_categorical_accuracy'],
label='Оценка точности на обучающем наборе')
 plt.plot(history.history['val_sparse_categorical_accuracy'],
label='Оценка точности на проверочном наборе')
 plt.xlabel('Эпоха обучения')
 plt.ylabel('Оценка точности')
 plt.legend()
plt.show()<load_pretrained>
train = pd.read_csv(".. /input/train.csv")
 test = pd.read_csv(".. /input/test.csv" )
model = tf.keras.models.load_model('my_ef_net_b7.h5' )<predict_on_test>
train = pd.read_csv(".. /input/train.csv")
 test = pd.read_csv(".. /input/test.csv" )
test_ds = get_test_dataset(ordered=True)
 print('Вычисляем предсказания...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Создание файла submission.csv...')
 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('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='' )<install_modules>
add_features(train, "question_text", "train")
 add_features(test, "question_text", "test" )
!pip install -q efficientnet<set_options>
train = run_text_preprocessing(train, "question_text", "train")
 test = run_text_preprocessing(test, "question_text", "test" )
%matplotlib inline
print("Tensorflow version " + tf.__version__ )<define_variables>
df_texts = pd.concat([train.drop('target', axis=1),test])
 df_texts.to_csv("texts_processed.csv" )
GCS_DS_PATH = KaggleDatasets().get_gcs_path("tpu-getting-started" )<define_variables>
del(train)
 del(test)
 gc.collect()
IMAGE_SIZE = [512, 512]
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]]
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 SEED = 2020<data_type_conversions>
glove = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt'
paragram = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
wiki_news = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'
NUM_WORDS = None
word_idx = build_vocab(df_texts["treated_question"], NUM_WORDS)
 NUM_WORDS = len(word_idx)+ 1
print(NUM_WORDS)
 print("
****** LOAD EMBEDDINGS ******")
 print("
---Extracting GloVe embedding---")
 embed_glove = load_embed(glove)
 index_embs(embed_glove, word_idx, NUM_WORDS, fileName="glove")
 del(embed_glove)
 gc.collect()
print("
---Extracting Paragram embedding---")
 embed_paragram = load_embed(paragram)
 index_embs(embed_paragram, word_idx, NUM_WORDS, fileName="paragram")
 del(embed_paragram)
 gc.collect()
---Extracting FastText embedding---")
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 get_validation_dataset() :
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)
 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_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 print('Dataset: {} validation images, {} unlabeled test images'.format(NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<choose_model_class>
gc.collect()
%reset -f
def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
 model = Model(inputs=base_model.input, outputs=predictions)
 model.compile(
 optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
with strategy.scope() :
model1 = get_model(EfficientNetB7)
 model1.load_weights("/kaggle/input/more-data-with-efficientnetb7/my_ef_net_b7.h5" )<choose_model_class>
startTimePt2 = time.time()
def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
 model = Model(inputs=base_model.input, outputs=predictions)
 model.compile(
 optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
with strategy.scope() :
model2 = get_model(VGG19)
 model2.load_weights("/kaggle/input/start-with-pre-train/my_ef_net_b7.h5" )<predict_on_test>
NUM_WORDS = 192111
EMBEDDING_DIM = 300
NUM_FILTERS = 100
MAX_LEN = 72
BATCH_SIZE = 512
RANDOM_STATE = 201942
NUM_EPOCH = 6
LR = 0.003
LR_MAX = LR * 6
WD = 0.011 *(BATCH_SIZE / 979591 / NUM_EPOCH)**0.5
STEP_SIZE_CLR = 2 *(int(979591 * 2)/ BATCH_SIZE)
val_dataset = get_validation_dataset()
images_ds = val_dataset.map(lambda image, label: image)
 labels_ds = val_dataset.map(lambda image, label: label ).unbatch()
val_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
m1 = model1.predict(images_ds)
 m2 = model2.predict(images_ds)
 scores = []
for alpha in np.linspace(0,1,100):
val_probabilities = alpha*m1+(1-alpha)*m2
val_predictions = np.argmax(val_probabilities, axis=-1)
 scores.append(f1_score(val_labels, val_predictions, labels=range(104), average='macro'))
best_alpha = np.argmax(scores)/100
print('Best alpha: ' + str(best_alpha))<predict_on_test>
np.random.seed(RANDOM_STATE)
 set_random_seed(RANDOM_STATE )
test_ds = get_test_dataset(ordered=True)
 best_alpha = 0.48
print('Вычисляем предсказания...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities1 = model1.predict(test_images_ds)
 probabilities2 = model2.predict(test_images_ds)
 probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Создание файла submission.csv...')
 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('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='' )<install_modules>
df_train = pd.read_csv("train_processed_text.csv")
 df_test = pd.read_csv("test_processed_text.csv")
 print("Train shape : ", df_train.shape)
 print("Test shape : ", df_test.shape )
!pip install efficientnet<import_modules>
X_train = df_train["treated_question"].fillna("_na_" ).values
X_test = df_test["treated_question"].fillna("_na_" ).values
y_train = df_train['target'].values
import random, re, math, os
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow_addons as tfa
from kaggle_datasets import KaggleDatasets
from tensorflow.keras.mixed_precision import experimental as mixed_precision
import tensorflow.keras.backend as K
import efficientnet.tfkeras as efn
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
import datetime
import tqdm
import json
from collections import Counter
import gc<define_variables>
X_features_train = np.load("train_features.npy")
 X_features_test = np.load("test_features.npy" )
IMAGE_SIZE = [512, 512]
EPOCHS = 16
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
SEED = 100<define_variables>
with open('tokenizer.pickle', 'rb')as handle:
tokenizer = pickle.load(handle )
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 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' )<set_options>
NUM_WORDS = len(tokenizer.word_index)+ 1
NUM_WORDS
MIXED_PRECISION = False
XLA_ACCELERATE = False
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )<define_variables>
X_train = tokenizer.texts_to_sequences(X_train)
 X_test = tokenizer.texts_to_sequences(X_test)
 print("hello word" )
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_train = pad_sequences(X_train, maxlen=MAX_LEN)
 X_test = pad_sequences(X_test, maxlen=MAX_LEN)
 print("hello word" )
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 dataset_to_numpy_util(dataset, N):
dataset = dataset.unbatch().batch(N)
 for images, labels in dataset:
numpy_images = images.numpy()
numpy_labels = labels.numpy()
break;
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
label = np.argmax(label, axis = -1)
 correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], str(correct), ', should be ' if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower_eval(image, title, subplot, red = False):
plt.subplot(subplot)
 plt.axis('off')
 plt.imshow(image)
 plt.title(title, fontsize = 14, color = 'red' if red else 'black')
 return subplot + 1
def display_9_images_with_predictions(images, predictions, labels):
subplot = 331
plt.figure(figsize =(13,13))
for i, image in enumerate(images):
title, correct = title_from_label_and_target(predictions[i], labels[i])
 subplot = display_one_flower_eval(image, title, subplot, not correct)
 if i >= 8:
break;
plt.tight_layout()
plt.subplots_adjust(wspace = 0.1, hspace = 0.1)
 plt.show()<categorify>
del(df_train)
 del(df_test )
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<categorify>
embedding_matrix_1 = np.load("glove.npy")
 embedding_matrix_3 = np.load("paragram.npy")
 print("Done..." )
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_labeled_id_tfrecord(example):
LABELED_ID_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, LABELED_ID_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 idnum = example['id']
return image, label, idnum<prepare_x_and_y>
embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0)
 np.shape(embedding_matrix )
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<create_dataframe>
del(embedding_matrix_1)
 del(embedding_matrix_3 )
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_id_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset<create_dataframe>
gc.collect()
print("done" )
def get_training_dataset() :
train = load_dataset(TRAINING_FILENAMES, labeled = True)
 train = train.map(lambda image, label, idnum: [image, label])
 train = train.repeat()
train = train.shuffle(2048)
 train = train.batch(BATCH_SIZE)
 train = train.prefetch(AUTO)
 return train
def get_training_dataset_preview(ordered = True):
train = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = ordered)
 train = train.batch(BATCH_SIZE)
 train = train.cache()
train = train.prefetch(AUTO)
 return train<create_dataframe>
class CyclicLR(Callback):

 def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular',
gamma=1., scale_fn=None, scale_mode='cycle'):
super(CyclicLR, self ).__init__()
self.base_lr = base_lr
self.max_lr = max_lr
self.step_size = step_size
self.mode = mode
self.gamma = gamma
if scale_fn == None:
if self.mode == 'triangular':
self.scale_fn = lambda x: 1.
 self.scale_mode = 'cycle'
elif self.mode == 'triangular2':
self.scale_fn = lambda x: 1/(2.**(x-1))
self.scale_mode = 'cycle'
elif self.mode == 'exp_range':
self.scale_fn = lambda x: gamma**(x)
 self.scale_mode = 'iterations'
else:
self.scale_fn = scale_fn
self.scale_mode = scale_mode
self.clr_iterations = 0.
 self.trn_iterations = 0.
 self.history = {}
self._reset()
def _reset(self, new_base_lr=None, new_max_lr=None,
new_step_size=None):

 if new_base_lr != None:
self.base_lr = new_base_lr
if new_max_lr != None:
self.max_lr = new_max_lr
if new_step_size != None:
self.step_size = new_step_size
self.clr_iterations = 0.
 def clr(self):
cycle = np.floor(1+self.clr_iterations/(2*self.step_size))
x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1)
 if self.scale_mode == 'cycle':
return self.base_lr +(self.max_lr-self.base_lr)*np.maximum(0,(1-x)) *self.scale_fn(cycle)
 else:
return self.base_lr +(self.max_lr-self.base_lr)*np.maximum(0,(1-x)) *self.scale_fn(self.clr_iterations)
 def on_train_begin(self, logs={}):
logs = logs or {}
if self.clr_iterations == 0:
K.set_value(self.model.optimizer.lr, self.base_lr)
 else:
K.set_value(self.model.optimizer.lr, self.clr())
 def on_batch_end(self, epoch, logs=None):
logs = logs or {}
self.trn_iterations += 1
self.clr_iterations += 1
K.set_value(self.model.optimizer.lr, self.clr() )
def get_validation_dataset(ordered = False):
validation = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = ordered)
 validation = validation.map(lambda image, label, idnum: [image, label])
 validation = validation.batch(BATCH_SIZE)
 validation = validation.cache()
validation = validation.prefetch(AUTO)
 return validation<create_dataframe>
class AdamW(Optimizer):

 def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, weight_decay=1e-4,
epsilon=1e-8, decay=0., **kwargs):
super(AdamW, self ).__init__(**kwargs)
 with K.name_scope(self.__class__.__name__):
self.iterations = K.variable(0, dtype='int64', name='iterations')
 self.lr = K.variable(lr, name='lr')
 self.init_lr = lr
self.beta_1 = K.variable(beta_1, name='beta_1')
 self.beta_2 = K.variable(beta_2, name='beta_2')
 self.decay = K.variable(decay, name='decay')
 self.wd = K.variable(weight_decay, name='weight_decay')
 self.epsilon = epsilon
self.initial_decay = decay
@interfaces.legacy_get_updates_support
def get_updates(self, loss, params):
grads = self.get_gradients(loss, params)
 self.updates = [K.update_add(self.iterations, 1)]
wd = self.wd
lr = self.lr
if self.initial_decay > 0:
lr *=(1./(1.+ self.decay * K.cast(self.iterations,
K.dtype(self.decay))))
eta_t = lr / self.init_lr
t = K.cast(self.iterations, K.floatx())+ 1
lr_t = lr *(K.sqrt(1.- K.pow(self.beta_2, t)) / 
(1.- K.pow(self.beta_1, t)))
 ms = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]
vs = [K.zeros(K.int_shape(p), dtype=K.dtype(p)) for p in params]
self.weights = [self.iterations] + ms + vs
for p, g, m, v in zip(params, grads, ms, vs):
m_t =(self.beta_1 * m)+(1.- self.beta_1)* g
v_t =(self.beta_2 * v)+(1.- self.beta_2)* K.square(g)
 p_t = p - lr_t * m_t /(K.sqrt(v_t)+ self.epsilon)- eta_t * wd * p
self.updates.append(K.update(m, m_t))
self.updates.append(K.update(v, v_t))
new_p = p_t
if getattr(p, 'constraint', None)is not None:
new_p = p.constraint(new_p)
 self.updates.append(K.update(p, new_p))
return self.updates
def get_config(self):
config = {'lr': float(K.get_value(self.lr)) ,
'beta_1': float(K.get_value(self.beta_1)) ,
'beta_2': float(K.get_value(self.beta_2)) ,
'decay': float(K.get_value(self.decay)) ,
'weight_decay': float(K.get_value(self.wd)) ,
'epsilon': self.epsilon}
base_config = super(AdamW, self ).get_config()
return dict(list(base_config.items())+ list(config.items()))
def get_test_dataset(ordered = False):
test = load_dataset(TEST_FILENAMES, labeled = False, ordered = ordered)
 test = test.batch(BATCH_SIZE)
 test = test.prefetch(AUTO)
 return test<groupby>
glorotInit = initializers.glorot_uniform(seed=RANDOM_STATE)
 orthoInit = initializers.Orthogonal(seed=RANDOM_STATE )
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>
def squash(x, axis=-1):
s_squared_norm = K.sum(K.square(x), axis, keepdims=True)
 scale = K.sqrt(s_squared_norm + K.epsilon())
 return x / scale
class Capsule(Layer):
def __init__(self, num_capsule, dim_capsule, routings=3, kernel_size=(9, 1), share_weights=True,
activation='default', **kwargs):
super(Capsule, self ).__init__(**kwargs)
 self.num_capsule = num_capsule
self.dim_capsule = dim_capsule
self.routings = routings
self.kernel_size = kernel_size
self.share_weights = share_weights
if activation == 'default':
self.activation = squash
else:
self.activation = Activation(activation)
 def build(self, input_shape):
super(Capsule, self ).build(input_shape)
 input_dim_capsule = input_shape[-1]
if self.share_weights:
self.W = self.add_weight(name='capsule_kernel',
shape=(1, input_dim_capsule,
self.num_capsule * self.dim_capsule),
initializer=glorotInit,
trainable=True)
 else:
input_num_capsule = input_shape[-2]
self.W = self.add_weight(name='capsule_kernel',
shape=(input_num_capsule,
input_dim_capsule,
self.num_capsule * self.dim_capsule),
initializer=glorotInit,
trainable=True)
 def call(self, u_vecs):
if self.share_weights:
u_hat_vecs = K.conv1d(u_vecs, self.W)
 else:
u_hat_vecs = K.local_conv1d(u_vecs, self.W, [1], [1])
 batch_size = K.shape(u_vecs)[0]
input_num_capsule = K.shape(u_vecs)[1]
u_hat_vecs = K.reshape(u_hat_vecs,(batch_size, input_num_capsule,
self.num_capsule, self.dim_capsule))
u_hat_vecs = K.permute_dimensions(u_hat_vecs,(0, 2, 1, 3))
b = K.zeros_like(u_hat_vecs[:, :, :, 0])
 for i in range(self.routings):
b = K.permute_dimensions(b,(0, 2, 1))
c = K.softmax(b)
 c = K.permute_dimensions(c,(0, 2, 1))
b = K.permute_dimensions(b,(0, 2, 1))
outputs = self.activation(tf.keras.backend.batch_dot(c, u_hat_vecs, [2, 2]))
if i < self.routings - 1:
b = tf.keras.backend.batch_dot(outputs, u_hat_vecs, [2, 3])
 return outputs
def compute_output_shape(self, input_shape):
return(None, self.num_capsule, self.dim_capsule)
train_dataset_aug = get_training_dataset()
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))<define_variables>
def capsule_model() :
K.clear_session()
inp_features = Input(shape=(6,))
inp = Input(shape=(MAX_LEN,))
emb = Embedding(NUM_WORDS, EMBEDDING_DIM, weights=[embedding_matrix], trainable=False )(inp)
 emb_drop = SpatialDropout1D(rate=0.2 )(emb)
 rnn = Bidirectional(CuDNNLSTM(75, return_sequences=True,
kernel_initializer=glorotInit, recurrent_initializer=orthoInit))(emb_drop)
 caps = Capsule(num_capsule=4, dim_capsule=10, routings=8, share_weights=True )(rnn)
 flat = Flatten()(caps)
 dense_1 = Dense(100, activation="elu", kernel_initializer=glorotInit )(flat)
 concat = concatenate([dense_1, inp_features])
 out_drop = Dropout(0.12 )(concat)
 out_bn = BatchNormalization()(out_drop)
 out = Dense(1, activation="sigmoid" )(out_bn)
 model = Model(inputs=[inp_features, inp], outputs=out)
 model.compile(loss='binary_crossentropy', optimizer=AdamW(lr=LR, weight_decay=WD), metrics=["acc", f1])
 return model
validation_dataset_aug = get_validation_dataset()
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))<define_variables>
def threshold_search(y_true, y_proba):
best_threshold = 0
best_score = 0
for threshold in [i * 0.01 for i in range(100)]:
score = f1_score(y_true=y_true, y_pred=y_proba > threshold)
 if score > best_score:
best_threshold = threshold
best_score = score
search_result = {'threshold': best_threshold, 'f1': best_score}
return search_result
test_dataset_aug = get_test_dataset()
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))<choose_model_class>
def step_decay(epoch):
initial_lrate = LR
drop = 0.6
epochs_drop = 5.0
lrate = initial_lrate * math.pow(drop, math.floor(( 1+epoch)/epochs_drop))
return lrate
def lrfn(epoch):
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
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:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY **(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<choose_model_class>
clr = CyclicLR(base_lr=0.001, max_lr=0.003,
step_size=300., mode='exp_range',
gamma=0.99994 )
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape =(512, 512, 3),
weights = 'imagenet',
include_top = False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'] 
)
 model.summary()
model.save('ML_finalproject.h5' )<create_dataframe>
def train_pred(model, train_X,train_features_X, train_y, val_X, val_features_X, val_y, test_data, callbacks=None):
st = time.time()
model.fit([train_features_X, np.array(train_X)], train_y, batch_size=BATCH_SIZE, epochs=NUM_EPOCH,
validation_data=([val_features_X, np.array(val_X)], val_y), callbacks = callbacks, verbose=2)
 pred_val_y = model.predict([val_features_X, val_X], batch_size=1024, verbose=0)
 best_thresh = threshold_search(val_y, pred_val_y)
 print("\tVal F1 Score: {:.4f}\tThresh: {:.2f}".format(best_thresh["f1"], best_thresh["threshold"]))
best_score = best_thresh["f1"]
pred_test_y = model.predict(test_data, batch_size=1024, verbose=0)
 print("Training time was: " + str(time.time() - st))
print('=' * 60)
 return pred_val_y, pred_test_y, best_score
gc.enable()
def get_training_dataset_raw() :
dataset = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = False)
 return dataset
raw_training_dataset = get_training_dataset_raw()
label_counter = Counter()
for images, labels, id in raw_training_dataset:
label_counter.update([labels.numpy() ])
 del raw_training_dataset
TARGET_NUM_PER_CLASS = 122
def get_weight_for_class(class_id):
counting = label_counter[class_id]
weight = TARGET_NUM_PER_CLASS / counting
return weight
weight_per_class = {class_id: get_weight_for_class(class_id)for class_id in range(104)}<train_model>
train_meta = np.zeros(y_train.shape)
 test_meta = np.zeros(len(X_test))
splits = list(StratifiedKFold(n_splits=5, shuffle=True, random_state=RANDOM_STATE ).split(X_train, y_train))
for idx,(train_idx, valid_idx)in enumerate(splits):
X_train_tmp = X_train[train_idx]
X_features_train_tmp = X_features_train[train_idx]
y_train_tmp = y_train[train_idx]
X_val_tmp = X_train[valid_idx]
X_features_val_tmp = X_features_train[valid_idx]
y_val_tmp = y_train[valid_idx]
model = capsule_model()
pred_val_y, pred_test_y, best_score = train_pred(model, X_train_tmp, X_features_train_tmp, y_train_tmp, X_val_tmp,
X_features_val_tmp, y_val_tmp, [X_features_test ,X_test],
callbacks=[clr])
 train_meta[valid_idx] = pred_val_y.reshape(-1)
 test_meta += pred_test_y.reshape(-1)/ len(splits)
 del(X_train_tmp)
 del(y_train_tmp)
 del(X_val_tmp)
 del(y_val_tmp)
 gc.collect()
history = model.fit(
 get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
class_weight = weight_per_class
)<predict_on_test>
search_result = threshold_search(y_train, train_meta)
 print(search_result)
 sub = pd.read_csv('.. /input/sample_submission.csv')
 sub.prediction = test_meta > search_result['threshold']
sub.to_csv("submission.csv", index=False )
<compute_train_metric><EOS> 
( time.time() - startTimePt2)/ 60