Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<groupby>
!pip install -q efficientnet
data['isChild'] =np.where(data.ImputedAge<18, 'Child','Adult')
 data.groupby('Survived' ).isChild.value_counts()<count_values>
print('TensorFlow version', tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
data['lastName'] =(data.Name.str.split(',', expand = True)) [:][0]
data['name_title'] =(data.Name.str.split('.',expand = True)) [:][0].str.split(',', expand = True)[:][1]
titles = data.name_title.value_counts().keys().tolist()
title_freq = data.name_title.value_counts().tolist()
miss_titles = [' Mme', ' Ms', ' Mlle']
rare_titles = [' Dr', ' Rev', ' Major', ' Col', ' Don', ' Capt', ' Sir', ' Lady', ' Jonkheer', ' the Countess', ' Dona']
data.name_title.replace(rare_titles,' Rare Titles', inplace = True)
 data.name_title.replace(miss_titles,' Miss', inplace = True)
(data.groupby('Sex' ).name_title.value_counts())
<prepare_x_and_y>
start_time = datetime.now()
print('Time now is', start_time)
 end_training_by_tdelta = timedelta(seconds=8400)
 this_run_file_prefix = start_time.strftime('%Y%m%d_%H%M_')
 print(this_run_file_prefix)
 IMAGE_SIZE = [224, 224]
EPOCHS = 12
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]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 MOREIMAGES_PATH_SELECT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
MOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
 INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
 OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
 OXFORD_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/oxford_102' + MOREIMAGES_PATH + '/*.tfrec')
 TENSORFLOW_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/tf_flowers' + MOREIMAGES_PATH + '/*.tfrec')
 ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES
print('----')
 TRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES + VALIDATION_FILENAMES
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']
features = ['Pclass', 'Sex', 'Fare_bin', 'ImputedAge_bin', 'fsize', 'isChild', 'name_title', 'isMother']
train_data = data.iloc[0:891,:]
test_data = data.iloc[891:1310,:]
y = train_data.Survived
X = train_data[features]<split>
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = LR_START
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY = 0.80
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = LR_START +(epoch *(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS)
 elif epoch <(LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS):
lr = LR_MAX
else:
lr = LR_MIN +(LR_MAX - LR_MIN)* LR_EXP_DECAY **(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)
 return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(30)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print(y )
X_train, X_val, y_train, y_val = train_test_split(X,y, random_state = 1 )<train_on_grid>
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.'] )
knn = KNeighborsClassifier()
n_neigh = [i for i in range(1,50,2)]
algorithm = ['auto']
weight = ['uniform','distance']
leaf = [i for i in range(1,50,5)]
param = {'n_neighbors':n_neigh, 'algorithm':algorithm, 'weights':weight, 'leaf_size':leaf}
grid = GridSearchCV(knn,param, cv = 10, scoring = 'accuracy')
 grid.fit(X_train, y_train)
 print(grid.best_score_)
 print(grid.best_estimator_)
 grid.best_estimator_.fit(X_train,y_train)
 grid_pred = grid.best_estimator_.predict(X_val)
 print("=== Confusion Matrix for Grid KNN ===")
 print(( confusion_matrix(y_val, grid_pred)))
 print("=== Classification Report ===")
 print(classification_report(y_val, grid_pred))<save_to_csv>
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 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_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 data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_saturation(image, 0, 2)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled = True)
 dataset = dataset.map(data_augment, num_parallel_calls = AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
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)
 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))
t_data = test_data.drop('Age', axis =1)
 t_data.Fare.fillna(t_data.Fare.median() , inplace = True)
 t_data_X = t_data[features]
predict_t_data =(grid.best_estimator_.predict(t_data_X ).astype(int))
submission = pd.DataFrame({"PassengerId": test_data["PassengerId"], "Survived": predict_t_data})
 submission.to_csv('submission_GridCV_KNN.csv', index=False )<set_options>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset)
pd.set_option('display.max_columns', 500)
 sns.set_style('whitegrid')
 simplefilter(action='ignore', category=FutureWarning)
 simplefilter(action='ignore', category=DeprecationWarning)
 %matplotlib inline<load_from_csv>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset)
train_data = pd.read_csv('/kaggle/input/titanic/train.csv')
 test_data = pd.read_csv('/kaggle/input/titanic/test.csv')
 train_data.head()<drop_column>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
submission = test_data['PassengerId']
train_data.drop(['PassengerId'], axis=1, inplace=True)
 test_data.drop(['PassengerId'], axis=1, inplace=True )<statistical_test>
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, restore_best_weights = True )
def get_stats(df):
lines = df.shape[0]
d_types = df.dtypes
count = df.count()
unique = df.apply(lambda x: x.unique().shape[0])
 nulls = df.isnull().sum()
null_ratio =(df.isnull().sum() /lines)*100
skew = df.skew()
names = ['data_types', 'count', 'unique', 'null', 'null_ratio']
temp_df = pd.concat([d_types, count, unique, nulls, null_ratio], axis=1)
 temp_df.columns = names
return temp_df
train_stats = get_stats(train_data)
 train_stats<compute_test_metric>
def create_VGG16_model() :
pretrained_model = tf.keras.applications.VGG16(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model
test_stats = get_stats(test_data)
 test_stats<drop_column>
def create_Xception_model() :
pretrained_model = tf.keras.applications.Xception(include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model
train_data.drop(['Ticket'], axis=1, inplace=True)
 test_data.drop(['Ticket'], axis=1, inplace=True )<data_type_conversions>
def create_DenseNet_model() :
pretrained_model = tf.keras.applications.DenseNet201(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model
test_data['Fare'].fillna(test_data['Fare'].median() , inplace=True)
 train_data['Embarked'].fillna(train_data['Embarked'].mode() [0], inplace=True )<count_values>
def create_EfficientNet_model() :
pretrained_model = efficientnet.EfficientNetB7(weights = 'noisy-student', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model
train_data['Cabin'].fillna(0, inplace=True)
 test_data['Cabin'].fillna(0, inplace=True)
 train_data.loc[(train_data['Cabin'] != 0), 'Cabin'] = 1
test_data.loc[(test_data['Cabin'] != 0), 'Cabin'] = 1
print(train_data['Cabin'].value_counts())
 print(test_data['Cabin'].value_counts() )<count_values>
def create_InceptionV3_model() :
pretrained_model = tf.keras.applications.InceptionV3(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model
train_data['Name'] = train_data['Name'].str.split(', ', expand=True)[1].str.split('.', expand=True)[0]
test_data['Name'] = test_data['Name'].str.split(', ', expand=True)[1].str.split('.', expand=True)[0]
train_title_mask =(train_data['Name'].value_counts() < 10)
 test_title_mask =(test_data['Name'].value_counts() < 10)
 train_data['Name'] = train_data['Name'].apply(lambda x: 'Misc' if train_title_mask.loc[x] == True else x)
 test_data['Name'] = test_data['Name'].apply(lambda x: 'Misc' if test_title_mask.loc[x] == True else x)
 print(train_data['Name'].value_counts())
 print(test_data['Name'].value_counts() )<feature_engineering>
def create_ResNet152_model() :
pretrained_model = tf.keras.applications.ResNet152V2(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model
train_data['F_size'] = train_data['Parch'] + train_data['SibSp'] + 1
test_data['F_size'] = test_data['Parch'] + test_data['SibSp'] + 1
train_data['Alone'] = 0
test_data['Alone'] = 0
train_data['Alone'].loc[(train_data['F_size'] == 1)] = 1
test_data['Alone'].loc[(test_data['F_size'] == 1)] = 1<drop_column>
def create_MobileNetV2_model() :
pretrained_model = tf.keras.applications.MobileNetV2(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model
train_data.drop(['Parch', 'SibSp'], axis=1, inplace=True)
 test_data.drop(['Parch', 'SibSp'], axis=1, inplace=True )<feature_engineering>
def create_InceptionResNetV2_model() :
pretrained_model = tf.keras.applications.InceptionResNetV2(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model
temp = train_data.groupby('Pclass')[['Age']].median()
temp
for i in range(3):
train_data.loc[(train_data['Age'].isnull() &(train_data['Pclass'] ==(i + 1))), 'Age'] = temp.loc[(i + 1), 'Age']
test_data.loc[(test_data['Age'].isnull() &(test_data['Pclass'] ==(i + 1))), 'Age'] = temp.loc[(i + 1), 'Age'] 
<compute_test_metric>
no_of_models = 2
models = [0] * no_of_models
start_model = 0
end_model = 2
model_indx_0 = start_model
model_indx_1 = start_model + 1
get_stats(test_data )<categorify>
val_probabilities = [0] * no_of_models
test_probabilities = [0] * no_of_models
all_probabilities = [0] * no_of_models
label = LabelEncoder()
train_data['Sex'] = label.fit_transform(train_data['Sex'])
 test_data['Sex'] = label.fit_transform(test_data['Sex'])
 train_data.head()<categorify>
with strategy.scope() :
for j in range(no_of_models):
models[j] = create_EfficientNet_model()
models[0].summary()
train_data[['Name', 'Embarked', 'F_size']] = train_data[['Name', 'Embarked', 'F_size']].astype(str)
 test_data[['Name', 'Embarked', 'F_size']] = test_data[['Name', 'Embarked', 'F_size']].astype(str)
 print(train_data.shape)
 train_data = pd.get_dummies(train_data)
 test_data = pd.get_dummies(test_data)
 print(train_data.shape)
 print(test_data.shape )<normalization>
def write_history(j):
history_dict = [0] * no_of_models
for i in range(j + 1):
if(historys[i] != 0):
history_dict[i] = historys[i].history
filename = './' + this_run_file_prefix + 'model_history_' + str(j)+ '.pkl'
pklfile = open(filename, 'ab')
 pickle.dump(history_dict, pklfile)
 pklfile.close()
pow_scale = PowerTransformer(method='yeo-johnson' ).fit(train_data[['Fare']])
 train_data[['Fare']] = pow_scale.transform(train_data[['Fare']])
 test_data[['Fare']] = pow_scale.transform(test_data[['Fare']])
 std_scale = StandardScaler().fit(train_data[['Age']])
 train_data[['Age']] = std_scale.transform(train_data[['Age']])
 test_data[['Age']] = std_scale.transform(test_data[['Age']] )<compute_train_metric>
EPOCHS = 25
historys = [0] * no_of_models
finished_models = 0
for j in range(start_model, end_model):
start_training = datetime.now()
print(start_training)
 time_from_start_program_tdelta = start_training - start_time
if time_from_start_program_tdelta > end_training_by_tdelta:
print(j, 'time limit for doing training over, get out')
 break
print('LR_EXP_DECAY:', LR_EXP_DECAY, '.LR_MAX:', LR_MAX)
 historys[j] = models[j].fit(get_training_dataset() , steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, validation_data = get_validation_dataset() , callbacks = [lr_callback, early_stop])
 write_history(j)
 filename = this_run_file_prefix + 'models_' + str(j)+ '.h5'
models[j].save(filename)
 gc.collect()
finished_models = j + 1
print(datetime.now())
def initial_score(mod, X, y, folds):
cv = KFold(n_splits=folds, shuffle=True)
 cv_estimate = cross_val_score(mod, X, y, cv=cv, scoring='accuracy', n_jobs=4)
 mean = np.mean(cv_estimate)
 std = np.std(cv_estimate)
 return mean, std<choose_model_class>
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()
svc_mod = SVC(probability=True)
 ada_mod = AdaBoostClassifier()
rfc_mod = RandomForestClassifier()
gbc_mod = GradientBoostingClassifier()
mlp_mod = MLPClassifier()<prepare_output>
test_ds = get_test_dataset(ordered = True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
names = ['SVC', 'AdaBoostClassifier', 'RandomForestClassifier', 'GradientBoostingClassifier', 'MLPClassifier']
mods = [svc_mod, ada_mod, rfc_mod, gbc_mod, mlp_mod]
results = pd.DataFrame(columns=['mean accuracy', 'std accuracy'], index=names)
 for name, mod in zip(names, mods):
mean, std = initial_score(mod, train_data, Label, 10)
 results.loc[name, 'mean accuracy'] = mean
results.loc[name, 'std accuracy'] = std
results<split>
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset)
 images, labels = next(batch )
cv = KFold(n_splits=10, shuffle=True)
 X_train, X_test, y_train, y_test = train_test_split(train_data, Label, test_size = 0.3 )<find_best_params>
print(datetime.now())
 for j in range(start_model, end_model):
val_probabilities[j] = models[j].predict(images_ds)
 test_probabilities[j] = models[j].predict(test_images_ds)
 all_probabilities[j] = models[j].predict(images)
 print(datetime.now())
svc_cf = SVC(probability=True)
 svc_cf.get_params()<define_search_space>
for j in range(start_model, finished_models):
display_training_curves(historys[j].history['loss'], historys[j].history['val_loss'], 'loss', 211)
 display_training_curves(historys[j].history['sparse_categorical_accuracy'], historys[j].history['val_sparse_categorical_accuracy'], 'accuracy', 212)
 for j in range(start_model, finished_models):
print('model number:', j, ', Train Accuracy:', max(historys[j].history['sparse_categorical_accuracy']), ', Validation Accuracy:', max(historys[j].history['val_sparse_categorical_accuracy']))
for j in range(start_model, finished_models):
print('model number:', j, ', Train Loss:', min(historys[j].history['loss']), ', Validation Loss:', min(historys[j].history['val_loss']))
param_grid = [{'C': [1, 10, 100, 1000], 'kernel': ['linear']},
{'C': [1, 10, 100, 1000], 'gamma': [1.0/50.0, 1.0/200.0, 1.0/500.0, 1.0/1000.0], 'kernel': ['rbf']}]
svc_class_grid = GridSearchCV(estimator=svc_cf,
param_grid=param_grid,
cv=cv,
scoring='accuracy',
return_train_score=True,
n_jobs=4,
verbose=1)
 svc_class_grid.fit(train_data, Label)
 svc_best_params = svc_class_grid.best_estimator_
print('GridsearchCV Best Score: {}'.format(svc_class_grid.best_score_))
print('
Tested HyperParameters Values')
 print('kernal: {}'.format(svc_class_grid.best_estimator_.kernel))
print('gamma: {}'.format(svc_class_grid.best_estimator_.gamma))
print('C: {}'.format(svc_class_grid.best_estimator_.C))<compute_train_metric>
def getFitPrecisionRecall(correct_labels, predictions):
score = f1_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 precision = precision_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 recall = recall_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 return score, precision, recall
svm_class = clone(svc_best_params)
 svm_class.fit(X_train, y_train)
 probabilities = svm_class.predict_proba(X_test)
 def score_model(probs, threshold):
return np.array([1 if x >= threshold else 0 for x in probs[:,1]])
 def print_metrics(labels, probs, threshold):
scores = score_model(probs, threshold)
 mets = metrics.precision_recall_fscore_support(labels, scores)
 conf = metrics.confusion_matrix(labels, scores)
 print(' Confusion matrix')
 print(' Score positive Score negative')
 print('Actual positive {:6d} {:6d}'.format(conf[0,0], conf[0,1]))
print('Actual negative {:6d} {:6d}'.format(conf[1,0], conf[1,1]))
print('')
 print('Accuracy {:.4f}'.format(metrics.accuracy_score(labels, scores)))
 print('AUC {:.4f}'.format(metrics.roc_auc_score(labels, probs[:,1])))
 print('Macro precision {:.4f}'.format(float(( float(mets[0][0])+ float(mets[0][1])) /2.0)))
 print('Macro recall {:.4f}'.format(float(( float(mets[1][0])+ float(mets[1][1])) /2.0)))
 print(' ')
 print(' Positive Negative')
 print('Num case {:6d} {:6d}'.format(mets[3][0], mets[3][1]))
print('Precision {:.4f} {:.4f}'.format(mets[0][0], mets[0][1]))
print('Recall {:.4f} {:.4f}'.format(mets[1][0], mets[1][1]))
print('F1 {:.4f} {:.4f}'.format(mets[2][0], mets[2][1]))
def plot_auc(labels, probs):
fpr, tpr, threshold = metrics.roc_curve(labels, probs[:,1])
 auc = metrics.auc(fpr, tpr)
 plt.title('Receiver Operating Characteristic')
 plt.plot(fpr, tpr, color = 'blue', label = 'AUC = {:.4f}'.format(auc))
plt.legend(loc = 'lower right')
 plt.plot([0, 1], [0, 1],'r--')
 plt.xlim([0, 1])
 plt.ylim([0, 1])
 plt.ylabel('True Positive Rate')
 plt.xlabel('False Positive Rate')
 plt.show()
print_metrics(y_test, probabilities,.5)
 plot_auc(y_test, probabilities )<choose_model_class>
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels = range(len(CLASSES)))
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, cm_predictions)
 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))
ad_clf = AdaBoostClassifier(DecisionTreeClassifier())
 ad_clf.get_params()<define_search_space>
def create_submission_file(filename, probabilities):
predictions = np.argmax(probabilities, axis = -1)
 print('Generating submission file...', filename)
 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(filename, np.rec.fromarrays([test_ids, predictions]), fmt = ['%s', '%d'], delimiter = ',', header = 'id,label', comments = '')
param_grid = {'base_estimator__max_depth' :[1, 2, 3, 5],
'base_estimator__min_samples_split':[2, 3, 5],
'base_estimator__min_samples_leaf':[2, 3, 5, 10],
'n_estimators' :[50, 100, 250, 500, 750],
'learning_rate' :[0.0001, 0.001, 0.01, 0.1, 1, 5]}
ad_clf_grid = GridSearchCV(estimator=ad_clf,
param_grid=param_grid,
cv=cv,
scoring='accuracy',
return_train_score=True,
n_jobs=4,
verbose=1)
 ad_clf_grid.fit(train_data, Label)
 ada_best_params = ad_clf_grid.best_estimator_
print('GridsearchCV Best Score: ' + str(ad_clf_grid.best_score_))
print('
Tested HyperParameters Values')
 print('base_estimator__max_depth: {}'.format(ad_clf_grid.best_estimator_.base_estimator.max_depth))
print('base_estimator__min_samples_split: {}'.format(ad_clf_grid.best_estimator_.base_estimator.min_samples_split))
print('base_estimator__min_samples_leaf : {}'.format(ad_clf_grid.best_estimator_.base_estimator.min_samples_leaf))
print('n_estimators: {}'.format(ad_clf_grid.best_estimator_.n_estimators))
print('learning_rate: {}'.format(ad_clf_grid.best_estimator_.learning_rate))<choose_model_class>
probabilities = np.zeros(( test_probabilities[0].shape))
for j in range(no_of_models):
probabilities = probabilities + test_probabilities[j]
filename = this_run_file_prefix + 'submission.csv'
create_submission_file(filename, probabilities)
 create_submission_file('submission.csv', probabilities )
rf_clf = RandomForestClassifier()
rf_clf.get_params()<define_search_space>
def combine_two(correct_labels, probability_0, probability_1):
print('Start.', datetime.now())
 alphas0_to_try = np.linspace(0, 1, 101)
 best_score = -1
best_alpha0 = -1
best_alpha1 = -1
best_precision = -1
best_recall = -1
best_val_predictions = None
for alpha0 in alphas0_to_try:
alpha1 = 1.0 - alpha0
probabilities = alpha0 * probability_0 + alpha1 * probability_1
predictions = np.argmax(probabilities, axis = -1)
 score, precision, recall = getFitPrecisionRecall(correct_labels, predictions)
 if score > best_score:
best_alpha0 = alpha0
best_alpha1 = alpha1
best_score = score
best_precision = precision
best_recall = recall
best_val_predictions = predictions
return best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall
param_grid = {'n_estimators': [10, 50, 100, 250, 500, 750],
'max_depth': [5, 8, 15, 25, 30],
'min_samples_split': [2, 5, 10, 15],
'min_samples_leaf':[2, 3, 5, 10, 15, 20]}
rf_clf_grid = GridSearchCV(estimator=rf_clf,
param_grid=param_grid,
cv=cv,
scoring='accuracy',
return_train_score=True,
n_jobs=4,
verbose=1)
 rf_clf_grid.fit(train_data, Label)
 rf_best_params = rf_clf_grid.best_estimator_
print('GridsearchCV Best Score: {}'.format(rf_clf_grid.best_score_))
print('
Tested HyperParameters Values')
 print('n_estimators: {}'.format(rf_clf_grid.best_estimator_.n_estimators))
print('max_depth: {}'.format(rf_clf_grid.best_estimator_.max_depth))
print('min_samples_split: {}'.format(rf_clf_grid.best_estimator_.min_samples_split))
print('min_samples_leaf: {}'.format(rf_clf_grid.best_estimator_.min_samples_leaf))<choose_model_class>
def combine_three(correct_labels, probability_0, probability_1, probability_2):
print('Start.', datetime.now())
 alphas0_to_try = np.linspace(0, 1, 101)
 alphas1_to_try = np.linspace(0, 1, 101)
 best_score = -1
best_alpha0 = -1
best_alpha1 = -1
best_alpha2 = -1
best_precision = -1
best_recall = -1
best_val_predictions = None
for alpha0 in alphas0_to_try:
for alpha1 in alphas1_to_try:
if(alpha0 + alpha1)> 1.0:
break
alpha2 = 1.0 - alpha0 - alpha1
probabilities = alpha0 * probability_0 + alpha1 * probability_1 + alpha2 * probability_2
predictions = np.argmax(probabilities, axis = -1)
 score, precision, recall = getFitPrecisionRecall(correct_labels, predictions)
 if score > best_score:
best_alpha0 = alpha0
best_alpha1 = alpha1
best_alpha2 = alpha2
best_score = score
best_precision = precision
best_recall = recall
best_val_predictions = predictions
return best_alpha0, best_alpha1, best_alpha2, best_val_predictions, best_score, best_precision, best_recall
gb_clf = GradientBoostingClassifier()
gb_clf.get_params()<define_search_space>
def get_best_combination(no_models, cm_correct_labels, val_probabilities, test_probabilities):
best_fit_score = -10000.0
best_predictions = 0
choose_filename = ''
curr_predictions = np.argmax(val_probabilities[0], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_0.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[0])
 create_submission_file(filename, test_probabilities[0])
 if no_models > 1:
curr_predictions = np.argmax(val_probabilities[1], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_1.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[1])
 create_submission_file(filename, test_probabilities[1])
 if no_models > 2:
curr_predictions = np.argmax(val_probabilities[2], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_2.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[2])
 create_submission_file(filename, test_probabilities[2])
 if no_models > 1:
best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[0], val_probabilities[1])
 print('For indx', [0, 1], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[1]
filename = this_run_file_prefix + 'submission_01.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 if no_models > 2:
best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[0], val_probabilities[2])
 print('For indx', [0, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_02.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[1], val_probabilities[2])
 print('For indx', [1, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[1] + best_alpha1 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_12.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 best_alpha0, best_alpha1, best_alpha2, best_val_predictions, best_score, best_precision, best_recall = combine_three(cm_correct_labels, val_probabilities[0], val_probabilities[1], val_probabilities[2])
 print('For indx', [0, 1, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, 'best_alpha2:', best_alpha2, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[1] + best_alpha2 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_012.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 cmat = confusion_matrix(cm_correct_labels, best_predictions, labels = range(len(CLASSES)))
 cmat =(cmat.T / cmat.sum(axis = -1)).T
display_confusion_matrix(cmat, best_fit_score, precision, recall)
 print('Best score from all combination was', best_fit_score, '.For submission file used is', choose_filename)
 return best_predictions
param_grid = {'n_estimators': [50, 100, 250, 500, 750, 1000],
'max_depth': [3, 5, 8, 15, 25],
'min_samples_split': [2, 5, 10],
'min_samples_leaf':[1, 2, 3, 5, 10],
'learning_rate' :[0.0001, 0.001, 0.01, 0.1, 1]}
gb_clf_grid = GridSearchCV(estimator=gb_clf,
param_grid=param_grid,
cv=KFold(n_splits=5, shuffle=True),
scoring='accuracy',
return_train_score=True,
n_jobs=4,
verbose=1)
 gb_clf_grid.fit(train_data, Label)
 gb_best_params = gb_clf_grid.best_estimator_
print('GridsearchCV Best Score: {}'.format(gb_clf_grid.best_score_))
print('
Tested HyperParameters Values')
 print('n_estimators: {}'.format(gb_clf_grid.best_estimator_.n_estimators))
print('max_depth: {}'.format(gb_clf_grid.best_estimator_.max_depth))
print('min_samples_split: {}'.format(gb_clf_grid.best_estimator_.min_samples_split))
print('min_samples_leaf: {}'.format(gb_clf_grid.best_estimator_.min_samples_leaf))
print('learning_rate: {}'.format(gb_clf_grid.best_estimator_.learning_rate))<choose_model_class>
best_predictions = cm_predictions
if no_of_models > 1:
bp = get_best_combination(no_of_models, cm_correct_labels, val_probabilities, test_probabilities)
 best_predictions = bp
mlp_clf = MLPClassifier()
mlp_clf.get_params()<define_search_space>
probabilities = np.zeros(( all_probabilities[0].shape))
for j in range(no_of_models):
probabilities = probabilities + all_probabilities[j]
predictions = np.argmax(probabilities, axis =-1)
 display_batch_of_images(( images, labels), predictions )
param_grid = {'hidden_layer_sizes' :[(50, 50, 10),(50, 100, 10),(100,)],
'solver' :['lbfgs', 'adam'],
'alpha' :[.000001,.00001,.0001,.001],
'early_stopping' :[True, False],
'beta_1' :[.8,.9,.99],
'beta_2' :[.8,.9,.99,.999],
'max_iter' :[100, 200, 500, 1000]}
mlp_clf_grid = GridSearchCV(estimator=mlp_clf,
param_grid=param_grid,
cv=KFold(n_splits=5, shuffle=True),
scoring='accuracy',
return_train_score=True,
n_jobs=4,
verbose=1)
 mlp_clf_grid.fit(train_data, Label)
 mlp_best_params = mlp_clf_grid.best_estimator_
print('GridSearchCV Best Score: {}'.format(mlp_clf_grid.best_score_))
print('
Tested HyperParameters Values')
 print('hidden_layer_sizes: {}'.format(mlp_clf_grid.best_estimator_.hidden_layer_sizes))
print('solver: {}'.format(mlp_clf_grid.best_estimator_.solver))
print('alpha: {}'.format(mlp_clf_grid.best_estimator_.alpha))
print('early_stopping: {}'.format(mlp_clf_grid.best_estimator_.early_stopping))
print('beta_1: {}'.format(mlp_clf_grid.best_estimator_.beta_1))
print('beta_2: {}'.format(mlp_clf_grid.best_estimator_.beta_2))
print('max_iter: {}'.format(mlp_clf_grid.best_estimator_.max_iter))<choose_model_class>
val_probs = [cm_correct_labels, cm_predictions, val_probabilities[0], val_probabilities[1], test_probabilities[0], test_probabilities[1]]
filename = this_run_file_prefix + 'tests_vals_01.pkl'
pklfile = open(filename, 'ab')
 pickle.dump(val_probs, pklfile)
 pklfile.close()
voting_cf = VotingClassifier(estimators=[('rfc', rf_best_params), 
('svc', svc_best_params), 
('ada', ada_best_params), 
('gbc', gb_best_params), 
('mlp', mlp_best_params)], voting='soft', n_jobs=4)
 voting_cf = voting_cf.fit(X_train, y_train)
 voting = voting_cf.predict(X_test )<compute_test_metric>
use_correct_labels = cm_correct_labels
use_val_predictions = best_predictions
def print_metrics_score(labels, scores):
mets = metrics.precision_recall_fscore_support(labels, scores)
 conf = metrics.confusion_matrix(labels, scores)
 print(' Confusion matrix')
 print(' Score positive Score negative')
 print('Actual positive {:6d} {:6d}'.format(conf[0,0], conf[0,1]))
print('Actual negative {:6d} {:6d}'.format(conf[1,0], conf[1,1]))
print('')
 print('Accuracy {:.4f}'.format(metrics.accuracy_score(labels, scores)))
 print('Macro precision {:.4f}'.format(float(( float(mets[0][0])+ float(mets[0][1])) /2.0)))
 print('Macro recall {:.4f}'.format(float(( float(mets[1][0])+ float(mets[1][1])) /2.0)))
 print(' ')
 print(' Positive Negative')
 print('Num case {:6d} {:6d}'.format(mets[3][0], mets[3][1]))
print('Precision {:.4f} {:.4f}'.format(mets[0][0], mets[0][1]))
print('Recall {:.4f} {:.4f}'.format(mets[1][0], mets[1][1]))
print('F1 {:.4f} {:.4f}'.format(mets[2][0], mets[2][1]))
print_metrics_score(y_test, voting )<save_to_csv>
correct_labels_cnt = 0
incorrect_labels_cnt = 0
correct_labels = []
incorrect_labels = []
vals_actual_true = {}
vals_tp = {}
vals_fn = {}
vals_fp = {}
for i in range(len(CLASSES)) :
vals_actual_true[i] = 0
vals_tp[i] = 0
vals_fn[i] = 0
vals_fp[i] = 0
for i in range(len(use_correct_labels)) :
correct_label = use_correct_labels[i]
predict_label = use_val_predictions[i]
vals_actual_true[correct_label] = vals_actual_true[correct_label] + 1
if use_val_predictions[i] != use_correct_labels[i]:
incorrect_labels_cnt = incorrect_labels_cnt + 1
incorrect_labels.append(i)
 vals_fn[correct_label] = vals_fn[correct_label] + 1
vals_fp[predict_label] = vals_fp[predict_label] + 1
else:
correct_labels_cnt = correct_labels_cnt + 1
correct_labels.append(i)
 vals_tp[correct_label] = vals_tp[correct_label] + 1
print('Number of correct_labels is {}, incorrect_labels is {}'.format(correct_labels_cnt, incorrect_labels_cnt))
print('Incorrect labels', incorrect_labels)
svc_best = clone(svc_best_params)
 svc_best.fit(train_data, Label)
 scores = score_model(svc_best.predict_proba(test_data),.5)
 sub = pd.DataFrame({'PassengerId':submission, 'Survived': scores})
 sub.to_csv('svc_prediction.csv', index=False )<save_to_csv>
def display_my_batch_of_images(databatch, rows = 0, cols = 0, predictions=None):

 images, labels = databatch
if labels is None:
labels = [None for _ in enumerate(images)]
if rows == 0 or cols == 0:
rows = int(math.sqrt(len(images)))
 cols =(len(images)+ rows - 1)//rows
print('Total number of images is {}, rows is {}, cols is {}'.format(len(images), rows, cols))
FIGSIZE = 20.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()
ada_best = clone(ada_best_params)
 ada_best.fit(train_data, Label)
 scores = score_model(ada_best.predict_proba(test_data),.5)
 sub = pd.DataFrame({'PassengerId':submission, 'Survived': scores})
 sub.to_csv('adaboost_prediction.csv', index=False )<save_to_csv>
disp_labels = []
disp_predictions = []
for i in range(54):
if i >= incorrect_labels_cnt:
break
id = incorrect_labels[i]
disp_labels.append(use_correct_labels[id])
 disp_predictions.append(use_val_predictions[id])
 print(disp_labels)
 print(disp_predictions )
<save_to_csv><EOS> 
val_ids = list(range(len(use_correct_labels)))
 filename = this_run_file_prefix + 'validation_results.csv'
np.savetxt(filename, np.rec.fromarrays([val_ids, use_correct_labels, use_val_predictions]), fmt = ['%d', '%d', '%d'], delimiter = ',', header = 'id,correct_label,predicted_label', comments = '')
 cls_ids = list(range(len(CLASSES)))
 filename = this_run_file_prefix + 'validation_statistics.csv'
np.savetxt(filename, np.rec.fromarrays([cls_ids, list(vals_actual_true.values()), list(vals_tp.values()), list(vals_fn.values()), list(vals_fp.values())]), fmt = ['%d', '%d', '%d', '%d', '%d'], delimiter = ',', header = 'cls_id,actual_true,true_positive,false_negative,false_positive', comments = '' )