Kaggle competition: Recursion Cellular Image Classification
<SOS> metric: CategorizationAccuracy Kaggle data source: recursion-cellular-image-classification<string_transform>
!pip install efficientnet
def known_contractions(embed):
known = []
for contract in contraction_mapping:
if contract in embed:
known.append(contract)
 return known<string_transform>
epochs_0 = 10
epochs_1 = 28
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<drop_column>
import json
import math
import os
import cv2
import tensorflow as tf
from PIL import Image
import numpy as np
import keras
from keras import layers
from keras.applications import MobileNetV2
from keras.callbacks import Callback, ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model, load_model
from keras.layers import GlobalAveragePooling2D, Dense, Dropout, BatchNormalization, concatenate, Input, add
from keras.optimizers import Adam
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import cohen_kappa_score, accuracy_score
import scipy
from tqdm import tqdm
def unknown_punct(embed, punct):
unknown = ''
for p in punct:
if p not in embed:
unknown += p
unknown += ' '
return unknown<categorify>
train_df = pd.read_csv('.. /input/recursion-cellular-image-classification/train.csv')
 test_df = pd.read_csv('.. /input/recursion-cellular-image-classification/test.csv')
 train_df['category'] = train_df['experiment'].apply(lambda x: x.split('-')[0])
 test_df['category'] = test_df['experiment'].apply(lambda x: x.split('-')[0])
 train_target_df = pd.get_dummies(train_df['sirna'])
 print(train_df.shape)
 print(test_df.shape)
 print(train_target_df.shape)
 train_df.head()
def clean_special_chars(text, punct):
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<categorify>
train_idx, val_idx = train_test_split(
 train_df.index, test_size=0.15, random_state=1337 
)
 print(train_idx.shape)
 print(val_idx.shape )
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 = ": )(-!?|;'$&/[]>%=
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<categorify>
class DataGenerator(keras.utils.Sequence):
'Generates data for Keras'
def __init__(self, list_IDs, df, target_df=None, mode='fit',
base_path = '.. /input/recursion-cellular-image-classification-224-jpg/train/train',
batch_size=32, dim=(224, 224), n_channels=3,
n_classes=5, random_state=1337, shuffle=True):
self.dim = dim
self.batch_size = batch_size
self.df = df
self.mode = mode
self.base_path = base_path
self.target_df = target_df
self.list_IDs = list_IDs
self.n_channels = n_channels
self.n_classes = n_classes
self.shuffle = shuffle
self.random_state = random_state
self.on_epoch_end()
def __len__(self):
'Denotes the number of batches per epoch'
return int(np.floor(len(self.list_IDs)/ self.batch_size))
def __getitem__(self, index):
'Generate one batch of data'
indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
list_IDs_batch = [self.list_IDs[k] for k in indexes]
X = self.__generate_X(list_IDs_batch)
 if self.mode == 'fit':
y = self.__generate_y(list_IDs_batch)
 return X, y
elif self.mode == 'predict':
return X
else:
raise AttributeError('The parameter mode should be set to "fit" or "predict".')
 def on_epoch_end(self):
'Updates indexes after each epoch'
self.indexes = np.arange(len(self.list_IDs))
if self.shuffle == True:
np.random.seed(self.random_state)
 np.random.shuffle(self.indexes)
 def __generate_X(self, list_IDs_batch):
'Generates data containing batch_size samples'
X_1 = np.empty(( self.batch_size, *self.dim, self.n_channels))
X_2 = np.empty(( self.batch_size, *self.dim, self.n_channels))
for i, ID in enumerate(list_IDs_batch):
ext = 'jpeg'
code = self.df['id_code'].iloc[ID]
img_path_1 = f"{self.base_path}/{code}_s1.{ext}"
img_path_2 = f"{self.base_path}/{code}_s2.{ext}"
img1 = self.__load_image(img_path_1)
 img2 = self.__load_image(img_path_2)
 X_1[i,] = img1
X_2[i,] = img2
return [X_1, X_2]
def __generate_y(self, list_IDs_batch):
y = np.empty(( self.batch_size, self.n_classes), dtype=int)
 for i, ID in enumerate(list_IDs_batch):
sirna = self.target_df.iloc[ID]
y[i, ] = sirna
return y
def __load_image(self, img_path):
img = cv2.imread(img_path)
 img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
 img = img.astype(np.float32)/ 255.
 return img
def correct_spelling(x, dic):
for word in dic.keys() :
x = x.replace(word, dic[word])
 return x<feature_engineering>
BATCH_SIZE = 32
train_generator = DataGenerator(
 train_idx,
df=train_df,
target_df=train_target_df,
batch_size=BATCH_SIZE,
n_classes=train_target_df.shape[1] 
)
 val_generator = DataGenerator(
 val_idx,
df=train_df,
target_df=train_target_df,
batch_size=BATCH_SIZE,
n_classes=train_target_df.shape[1] 
)
 test_generator = DataGenerator(
 test_df.index,
df=test_df,
batch_size=1,
shuffle=False,
mode='predict',
n_classes=train_target_df.shape[1],
base_path='.. /input/recursion-cellular-image-classification-224-jpg/test/test/'
)
def run_text_preprocessing(df, textCol, outputFileName):
mispell_map, contraction_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))
****** 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(df)
 del(mispell_map)
 del(contraction_map)
 del(punct)
 gc.collect()<load_from_csv>
def build_model(n_classes):
backbone = efficientnet.EfficientNetB1(
 weights='imagenet',
include_top=False,
input_shape=(224, 224, 3)
)
 im_inp_1 = Input(shape=(224, 224, 3))
im_inp_2 = Input(shape=(224, 224, 3))
x1 = backbone(im_inp_1)
 x2 = backbone(im_inp_2)
 x1 = GlobalAveragePooling2D()(x1)
 x2 = GlobalAveragePooling2D()(x2)
 out = add([x1, x2])
 out = Dropout(0.5 )(out)
 out = Dense(n_classes, activation='softmax' )(out)
 model = Model(inputs=[im_inp_1, im_inp_2], outputs=out)
 model.compile(Adam(0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
 return model
train = pd.read_csv(".. /input/train.csv")
 test = pd.read_csv(".. /input/test.csv" )<load_from_csv>
model = build_model(n_classes=train_target_df.shape[1])
 model.summary()
train = pd.read_csv(".. /input/train.csv")
 test = pd.read_csv(".. /input/test.csv" )<categorify>
checkpoint = ModelCheckpoint(
 'model.h5',
monitor='val_loss',
verbose=0,
save_best_only=True,
save_weights_only=False,
mode='auto' 
)
 history = model.fit_generator(
 train_generator,
validation_data=val_generator,
callbacks=[checkpoint],
use_multiprocessing=False,
workers=1,
epochs=epochs_0
)
run_text_preprocessing(train, "question_text", "train")
 run_text_preprocessing(test, "question_text", "test" )<save_to_csv>
categories = train_df['category'].unique()
output_df = []
for category in categories:
category_df = train_df[train_df['category'] == category]
cat_test_df = test_df[test_df['category'] == category].copy()
print('
' + '=' * 40)
 print("CURRENT CATEGORY:", category)
 print('-' * 40)
 train_idx, val_idx = train_test_split(
 category_df.index,
random_state=1337,
test_size=0.15 
)
 train_generator = DataGenerator(
 train_idx,
df=train_df,
target_df=train_target_df,
batch_size=BATCH_SIZE,
n_classes=train_target_df.shape[1] 
)
 val_generator = DataGenerator(
 val_idx,
df=train_df,
target_df=train_target_df,
batch_size=BATCH_SIZE,
n_classes=train_target_df.shape[1] 
)
 test_generator = DataGenerator(
 cat_test_df.index,
df=test_df,
batch_size=1,
shuffle=False,
mode='predict',
n_classes=train_target_df.shape[1],
base_path='.. /input/recursion-cellular-image-classification-224-jpg/test/test/' 
)
 model.load_weights('model.h5')
 model.compile(
 Adam(0.0001),
loss='categorical_crossentropy',
metrics=['accuracy'] 
)
 checkpoint = ModelCheckpoint(
 f'model_{category}.h5',
monitor='val_loss',
verbose=0,
save_best_only=True,
save_weights_only=False,
mode='auto' 
)
 history_category = model.fit_generator(
 train_generator,
validation_data=val_generator,
callbacks=[checkpoint],
use_multiprocessing=False,
workers=1,
verbose=2,
epochs=epochs_1 
)
 y_pred = model.predict_generator(
 test_generator,
workers=2,
use_multiprocessing=True,
verbose=1 
)
 cat_test_df['sirna'] = y_pred.argmax(axis=1)
 output_df.append(cat_test_df[['id_code', 'sirna']])
 with open(f'history_{category}.json', 'w')as f:
json.dump(history_category.history, f )
df_texts = pd.concat([train.drop('target', axis=1),test])
 df_texts.to_csv("texts_processed.csv" )<drop_column>
output_df = pd.concat(output_df)
 output_df.to_csv('submission.csv', index=False )