Kaggle competition: Plant Pathology 2020 - FGVC7
<SOS> metric: MCAUC Kaggle data source: plant-pathology-2020-fgvc7<count_values>
train_info.image_name.value_counts().max()<count_values>
!pip install -q efficientnet
test_info.image_name.value_counts().max()<count_values>
import math, re, os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from kaggle_datasets import KaggleDatasets
import tensorflow as tf
import tensorflow.keras.layers as L
from sklearn import metrics
from sklearn.model_selection import train_test_split
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
from tensorflow.keras.layers import Flatten,Dense,Dropout,BatchNormalization
from tensorflow.keras.models import Model,Sequential
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalization
from keras.optimizers import Adam,SGD,Adagrad,Adadelta,RMSprop
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint
train_info.patient_id.value_counts().max()<count_values>
AUTO = tf.data.experimental.AUTOTUNE
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
 except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync )
test_info.patient_id.value_counts().max()<feature_engineering>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('plant-pathology-2020-fgvc7')
 EPOCHS = 40
BATCH_SIZE = 8 * strategy.num_replicas_in_sync
200/test_info.shape[0] * 100<count_unique_values>
def format_path(st):
return GCS_DS_PATH + '/images/' + st + '.jpg'
train_info.groupby("benign_malignant" ).target.nunique()<groupby>
train = pd.read_csv('/kaggle/input/plant-pathology-2020-fgvc7/train.csv')
 test = pd.read_csv('/kaggle/input/plant-pathology-2020-fgvc7/test.csv')
 sub = pd.read_csv('/kaggle/input/plant-pathology-2020-fgvc7/sample_submission.csv')
 train_paths = train.image_id.apply(format_path ).values
test_paths = test.image_id.apply(format_path ).values
train_labels = train.loc[:, 'healthy':].values
patient_ages_table_train = train_info.groupby(["patient_id", "age_approx"] ).size() / train_info.groupby("patient_id" ).size()
patient_ages_table_train = patient_ages_table_train.unstack().transpose()
patient_ages_table_test = test_info.groupby(["patient_id", "age_approx"] ).size() / test_info.groupby("patient_id" ).size()
patient_ages_table_test = patient_ages_table_test.unstack().transpose()
patient_with_known_ages_train = train_info[train_info.patient_id.isin(patient_ages_table_train.columns.values)]
sorted_patients_train = patient_with_known_ages_train.patient_id.value_counts().index.values
patient_with_known_ages_test = test_info[test_info.patient_id.isin(patient_ages_table_test.columns.values)]
sorted_patients_test = patient_with_known_ages_test.patient_id.value_counts().index.values
fig, ax = plt.subplots(2,1, figsize=(20,20))
sns.heatmap(patient_ages_table_train[sorted_patients_train], cmap="Reds", ax=ax[0], cbar=False);
ax[0].set_title("Image coverage in % per patient and age in train data");
sns.heatmap(patient_ages_table_test[sorted_patients_test], cmap="Blues", ax=ax[1], cbar=False);
ax[1].set_title("Image coverage in % per patient and age in test data");
ax[0].set_xlabel("")
 ax[1].set_xlabel("");<feature_engineering>
img_size = 768
def decode_image(filename, label=None, image_size=(img_size, img_size)) :
bits = tf.io.read_file(filename)
 image = tf.image.decode_jpeg(bits, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.image.resize(image, image_size)
 if label is None:
return image
else:
return image, label
def data_augment(image, label=None, seed=2020):
image = tf.image.random_flip_left_right(image, seed=seed)
 image = tf.image.random_flip_up_down(image, seed=seed)
 if label is None:
return image
else:
return image, label
patient_gender_train = train_info.groupby("patient_id" ).sex.unique().apply(lambda l: l[0])
 patient_gender_test = test_info.groupby("patient_id" ).sex.unique().apply(lambda l: l[0])
 train_patients = pd.DataFrame(index=patient_gender_train.index.values, data=patient_gender_train.values, columns=["sex"])
 test_patients = pd.DataFrame(index=patient_gender_test.index.values, data=patient_gender_test.values, columns=["sex"])
 train_patients.loc[:, "num_images"] = train_info.groupby("patient_id" ).size()
test_patients.loc[:, "num_images"] = test_info.groupby("patient_id" ).size()
train_patients.loc[:, "min_age"] = train_info.groupby("patient_id" ).age_approx.min()
train_patients.loc[:, "max_age"] = train_info.groupby("patient_id" ).age_approx.max()
test_patients.loc[:, "min_age"] = test_info.groupby("patient_id" ).age_approx.min()
test_patients.loc[:, "max_age"] = test_info.groupby("patient_id" ).age_approx.max()
train_patients.loc[:, "age_span"] = train_patients["max_age"] - train_patients["min_age"]
test_patients.loc[:, "age_span"] = test_patients["max_age"] - test_patients["min_age"]
train_patients.loc[:, "benign_cases"] = train_info.groupby(["patient_id", "benign_malignant"] ).size().loc[:, "benign"]
train_patients.loc[:, "malignant_cases"] = train_info.groupby(["patient_id", "benign_malignant"] ).size().loc[:, "malignant"]
train_patients["min_age_malignant"] = train_info.groupby(["patient_id", "benign_malignant"] ).age_approx.min().loc[:, "malignant"]
train_patients["max_age_malignant"] = train_info.groupby(["patient_id", "benign_malignant"] ).age_approx.max().loc[:, "malignant"]<sort_values>
train_dataset =(
 tf.data.Dataset 
.from_tensor_slices(( train_paths, train_labels)) 
.map(decode_image, num_parallel_calls=AUTO)
.map(data_augment, num_parallel_calls=AUTO)
.repeat() 
.shuffle(512)
.batch(BATCH_SIZE)
.prefetch(AUTO)
)
 test_dataset =(
 tf.data.Dataset 
.from_tensor_slices(test_paths)
.map(decode_image, num_parallel_calls=AUTO)
.batch(BATCH_SIZE)
 )
train_patients.sort_values(by="malignant_cases", ascending=False ).head()<define_variables>
LR_START = 0.00001
LR_MAX = 0.0001 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 15
LR_SUSTAIN_EPOCHS = 3
LR_EXP_DECAY =.8
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]))
example_files = os.listdir(basepath + "train/")[0:2]
example_files<feature_engineering>
def get_model() :
base_model = InceptionResNetV2(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(img_size, img_size, 3))
x = base_model.output
predictions = Dense(train_labels.shape[1], activation="softmax" )(x)
 return Model(inputs=base_model.input, outputs=predictions)
 with strategy.scope() :
model1 = get_model()
model1.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['categorical_accuracy'])
 model1.load_weights("/kaggle/input/tf-zoo-models-on-tpu-inceptionresnetv2/InceptionResNetV2.h5" )
train_info["dcm_path"] = basepath + "train/" + train_info.image_name + ".dcm"
test_info["dcm_path"] = basepath + "test/" + test_info.image_name + ".dcm"<load_from_csv>
def get_model() :
base_model = EfficientNetB7(weights='noisy-student',
include_top=False, pooling='avg',
input_shape=(img_size, img_size, 3))
x = base_model.output
predictions = Dense(train_labels.shape[1], activation="softmax" )(x)
 return Model(inputs=base_model.input, outputs=predictions)
 with strategy.scope() :
model2 = get_model()
model2.compile(optimizer='nadam', loss='categorical_crossentropy',metrics=['categorical_accuracy'])
 model2.load_weights("/kaggle/input/tf-zoo-models-on-tpu-efficientnetb7/EfficientNetB7.h5" )
<feature_engineering><EOS> 
probs =(model1.predict(test_dataset)+model2.predict(test_dataset)) /2
sub.loc[:, 'healthy':] = probs
sub.to_csv('submission.csv', index=False)
 sub.head()