Kaggle competition: Kannada MNIST
del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x
time.sleep(10 )<find_best_params>
train_data = pd.read_csv("/kaggle/input/Kannada-MNIST/train.csv")
 test_data = pd.read_csv("/kaggle/input/Kannada-MNIST/test.csv" )
pred_val_y =(4 * pred_glove_val_y + pred_fasttext_val_y + 3 * pred_paragram_val_y + 2 * pred_cnn_val_y)/ 10.0
thresholds = []
for thresh in np.arange(0.1, 0.501, 0.01):
thresh = np.round(thresh, 2)
 res = metrics.f1_score(val_y,(pred_val_y > thresh ).astype(int))
thresholds.append([thresh, res])
 print("F1 score at threshold {0} is {1}".format(thresh, res))
thresholds.sort(key=lambda x: x[1], reverse=True)
 best_thresh = thresholds[0][0]
print("Best threshold: ", best_thresh )<save_to_csv>
num_classes = 10
img_rows = 28
img_cols = 28
def raw_to_img_array(raw_data):
y = np.array(raw_data.iloc[:, 0])
 out_y = keras.utils.to_categorical(y, num_classes)
 x = np.array(raw_data.iloc[:,1:])
 num_images = raw_data.shape[0]
out_x = x.reshape(num_images, img_rows, img_cols, 1)
 out_x = out_x / 255
return out_x, out_y
pred_test_y =(4 * pred_glove_test_y + pred_fasttext_test_y + 3 * pred_paragram_test_y + 2 * pred_cnn_test_y)/ 10.0
pred_test_y =(pred_test_y > best_thresh ).astype(int)
 out_df = pd.DataFrame({"qid":test_df["qid"].values})
 out_df['prediction'] = pred_test_y
out_df.to_csv("submission.csv", index=False )<define_variables>
datagen = ImageDataGenerator(
 featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=10,
zoom_range = 0.2,
shear_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=False,
vertical_flip=False,
)
embed_size = 300
max_features = 95000
maxlen = 70<import_modules>
train_x, train_y = raw_to_img_array(train_data)
 train_x,val_x,train_y,val_y=train_test_split(train_x, train_y, test_size=0.2)
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
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>
kannada_model = Sequential()
kannada_model.add(Conv2D(128, kernel_size=(4, 4),
activation='relu',padding="same",
input_shape=(img_rows, img_cols, 1)))
 kannada_model.add(BatchNormalization())
 kannada_model.add(MaxPool2D(pool_size=2,padding="valid"))
kannada_model.add(Dropout(0.25))
kannada_model.add(Conv2D(256,kernel_size=(4, 4),padding="same", activation='relu'))
kannada_model.add(BatchNormalization())
 kannada_model.add(MaxPool2D(pool_size=2,padding="valid"))
kannada_model.add(Dropout(0.25))
kannada_model.add(Conv2D(512,kernel_size=(4, 4),padding="same", activation='relu'))
kannada_model.add(BatchNormalization())
 kannada_model.add(MaxPool2D(pool_size=2,padding="valid"))
kannada_model.add(Dropout(0.25))
kannada_model.add(Flatten())
 kannada_model.add(Dense(1024, activation='relu'))
kannada_model.add(BatchNormalization())
 kannada_model.add(Dropout(0.4))
kannada_model.add(Dense(256, activation='relu'))
kannada_model.add(BatchNormalization())
 kannada_model.add(Dropout(0.4))
kannada_model.add(Dense(num_classes, activation='softmax'))
kannada_model.compile(loss=keras.losses.categorical_crossentropy,
optimizer="adam",
metrics=['accuracy'])
 learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', patience=5, verbose=1, factor=0.5, min_lr=0.00001)
 checkpoint = ModelCheckpoint("bestmodel.model", monitor='val_acc', verbose=1, save_best_only=True)
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["question_text"] = train_df["question_text"].fillna(" ")
 train_df["question_len"] = train_df["question_text"].apply(lambda x: len(x))
test_df["question_text"] = test_df["question_text"].fillna(" ")
 test_df["question_len"] = test_df["question_text"].apply(lambda x: len(x))
train_df, val_df = train_test_split(train_df, test_size=0.08, random_state=2018)
 train_X = train_df["question_text"].values
val_X = val_df["question_text"].values
test_X = test_df["question_text"].values
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]
train_X_len = train_df["question_len"].values[trn_idx]
val_X_len = val_df["question_len"].values[val_idx]
test_X_len = test_df["question_len"].values
return train_X, val_X, test_X, train_y, val_y, tokenizer.word_index, train_X_len, val_X_len, test_X_len<statistical_test>
batch_size=64
kannada_model.fit_generator(datagen.flow(train_x,train_y, batch_size=batch_size),
steps_per_epoch=train_x.shape[0]//batch_size,
epochs=50,callbacks= [checkpoint,learning_rate_reduction],
validation_data=datagen.flow(val_x,val_y,batch_size=batch_size),
validation_steps = val_x.shape[0]//batch_size )
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 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 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 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>
test_x = np.array(test_data.iloc[:,1:])
 test_index = np.array(test_data.iloc[:,0])
 num_images = test_data.shape[0]
test_x = test_x.reshape(num_images, img_rows, img_cols, 1)
 test_x = test_x / 255
kannada_model.load_weights('bestmodel.model')
 preds = kannada_model.predict(test_x )
class Attention(Layer):
def __init__(self, step_dim,
W_regularizer=None, b_regularizer=None,
W_constraint=None, b_constraint=None,
bias=True, **kwargs):
self.supports_masking = True
self.init = initializers.get('glorot_uniform')
 self.W_regularizer = regularizers.get(W_regularizer)
 self.b_regularizer = regularizers.get(b_regularizer)
 self.W_constraint = constraints.get(W_constraint)
 self.b_constraint = constraints.get(b_constraint)
 self.bias = bias
self.step_dim = step_dim
self.features_dim = 0
super(Attention, self ).__init__(**kwargs)
 def build(self, input_shape):
assert len(input_shape)== 3
self.W = self.add_weight(( input_shape[-1],),
initializer=self.init,
name='{}_W'.format(self.name),
regularizer=self.W_regularizer,
constraint=self.W_constraint)
 self.features_dim = input_shape[-1]
if self.bias:
self.b = self.add_weight(( input_shape[1],),
initializer='zero',
name='{}_b'.format(self.name),
regularizer=self.b_regularizer,
constraint=self.b_constraint)
 else:
self.b = None
self.built = True
def compute_mask(self, input, input_mask=None):
return None
def call(self, x, mask=None):
features_dim = self.features_dim
step_dim = self.step_dim
eij = K.reshape(K.dot(K.reshape(x,(-1, features_dim)) ,
K.reshape(self.W,(features_dim, 1))),(-1, step_dim))
if self.bias:
eij += self.b
eij = K.tanh(eij)
 a = K.exp(eij)
 if mask is not None:
a *= K.cast(mask, K.floatx())
 a /= K.cast(K.sum(a, axis=1, keepdims=True)+ K.epsilon() , K.floatx())
 a = K.expand_dims(a)
 weighted_input = x * a
return K.sum(weighted_input, axis=1)
 def compute_output_shape(self, input_shape):
return input_shape[0], self.features_dim<define_search_model>
submissions = np.zeros(( len(preds),2),dtype=int)
 for ix in range(preds.shape[0]):
submissions[ix][0] = test_index[ix]
submissions[ix][1] = np.argmax(preds[ix])
 print(submissions )
<predict_on_test><EOS> 
submissions_pd = pd.DataFrame(data=submissions,columns=["id","label"])
 submissions_pd.head()
submissions_pd.to_csv("submissions.csv",index=False )