Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<categorify>
!pip install --quiet efficientnet
def seed_everything(seed=0):
random.seed(seed)
 np.random.seed(seed)
 tf.random.set_seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 os.environ['TF_DETERMINISTIC_OPS'] = '1'
seed = 0
seed_everything(seed)
 warnings.filterwarnings("ignore" )
all_data = pd.get_dummies(all_data)
 print(all_data.shape )<choose_model_class>
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print(f'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()
AUTO = tf.data.experimental.AUTOTUNE
REPLICAS = strategy.num_replicas_in_sync
print(f'REPLICAS: {REPLICAS}' )
regr = xgb.XGBRegressor(colsample_bytree=0.2,
gamma=0.0,
learning_rate=0.1,
max_depth=4,
min_child_weight=1.5,
n_estimators=7200,
reg_alpha=0.9,
reg_lambda=0.6,
subsample=0.2,
seed=42,
silent=1)
 regr.fit(train_new,y_train)
 y_pred = regr.predict(train_new)
 y_test = train['SalePrice']
print("XGB Score :",(np.sqrt(mean_squared_error(y_test, y_pred))))
y_pred_xgb = regr.predict(test_new)
 y_pred_xgb = np.exp(y_pred_xgb)
 pred_df = pd.DataFrame(y_pred_xgb, index=test_ID, columns=["SalePrice"])
 pred_df.to_csv('submission1.csv', header=True, index_label='Id' )<train_model>
BATCH_SIZE = 16 * REPLICAS
WARMUP_EPOCHS = 3
WARMUP_LEARNING_RATE = 1e-4 * REPLICAS
EPOCHS = 20
LEARNING_RATE = 3e-5 * REPLICAS
HEIGHT = 512
WIDTH = 512
CHANNELS = 3
N_CLASSES = 104
ES_PATIENCE = 5
model_lasso =Lasso(alpha=0.0005,normalize=True, max_iter=1e5)
 model_lasso.fit(train_new,y_train)
 y_pred_lasso = model_lasso.predict(train_new)
 score_lasso = np.sqrt(mean_squared_error(y_train, y_pred_lasso))
print("Lasso Score :",score_lasso)
 y_pred_lasso_test = model_lasso.predict(test_new)
 y_pred_lasso_test = np.exp(y_pred_lasso_test )<compute_train_metric>
model_path = f'model_{HEIGHT}x{WIDTH}.h5'
GCS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')+ f'/tfrecords-jpeg-{HEIGHT}x{WIDTH}'
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')
 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']
model_rd = Ridge(alpha = 4.84)
 model_rd.fit(train_new,y_train)
 y_pred_rd = model_rd.predict(train_new)
 score_rd = np.sqrt(mean_squared_error(y_train, y_pred_rd))
print("Ridge Score :",score_rd)
 y_pred_rd_test = model_rd.predict(test_new)
 y_pred_rd_test = np.exp(y_pred_rd_test )<compute_train_metric>
AUTO = tf.data.experimental.AUTOTUNE
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, [HEIGHT, WIDTH, 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):
crop_size = tf.random.uniform([], int(HEIGHT*.7), HEIGHT, dtype=tf.int32)
 image = tf.image.random_flip_left_right(image)
 image = tf.image.random_flip_up_down(image)
 image = tf.image.random_saturation(image, lower=0, upper=2)
 image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])
 image = tf.image.resize(image, size=[HEIGHT, WIDTH])
 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_training_dataset_preview(ordered=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
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 )
model_enet = ElasticNet(alpha=0.0005, l1_ratio=.9, random_state=3)
 model_enet.fit(train_new,y_train)
 y_pred_enet = model_enet.predict(train_new)
 score_enet = np.sqrt(mean_squared_error(y_train, y_pred_enet))
print("ElasticNet Score :",score_enet)
 y_pred_enet_test = model_enet.predict(test_new)
 y_pred_enet_test = np.exp(y_pred_enet_test )<predict_on_test>
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 dataset_to_numpy_util(dataset, N):
dataset = dataset.unbatch().batch(N)
 for images, labels in dataset:
numpy_images = images.numpy()
numpy_labels = labels.numpy()
break;
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
label = np.argmax(label, axis=-1)
 correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], str(correct), ', shoud be ' if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower_eval(image, title, subplot, red=False):
plt.subplot(subplot)
 plt.axis('off')
 plt.imshow(image)
 plt.title(title, fontsize=14, color='red' if red else 'black')
 return subplot+1
def display_9_images_with_predictions(images, predictions, labels):
subplot=331
plt.figure(figsize=(13,13))
for i, image in enumerate(images):
title, correct = title_from_label_and_target(predictions[i], labels[i])
 subplot = display_one_flower_eval(image, title, subplot, not correct)
 if i >= 8:
break;
plt.tight_layout()
plt.subplots_adjust(wspace=0.1, hspace=0.1)
 plt.show()
model_rf = RandomForestRegressor(n_estimators = 12,max_depth = 3,n_jobs = -1)
 model_rf.fit(train_new,y_train)
 y_pred_rf = model_rf.predict(train_new)
 score_rf = np.sqrt(mean_squared_error(y_train, y_pred_rf))
print("RandomForest Score :",score_rf)
 y_pred_rf_test = model_rf.predict(test_new)
 y_pred_rf_test = np.exp(y_pred_rf_test )<predict_on_test>
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 train_dataset = get_training_dataset_preview(ordered=True)
 y_train = next(iter(train_dataset.unbatch().map(lambda image, label: label ).batch(NUM_TRAINING_IMAGES)) ).numpy()
print(f'Number of training images {NUM_TRAINING_IMAGES}')
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 valid_dataset = get_validation_dataset(ordered=True)
 y_valid = next(iter(valid_dataset.unbatch().map(lambda image, label: label ).batch(NUM_VALIDATION_IMAGES)) ).numpy()
print(f'Number of validation images {NUM_VALIDATION_IMAGES}')
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 print(f'Number of test images {NUM_TEST_IMAGES}')
 test_dataset = get_test_dataset(ordered=True )
model_gb = GradientBoostingRegressor(n_estimators = 40,max_depth = 2)
 model_gb.fit(train_new,y_train)
 y_pred_gb = model_gb.predict(train_new)
 score_gb = np.sqrt(mean_squared_error(y_train, y_pred_gb))
print("GradientBoosting Score :",score_gb)
 y_pred_gb_test = model_gb.predict(test_new)
 y_pred_gb_test = np.exp(y_pred_gb_test )<compute_train_metric>
display_batch_of_images(next(iter(train_dataset.unbatch().batch(20))))
dt = DecisionTreeRegressor(max_depth=4)
 model_ad = AdaBoostRegressor(dt, learning_rate = 0.1, n_estimators=300,random_state= None)
 model_ad.fit(train_new,y_train)
 y_pred_ad = model_ad.predict(train_new)
 score_ad = np.sqrt(mean_squared_error(y_train, y_pred_ad))
print("AdaBoost Model :",score_ad)
 y_pred_ad_test = model_ad.predict(test_new)
 y_pred_ad_test = np.exp(y_pred_ad_test )<import_modules>
display_batch_of_images(next(iter(valid_dataset.unbatch().batch(20))))
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn import metrics
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt<load_from_csv>
display_batch_of_images(next(iter(test_dataset.unbatch().batch(20))))
train = pd.read_csv('.. /input/train.csv')
 train.head()<load_from_csv>
for img, label in train_dataset.take(1):
data = [img[0:32,:,:,:].numpy() ,label[0:32].numpy() ]
test = pd.read_csv('.. /input/test.csv')
 test.head()<prepare_x_and_y>
train_y = train['Survived']
train_y<drop_column>
def create_model(input_shape, N_CLASSES):
base_model =tf.keras.applications.VGG16(weights = 'imagenet',
include_top=False,
input_shape=input_shape)
 base_model.trainable = False
model = tf.keras.Sequential([
base_model,
L.GlobalAveragePooling2D() ,
L.Dense(N_CLASSES, activation='softmax')
 ])
 return model
del train['Name'], train['Ticket'], train['Cabin'], train['Survived']
del test['Name'], test['Ticket'], test['Cabin']
train.head()<categorify>
with strategy.scope() :
model = create_model(( None, None, CHANNELS), N_CLASSES)
 metric_list = ['sparse_categorical_accuracy']
optimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)
 model.compile(optimizer=optimizer,
loss=losses.SparseCategoricalCrossentropy() ,
metrics=metric_list)
 model.summary()
train['Sex'] = train['Sex'].replace({'male': 0, 'female':1})
 train['Embarked'] = train['Embarked'].replace({'Q': 0, 'S':1, 'C':1})
 test['Sex'] = test['Sex'].replace({'male': 0, 'female':1})
 test['Embarked'] = test['Embarked'].replace({'Q': 0, 'S':1, 'C':1} )<count_missing_values>
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
warmup_history = model.fit(x=get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
validation_data=get_validation_dataset() ,
epochs=WARMUP_EPOCHS,
verbose=2 ).history
train[train['Pclass'].isnull() ]
train[train['Sex'].isnull() ]
train[train['Age'].isnull() ]
train[train['SibSp'].isnull() ]
train[train['Parch'].isnull() ]
train[train['Fare'].isnull() ]
train[train['Embarked'].isnull() ]<filter>
LR_START = 0.00000001
LR_MIN = 0.000001
LR_MAX = LEARNING_RATE
LR_RAMPUP_EPOCHS = 3
LR_SUSTAIN_EPOCHS = 0
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
rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
sns.set(style='whitegrid')
 fig, ax = plt.subplots(figsize=(20, 6))
plt.plot(rng, y)
 print(f'{EPOCHS} total epochs and {NUM_TRAINING_IMAGES//BATCH_SIZE} steps per epoch')
 print(f'Learning rate schedule: {y[0]:.3g} to {max(y):.3g} to {y[-1]:.3g}' )
test[test['Pclass'].isnull() ]
test[test['Sex'].isnull() ]
test[test['Age'].isnull() ]
test[test['SibSp'].isnull() ]
test[test['Parch'].isnull() ]
test[test['Fare'].isnull() ]
test[test['Embarked'].isnull() ]<split>
for layer in model.layers:
layer.trainable = True
checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True)
 es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE,
restore_best_weights=True, verbose=1)
 lr_callback = LearningRateScheduler(lrfn, verbose=0)
 callback_list = [checkpoint, es, lr_callback]
optimizer = optimizers.Adam(lr=LEARNING_RATE)
 model.compile(optimizer=optimizer,
loss='sparse_categorical_crossentropy',
metrics=metric_list)
 model.summary()
X, y = train, train_y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y)
 print("X_train len:{}".format(len(X_train)))
 print("X_test len:{}".format(len(X_test)))
 print("y_train len:{}".format(len(y_train)))
 print("y_test len:{}".format(len(y_test)) )<count_values>
history = model.fit(x=get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
validation_data=get_validation_dataset() ,
callbacks=callback_list,
epochs=20,
verbose=2 ).history
y_train.value_counts(normalize=True)
<count_values>
x_train = train_dataset.map(lambda image, label: image)
 train_preds = model.predict(x_train)
 train_preds = np.argmax(train_preds, axis=-1)
 print(classification_report(y_train, train_preds, target_names=CLASSES))
y_test.value_counts(normalize=True )<find_best_model_class>
x_valid = valid_dataset.map(lambda image, label: image)
 valid_preds = model.predict(x_valid)
 valid_preds = np.argmax(valid_preds, axis=-1)
 print(classification_report(y_valid, valid_preds, target_names=CLASSES))
lgb_train = lgb.Dataset(X_train, y_train)
 lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
 lgbm_params = {
'objective': 'binary',
'metric': 'auc',
}
model = lgb.train(lgbm_params, lgb_train, valid_sets=lgb_eval)
 y_pred = model.predict(X_test, num_iteration=model.best_iteration)
 fpr, tpr, thresholds = metrics.roc_curve(y_test, y_pred)
 auc = metrics.auc(fpr, tpr)
 print(auc)
 y_pred<predict_on_test>
x_train_samp, y_train_samp = dataset_to_numpy_util(train_dataset, 12)
 train_samp_preds = model.predict(x_train_samp, batch_size=12)
 display_9_images_with_predictions(x_train_samp, train_samp_preds, y_train_samp )
y_test_pred = model.predict(test, num_iteration=model.best_iteration)
 y_test_pred<data_type_conversions>
x_valid_samp, y_valid_samp = dataset_to_numpy_util(valid_dataset, 9)
 valid_samp_preds = model.predict(x_valid_samp, batch_size=9)
 display_9_images_with_predictions(x_valid_samp, valid_samp_preds, y_valid_samp )
preds = np.round(y_test_pred ).astype(int)
 preds<predict_on_test>
x_test = test_dataset.map(lambda image, idnum: image)
 test_preds = model.predict(x_test)
 test_preds = np.argmax(test_preds, axis=-1 )
<load_from_csv><EOS> 
test_ids_ds = test_dataset.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 submission = pd.DataFrame(test_ids, columns=['id'])
 submission['label'] = test_preds
submission.to_csv('submission.csv', index=False)
 display(submission.head(10))