Kaggle competition: Kannada MNIST
<SOS> metric: CategorizationAccuracy Kaggle data source: kannada-mnist<prepare_output>
warnings.filterwarnings('ignore' )
sample_submission['prediction'] = preds
mlc.kaggle.save_sub(sample_submission, 'submission.csv' )<define_variables>
train = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')
 test = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')
 sub = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')
 print('Our train set have {} rows and {} columns'.format(train.shape[0], train.shape[1]))
print('Our test set have {} rows and {} columns'.format(test.shape[0], test.shape[1]))
embed_size = 300
max_features = 95000
maxlen = 70<import_modules>
train.isnull().sum().sum()
import os
import time
import numpy as np
import pandas as pd
from tqdm import tqdm
import math
from sklearn.model_selection import train_test_split
from sklearn import metrics
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D
from keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D
from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate, Lambda
from keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D
from keras.optimizers import Adam
from keras.models import Model
from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints, optimizers, layers<load_from_csv>
def preprocessing(train, test):
IMG_SIZE = 28
img_train = train.drop(['label'], axis = 1 ).values.reshape(-1, IMG_SIZE, IMG_SIZE, 1 ).astype('float32')
 img_test = test.drop(['id'], axis = 1 ).values.reshape(-1, IMG_SIZE, IMG_SIZE, 1 ).astype('float32')
 img_y = train['label'].values
img_train /= 255
img_test /= 255
x_train, x_val, y_train, y_val = train_test_split(img_train, img_y, test_size = 0.20)
 print('Our transformed train set have the following dimension: ', x_train.shape)
 print('Our transformed valid set have the following dimension: ', x_val.shape)
 return img_test, x_train, x_val, y_train, y_val
def load_and_prec() :
train_df = pd.read_csv(".. /input/train.csv")
 test_df = pd.read_csv(".. /input/test.csv")
 print("Train shape : ",train_df.shape)
 print("Test shape : ",test_df.shape)
 train_df, val_df = train_test_split(train_df, test_size=0.08, random_state=2018)
 train_X = train_df["question_text"].fillna("_
val_X = val_df["question_text"].fillna("_
test_X = test_df["question_text"].fillna("_
tokenizer = Tokenizer(num_words=max_features)
 tokenizer.fit_on_texts(list(train_X))
train_X = tokenizer.texts_to_sequences(train_X)
 val_X = tokenizer.texts_to_sequences(val_X)
 test_X = tokenizer.texts_to_sequences(test_X)
 train_X = pad_sequences(train_X, maxlen=maxlen)
 val_X = pad_sequences(val_X, maxlen=maxlen)
 test_X = pad_sequences(test_X, maxlen=maxlen)
 train_y = train_df['target'].values
val_y = val_df['target'].values
np.random.seed(2018)
 trn_idx = np.random.permutation(len(train_X))
val_idx = np.random.permutation(len(val_X))
train_X = train_X[trn_idx]
val_X = val_X[val_idx]
train_y = train_y[trn_idx]
val_y = val_y[val_idx]
return train_X, val_X, test_X, train_y, val_y, tokenizer.word_index<statistical_test>
n_classes = train['label'].value_counts().count()
def build_model(input_shape=(28, 28, 1), classes = n_classes):
input_layer = Input(shape=input_shape)
 x = Conv2D(16,(3,3), strides=1, padding="same", name="conv1" )(input_layer)
 x = BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform", name="batch1" )(x)
 x = Activation('relu',name='relu1' )(x)
 x = Dropout(0.1 )(x)
 x = Conv2D(32,(3,3), strides=1, padding="same", name="conv2" )(x)
 x = BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer="uniform", name="batch2" )(x)
 x = Activation('relu',name='relu2' )(x)
 x = Dropout(0.15 )(x)
 x = MaxPooling2D(pool_size=2, strides=2, padding="same", name="max2" )(x)
 x = Conv2D(64,(5,5), strides=1, padding ="same", name="conv3" )(x)
 x = BatchNormalization(momentum=0.17, epsilon=1e-5, gamma_initializer="uniform", name="batch3" )(x)
 x = Activation('relu', name="relu3" )(x)
 x = MaxPooling2D(pool_size=2, strides=2, padding="same", name="max3" )(x)
 x = Conv2D(128,(5,5), strides=1, padding="same", name="conv4" )(x)
 x = BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer="uniform", name="batch4" )(x)
 x = Activation('relu', name="relu4" )(x)
 x = Dropout(0.17 )(x)
 x = Conv2D(64,(3,3), strides=1, padding="same", name="conv5" )(x)
 x = BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer="uniform", name="batch5" )(x)
 x = Activation('relu', name='relu5' )(x)
 x = Dropout(0.2 )(x)
 x = Conv2D(32,(3,3), strides=1, padding="same", name="conv6" )(x)
 x = BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer="uniform", name="batch6" )(x)
 x = Activation('relu', name="relu6" )(x)
 x = Dropout(0.05 )(x)
 x = Flatten()(x)
 x = Dense(50, name="Dense1" )(x)
 x = Activation('relu', name='relu7' )(x)
 x = Dropout(0.05 )(x)
 x = Dense(25, name="Dense2" )(x)
 x = Activation('relu', name='relu8' )(x)
 x = Dropout(0.03 )(x)
 x = Dense(classes, name="Dense3" )(x)
 x = Activation('softmax' )(x)
 model = Model(inputs=input_layer, outputs=x)
 return model
def load_glove(word_index):
EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE))
all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
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 tqdm(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
return embedding_matrix
def load_fasttext(word_index):
EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
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 tqdm(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
return embedding_matrix
def load_para(word_index):
EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
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 tqdm(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
return embedding_matrix<choose_model_class>
def trng_lr_ck_opt(modelname):
train_generator = ImageDataGenerator(rotation_range = 8,
zoom_range = 0.28,
width_shift_range = 0.25,
height_shift_range = 0.25)
 learning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy', patience = 5, verbose = 1, factor = 0.5, min_le = 0.000001)
 checkpoint = ModelCheckpoint(modelname+'.hdf5', monitor = 'val_accuracy', verbose = 1, save_best_only = True)
 return train_generator, learning_rate_reduction, checkpoint
def compile_model() :
optimizer = Adam(lr = 0.001)
 model = build_model(input_shape =(28, 28, 1), classes = n_classes)
 model.compile(loss = 'sparse_categorical_crossentropy', optimizer = optimizer, metrics = ['accuracy'])
 return model
def train_and_evaluate(train, test, batch_size, epochs):
img_test, x_train, x_val, y_train, y_val = preprocessing(train, test)
 model = compile_model()
train_generator, learning_rate_reduction, checkpoint = trng_lr_ck_opt('bestmodel')
 history = model.fit_generator(train_generator.flow(x_train, y_train, batch_size = batch_size),
steps_per_epoch = x_train.shape[0] // batch_size,
epochs = epochs,
validation_data =(x_val, y_val),
callbacks = [checkpoint, learning_rate_reduction])
 return img_test, history
BATCH_SIZE = 64
EPOCHS = 70
img_test, history = train_and_evaluate(train, test, BATCH_SIZE, EPOCHS )
def model_cnn(embedding_matrix):
filter_sizes = [1,2,3,5]
num_filters = 36
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp)
 x = Reshape(( maxlen, embed_size, 1))(x)
 maxpool_pool = []
for i in range(len(filter_sizes)) :
conv = Conv2D(num_filters, kernel_size=(filter_sizes[i], embed_size),
kernel_initializer='he_normal', activation='elu' )(x)
 maxpool_pool.append(MaxPool2D(pool_size=(maxlen - filter_sizes[i] + 1, 1))(conv))
z = Concatenate(axis=1 )(maxpool_pool)
 z = Flatten()(z)
 z = Dropout(0.1 )(z)
 outp = Dense(1, activation="sigmoid" )(z)
 model = Model(inputs=inp, outputs=outp)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model
def model_cnn_flip(embedding_matrix):
filter_sizes = [1,2,3,5]
num_filters = 36
inp = Input(shape=(maxlen,))
x = Lambda(lambda x: K.reverse(x,axes=-1))(inp)
 x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(x)
 x = Reshape(( maxlen, embed_size, 1))(x)
 maxpool_pool = []
for i in range(len(filter_sizes)) :
conv = Conv2D(num_filters, kernel_size=(filter_sizes[i], embed_size),
kernel_initializer='he_normal', activation='elu' )(x)
 maxpool_pool.append(MaxPool2D(pool_size=(maxlen - filter_sizes[i] + 1, 1))(conv))
z = Concatenate(axis=1 )(maxpool_pool)
 z = Flatten()(z)
 z = Dropout(0.1 )(z)
 outp = Dense(1, activation="sigmoid" )(z)
 model = Model(inputs=inp, outputs=outp)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model<choose_model_class>
def train_and_evaluate_kfold(train, test, batch_size, epochs):
IMG_SIZE = 28
img_test = test.drop(['id'], axis = 1 ).values.reshape(-1, IMG_SIZE, IMG_SIZE, 1 ).astype('float32')/ 255
img_y = train['label'].values
train = train.drop(['label'], axis = 1)
 preds = np.zeros([test.shape[0], n_classes])
 for fold_n in [1, 2, 3]:
print('Training fold {}'.format(fold_n))
x_train, x_val, y_train, y_val = train_test_split(train, img_y, test_size = 0.15, random_state = 42 + fold_n)
 x_train = x_train.values.reshape(-1, IMG_SIZE, IMG_SIZE, 1 ).astype('float32')/ 255
x_val = x_val.values.reshape(-1, IMG_SIZE, IMG_SIZE, 1 ).astype('float32')/ 255
model = compile_model()
train_generator, learning_rate_reduction, checkpoint = trng_lr_ck_opt('model_fold_{}'.format(fold_n))
history = model.fit_generator(train_generator.flow(x_train, y_train, batch_size = batch_size),
steps_per_epoch = x_train.shape[0] // batch_size,
epochs = epochs,
validation_data =(x_val, y_val),
callbacks = [checkpoint, learning_rate_reduction])
 model.load_weights('model_fold_{}'.format(fold_n)+ '.hdf5')
 preds += model.predict(img_test)/ 3
preds = np.argmax(preds, axis = 1)
 return preds
preds = train_and_evaluate_kfold(train, test, BATCH_SIZE, EPOCHS )
<choose_model_class><EOS> 
sub['label'] = preds
sub.to_csv('cnn_kfold_baseline.csv', index = False )