Kaggle competition: Kannada MNIST
<SOS> metric: CategorizationAccuracy Kaggle data source: kannada-mnist<predict_on_test>
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
predictions = bert_classifier.predict(glue_test )<prepare_output>
train = pd.read_csv(".. /input/Kannada-MNIST/train.csv")
 test = pd.read_csv(".. /input/Kannada-MNIST/test.csv" )
predictions = np.argmax(predictions, axis=1 )<save_to_csv>
y = train["label"]
train.drop("label",axis=1,inplace=True)
 test.drop("id",axis=1,inplace=True )
submission = pd.DataFrame({"id":test["id"], "target":predictions})
 submission.to_csv('/kaggle/working/submission.csv', index=False )<choose_model_class>
x_train = train.values
test = test.values
x_train = x_train/255
test = test/255
convert_abbrev = False
model_type = 'default'
Dropout_num = 0.1
learning_rate = 1e-5
max_len = 160
layers = []
activation = 'relu'
model_name = 'model_bert_cv_default_{}_shape_{}'.format(Dropout_num,'_'.join([str(i)for i in layers]))<load_from_url>
y_train = pd.get_dummies(y )
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py<load_from_csv>
x_train, x_test, y_train, y_test = train_test_split(x_train,y_train,test_size=0.2,random_state=42,stratify=y_train )
train = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv")
 test = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv")
 submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv" )<import_modules>
from keras.models import Sequential
from keras.layers import Dense, Conv2D, AveragePooling2D, Flatten, Dropout,MaxPool2D,BatchNormalization
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from keras.optimizers import RMSprop
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input,Dropout
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import ModelCheckpoint
import tensorflow_hub as hub
import tokenization
from sklearn.metrics import f1_score,precision_score,recall_score,roc_auc_score,log_loss,accuracy_score<categorify>
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size =(5,5),padding = 'Same', activation ='relu', input_shape =(28,28,1)))
 model.add(Conv2D(filters = 32, kernel_size =(5,5),padding = 'Same', activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
 model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size =(3,3),padding = 'Same', activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size =(3,3),padding = 'Same', activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
 model.add(Dropout(0.25))
model.add(Flatten())
 model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(10, activation = "softmax"))
def bert_encode(texts, tokenizer, max_len=512):
all_tokens = []
all_masks = []
all_segments = []
for text in texts:
text = tokenizer.tokenize(text)
 text = text[:max_len-2]
input_sequence = ["[CLS]"] + text + ["[SEP]"]
pad_len = max_len - len(input_sequence)
 tokens = tokenizer.convert_tokens_to_ids(input_sequence)
 tokens += [0] * pad_len
pad_masks = [1] * len(input_sequence)+ [0] * pad_len
segment_ids = [0] * max_len
all_tokens.append(tokens)
 all_masks.append(pad_masks)
 all_segments.append(segment_ids)
 return np.array(all_tokens), np.array(all_masks), np.array(all_segments)
 def build_model(bert_layer, max_len=512):
input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name="input_word_ids")
 input_mask = Input(shape=(max_len,), dtype=tf.int32, name="input_mask")
 segment_ids = Input(shape=(max_len,), dtype=tf.int32, name="segment_ids")
 _, sequence_output = bert_layer([input_word_ids, input_mask, segment_ids])
 clf_output = sequence_output[:, 0, :]
if model_type=='default':
for layer in layers:
clf_output = Dense(layer, activation=activation )(clf_output)
 out = Dense(1, activation='sigmoid' )(clf_output)
 elif model_type=='dropout':
for layer in layers:
x = Dropout(Dropout_num )(clf_output)
 clf_output = Dense(layer, activation=activation )(x)
 x = Dropout(Dropout_num )(clf_output)
 out = Dense(1, activation='sigmoid' )(x)
 elif model_type=='GlobalAveragePooling1D':
for layer in layers:
if Dropout_num>0:
clf_output = Dropout(Dropout_num )(clf_output)
 clf_output = Dense(layer, activation=activation )(clf_output)
 x = tf.keras.layers.GlobalAveragePooling1D()(sequence_output)
 out = Dense(1, activation='sigmoid' )(x)
 model = Model(inputs=[input_word_ids, input_mask, segment_ids], outputs=out)
 model.compile(Adam(lr=learning_rate), loss='binary_crossentropy', metrics=['accuracy'])
 return model<choose_model_class>
optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0 )
%%time
module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1"
bert_layer = hub.KerasLayer(module_url, trainable=True)
<feature_engineering>
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.00001 )
vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()
do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()
tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case )<categorify>
checkpoint=ModelCheckpoint('bestweights.hdf5', monitor='val_acc', verbose=1, save_best_only=True, mode="max" )
train_input = bert_encode(train.text.values, tokenizer, max_len=max_len)
 test_input = bert_encode(test.text.values, tokenizer, max_len=max_len)
 train_labels = train.target.values
print(train_input[0].shape,test_input[0].shape )<import_modules>
model.compile(optimizer=optimizer,loss='categorical_crossentropy',metrics=['acc'] )
from sklearn.model_selection import StratifiedKFold<choose_model_class>
train_gen = ImageDataGenerator(rotation_range=10,
width_shift_range=0.1,
height_shift_range=0.1,
zoom_range=0.1 )
skf = StratifiedKFold(n_splits=5 )<define_variables>
history= model.fit_generator(train_gen.flow(x_train,y_train,batch_size=86),
steps_per_epoch=x_train.shape[0]//86,
validation_data=(x_test,y_test),
validation_steps=x_test.shape[0]//86,
epochs=30,callbacks=[checkpoint,learning_rate_reduction ] )
train_labels = train.target.values<import_modules>
model.load_weights("bestweights.hdf5" )
import gc<categorify>
results = model.predict(test)
 results = np.argmax(results,axis = 1)
 submission = pd.read_csv('.. /input/Kannada-MNIST/sample_submission.csv')
 submission['label'] = results
submission.to_csv('submission.csv', index=False)
 submission.head()