Kaggle competition: Flower Classification with TPUs
train.Parch.value_counts()<define_search_space>
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
print_percentage(train,'Parch',[0,1,2,3,4,5,6] )<count_values>
sys.stdout = open("/kaggle/working/logoutput.txt", "w")
 def setup_tf_logging() :
tf.get_logger().handlers = []
tf.get_logger().addHandler(logging.StreamHandler(sys.stdout))
setup_tf_logging()
train.SibSp.value_counts()<define_search_space>
from kaggle_datasets import KaggleDatasets
print_percentage(train,'SibSp',[0,1,2,3,4,5,8] )<count_missing_values>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
print('Amount of missing data in Fare for training set:', train.Fare.isnull().sum())
 print('Amount of missing data in Fare for test set:', Test.Fare.isnull().sum() )<filter>
IMAGE_SIZE = [331, 331]
IMAGE_SIZE_1 = [512,512]
EPOCHS = 40
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
GCS_PATH_1 = GCS_PATH_SELECT[IMAGE_SIZE_1[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 TRAINING_FILENAMES2 = tf.io.gfile.glob(GCS_PATH_1 + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']
Test[Test['Fare'].isnull() ]<categorify>
FULL_TRAINING=True
if FULL_TRAINING:
TRAINING_FILENAMES+=VALIDATION_FILENAMES
TRAINING_FILENAMES
median_fare = Test.groupby(['Pclass', 'Parch'] ).Fare.median() [3][0]
Test['Fare'] = Test['Fare'].fillna(median_fare )<count_missing_values>
np.set_printoptions(threshold=15, linewidth=80)
 def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red=False, titlesize=16):
plt.subplot(*subplot)
 plt.axis('off')
 plt.imshow(image)
 if len(title)> 0:
plt.title(title, fontsize=int(titlesize)if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2]+1)
 def display_batch_of_images(databatch, predictions=None):

 images, labels = batch_to_numpy_images_and_labels(databatch)
 if labels is None:
labels = [None for _ in enumerate(images)]
rows = int(math.sqrt(len(images)))
 cols = len(images)//rows
FIGSIZE = 13.0
SPACING = 0.1
subplot=(rows,cols,1)
 if rows < cols:
plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))
else:
plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))
for i,(image, label)in enumerate(zip(images[:rows*cols], labels[:rows*cols])) :
title = '' if label is None else CLASSES[label]
correct = True
if predictions is not None:
title, correct = title_from_label_and_target(predictions[i], label)
 dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3
subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)
 plt.tight_layout()
if label is None and predictions is None:
plt.subplots_adjust(wspace=0, hspace=0)
 else:
plt.subplots_adjust(wspace=SPACING, hspace=SPACING)
 plt.show()
def display_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='Reds')
 ax.set_xticks(range(len(CLASSES)))
 ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
 ax.set_yticks(range(len(CLASSES)))
 ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
 titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
 if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
 if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
 if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
plt.show()
def display_training_curves(training, validation, title, subplot):
if subplot%10==1:
plt.subplots(figsize=(10,10), facecolor='
plt.tight_layout()
ax = plt.subplot(subplot)
 ax.set_facecolor('
ax.plot(training)
 ax.plot(validation)
 ax.set_title('model '+ title)
 ax.set_ylabel(title)
 ax.set_xlabel('epoch')
 ax.legend(['train', 'valid.'] )
print('Amount of missing data in Embarked for train:', train.Embarked.isnull().sum())
 print('Amount of missing data in Embarked for test:', Test.Embarked.isnull().sum() )<filter>
from sklearn.utils import class_weight
train[train['Embarked'].isnull() ]<feature_engineering>
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))
def transform(image,label):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
rot = 15.* tf.random.normal([1],dtype='float32')
 shr = 5.* tf.random.normal([1],dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 h_shift = 16.* tf.random.normal([1],dtype='float32')
 w_shift = 16.* tf.random.normal([1],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3]),label
train['Embarked'] = train['Embarked'].fillna('S' )<count_missing_values>
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def decode_image2(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE_1, 3])
 return image
def decode_image3(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE_2, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_labeled_tfrecord2(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image2(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_labeled_tfrecord3(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image3(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def load_dataset2(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord2 if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def load_dataset3(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord3 if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 return image, label
def data_augment2(image, label):
image = tf.image.random_flip_left_right(image)
 print(f"Resizing image with size {image.shape[1]} to {IMAGE_SIZE[0]}")
 image = tf.image.random_crop(image, size=[IMAGE_SIZE[0], IMAGE_SIZE[0],3])
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset2 = load_dataset2(TRAINING_FILENAMES2, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset2 = dataset2.map(data_augment2, num_parallel_calls=AUTO)
 dataset = dataset.concatenate(dataset2)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_class_weights() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset2 = load_dataset2(TRAINING_FILENAMES2, labeled=True)
 dataset = dataset.concatenate(dataset2)
 flower_counts=[]
for images, labels in dataset:
flower_counts.append(labels)
 print(np.array(flower_counts))
print(np.unique(flower_counts,return_counts=True))
class_weights=class_weight.compute_class_weight('balanced',np.unique(flower_counts),np.array(flower_counts))
print(f'class_weights:{class_weights}')
 return class_weights
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)+count_data_items(TRAINING_FILENAMES2)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
print('Amount of missing data in Age for train:', train.Age.isnull().sum())
 print('Amount of missing data in Age for test:', Test.Age.isnull().sum() )<data_type_conversions>
get_training_dataset()
copy5 = train.copy()
missing_age_rows2 = copy5.Age.isna()
missing_age_rows2 
<groupby>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
age_by_pclass_SibSp = copy5.groupby(['Pclass', 'SibSp'] ).median() ['Age']
age_by_pclass_SibSp<categorify>
display_batch_of_images(next(train_batch))
age_by_pclass_SibSp[1].index.tolist()
age_by_pclass_SibSp[3][8] = age_by_pclass_SibSp[3][5]
age_by_pclass_SibSp<feature_engineering>
class_weights=get_class_weights()
copy5['Age'] = copy5.groupby(['Pclass', 'SibSp'])[
'Age'].apply(lambda x: x.fillna(x.median()))
copy5['Age'] = copy5.Age.fillna(11)
 copy5.info()<create_dataframe>
!pip install -q efficientnet
copy2 = train.copy()
copy2['Age'].fillna(copy2['Age'].median() ,inplace = True )<define_variables>
from efficientnet.tfkeras import EfficientNetB7
train = copy5<feature_engineering>
with strategy.scope() :
pretrained_model_1 = EfficientNetB7(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 pretrained_model_1.trainable = True
model = tf.keras.Sequential([
pretrained_model_1,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()
test_age_by_pclass_SibSp = Test.groupby(['Pclass', 'SibSp'] ).median() ['Age']
test_age_by_pclass_SibSp
Test['Age'] = Test.groupby(['Pclass', 'SibSp'])['Age'].apply(lambda x: x.fillna(x.median()))
Test.info()<define_variables>
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 6
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = np.random.random_sample() * 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 )
def detect_outliers(df, n, features):
outliers_indices = []
for col in features:
Q1 = np.nanpercentile(df[col], 25)
 Q3 = np.nanpercentile(df[col], 75)
 IQR = Q3 - Q1
outlier_step = 1.5 * IQR
outlier_list_col = df[(df[col] < Q1 - outlier_step)
 |(df[col] > Q3 + outlier_step)].index
print(col,Q1-outlier_step,Q3+outlier_step)
 outliers_indices.extend(outlier_list_col)
 outliers_indices = Counter(outliers_indices)
 multiple_outliers = list(k for k, v in outliers_indices.items() if v > n)
 return multiple_outliers
Outliers_to_drop = detect_outliers(train, 2, ["Age", "SibSp", "Parch", "Fare"])
<filter>
if not FULL_TRAINING:
es_callback = tf.keras.callbacks.EarlyStopping(monitor="val_sparse_categorical_accuracy",min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True)
 else:
es_callback = tf.keras.callbacks.EarlyStopping(monitor="sparse_categorical_accuracy",min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True)
Outliers_to_drop
train.loc[Outliers_to_drop]<categorify>
if not FULL_TRAINING:
history = model.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, validation_data=get_validation_dataset() ,callbacks = [lr_callback, es_callback],class_weight=class_weights)
 else:
history = model.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks = [lr_callback],class_weight=class_weights)
def outlier_treatment(datacolumn):
sorted(datacolumn)
 Q1, Q3 = np.nanpercentile(datacolumn,[25,75])
 IQR = Q3-Q1
lower_range = Q1-(1.5*IQR)
 upper_range = Q3+(1.5*IQR)
 return lower_range, upper_range
print('Upper and Lower bound for Age:',outlier_treatment(train.Age), sep = '
')
 print('Upper and Lower bound for Fare:',outlier_treatment(train.Fare), sep = '
')
 print('Upper and Lower bound for Parch:',outlier_treatment(train.Parch), sep = '
')
 print('Upper and Lower bound for Siblings:',outlier_treatment(train.SibSp), sep = '
')
<count_unique_values>
print('Number of Unique values for Name is', len(train.Name.unique()))
print('Number of Unique values for PassengerID is', len(train.PassengerId.unique()))
print('Number of Unique values for Fare is', len(train.Fare.unique()))
print('Number of Unique values for Survived is', len(train.Survived.unique()))
print('Number of Unique values for Pclass is', len(train.Pclass.unique()))
print('Number of Unique values for Parch is', len(train.Parch.unique()))
print('Number of Unique values for SibSp is', len(train.SibSp.unique()))
print('Number of Unique values for Embarked is', len(train.Embarked.unique()))
print('Number of Unique values for Cabin is', len(train.Cabin.unique()))
print('Number of Unique values for Sex is', len(train.Sex.unique()))
print('Number of Unique values for Ticket is', len(train.Ticket.unique()))<drop_column>
train.drop(["PassengerId"],inplace=True,axis=1)
 Test.drop(["PassengerId"],inplace=True,axis=1 )<drop_column>
train.drop(["Ticket"],inplace=True,axis=1)
 Test.drop(["Ticket"],inplace=True,axis=1 )<string_transform>
with strategy.scope() :
pretrained_model_3 = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model_3.trainable = True
model_3 = tf.keras.Sequential([
pretrained_model_3,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model_3.compile(
 tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model_3.summary()
def name_sep(data):
families=[]
titles = []
new_name = []
for i in range(len(data)) :
name = data.iloc[i]
if '(' in name:
name_no_bracket = name.split('(')[0]
else:
name_no_bracket = name
family = name_no_bracket.split(",")[0]
title = name_no_bracket.split(",")[1].strip().split(" ")[0]
for c in string.punctuation:
name = name.replace(c,"" ).strip()
family = family.replace(c,"" ).strip()
title = title.replace(c,"" ).strip()
families.append(family)
 titles.append(title)
 new_name.append(name)
 return families, titles, new_name<feature_engineering>
if not FULL_TRAINING:
history_3 = model_3.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, validation_data=get_validation_dataset() ,callbacks = [lr_callback, es_callback], class_weight=class_weights)
 else:
history_3 = model_3.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks = [lr_callback],class_weight=class_weights )
train['Surname'], train['Title'], train['Newname'] = name_sep(train.Name)
 Test['Surname'], Test['Title'], Test['Newname'] = name_sep(Test.Name)
 train.head()
train.Title.value_counts()<count_values>
train['Title'] = train['Title'].replace(['Ms', 'Mlle'],'Miss')
 train['Title'] = train['Title'].replace(['Mme'],'Mrs')
 train['Title'] = train['Title'].replace(['Dr','Rev','the','Jonkheer','Lady','Sir', 'Don'],'Nobles')
 train['Title'] = train['Title'].replace(['Major','Col', 'Capt'],'Navy')
 train.Title.value_counts()<groupby>
nobles_survival = train[train.Title == "Nobles"].groupby(['Sex'] ).Survived.value_counts()
nobles_survival<count_values>
if not FULL_TRAINING:
cmdataset = get_validation_dataset(ordered=True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
pred_score=[]
dense_pred=model_3.predict(images_ds)
 efn_pred=model.predict(images_ds)
 for model_wt in np.linspace(0,1,100):
cm_probabilities= model_wt*dense_pred +(1-model_wt)*efn_pred
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 pred_score.append(f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro'))
plt.plot(pred_score)
 best_model_wt=np.argmax(pred_score)/100
cm_probabilities= best_model_wt*dense_pred +(1-best_model_wt)*efn_pred
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 else:
best_model_wt=0.56
Test.Title.value_counts()
Test['Title'] = Test['Title'].replace(['Ms','Dona'],'Miss')
 Test['Title'] = Test['Title'].replace(['Dr','Rev'],'Nobles')
 Test['Title'] = Test['Title'].replace(['Col'],'Navy')
 Test.Title.value_counts()<count_missing_values>
print(f'Best model weight {best_model_wt}' )
print('Missing values in Train set:', train.Cabin.isnull().sum())
 print('Missing values in Test set:', Test.Cabin.isnull().sum() )<count_values>
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
<feature_engineering><EOS> 
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities =(model_3.predict(test_ds)*best_model_wt)+(model.predict(test_ds)*best_model_wt)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 !head submission.csv