Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<drop_column>
import re
import numpy as np
from matplotlib import pyplot as plt
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
x_train.drop(columns=['Name','Ticket','Cabin'],inplace=True,axis=1)
 x_val.drop(columns=['Name','Ticket','Cabin'],inplace=True,axis=1 )<drop_column>
print("Tensorflow version " + tf.__version__ )
impute=SimpleImputer(strategy='most_frequent')
 x_train_1=pd.DataFrame(impute.fit_transform(x_train[['Embarked']]))
x_val_1=pd.DataFrame(impute.transform(x_val[['Embarked']]))
x_train_1.columns=['Embarked']
x_val_1.columns=['Embarked']
x_train_1.index=x_train.index
x_val_1.index=x_val.index
x_train.drop('Embarked',axis=1,inplace=True)
 x_val.drop('Embarked',axis=1,inplace=True)
 x_train=pd.concat([x_train,x_train_1],axis=1)
 x_val=pd.concat([x_val,x_val_1],axis=1)
 x_train<create_dataframe>
AUTO = tf.data.experimental.AUTOTUNE
AUTO
impute_1=SimpleImputer(strategy='mean')
 x_train_2=pd.DataFrame(impute_1.fit_transform(x_train[['Age']]))
x_val_2=pd.DataFrame(impute_1.transform(x_val[['Age']]))
x_train_2.columns=['Age']
x_val_2.columns=['Age']
x_train_2.index=x_train.index
x_val_2.index=x_val.index
x_train.drop('Age',axis=1,inplace=True)
 x_val.drop('Age',axis=1,inplace=True)
 x_train=pd.concat([x_train,x_train_2],axis=1)
 x_val=pd.concat([x_val,x_val_2],axis=1)
 x_train<count_missing_values>
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu )
print("{} null-values left in training-set".format(x_train.isnull().any().sum()),end='
')
 print("{} null-values left in validation-set".format(x_val.isnull().any().sum()),end='
' )<categorify>
IMAGE_SIZE = [512, 512]
EPOCHS = 30
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
encode=OneHotEncoder(handle_unknown='ignore',sparse=False)
 categorical_cols=list(x_train.select_dtypes(include=['object'] ).columns)
 categorical_cols
x_train_oh=pd.DataFrame(encode.fit_transform(x_train[categorical_cols]))
x_val_oh=pd.DataFrame(encode.transform(x_val[categorical_cols]))
x_train_oh.index=x_train.index
x_val_oh.index=x_val.index
x_train.drop(columns=categorical_cols,axis=1,inplace=True)
 x_val.drop(columns=categorical_cols,axis=1,inplace=True)
 x_train=pd.concat([x_train,x_train_oh],axis=1)
 x_val=pd.concat([x_val,x_val_oh],axis=1)
 x_train<normalization>
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
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
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]))
col_scale=['Age','Fare']
scale=StandardScaler()
x_train_scale=pd.DataFrame(scale.fit_transform(x_train[col_scale]))
x_val_scale=pd.DataFrame(scale.transform(x_val[col_scale]))
x_train_scale.index=x_train.index
x_val_scale.index=x_val.index
x_train_scale.columns=col_scale
x_val_scale.columns=col_scale
x_train.drop(columns=col_scale,axis=1,inplace=True)
 x_val.drop(columns=col_scale,axis=1,inplace=True)
 x_train=pd.concat([x_train,x_train_scale],axis=1)
 x_val=pd.concat([x_val,x_val_scale],axis=1)
 x_train<drop_column>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
test.drop(columns=['Ticket','Cabin','Name'],axis=1,inplace=True )<drop_column>
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' )
test_1=pd.DataFrame(impute_1.transform(test[['Age']]))
test_1.columns=['Age']
test_1.index=test.index
test.drop('Age',axis=1,inplace=True)
 test=pd.concat([test,test_1],axis=1)
 test 
<create_dataframe>
SKIP_VALIDATION = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
impute_3=SimpleImputer(strategy='most_frequent')
 test_2=pd.DataFrame(impute_3.fit_transform(test[['Fare']]))
test_2.columns=['Fare']
test_2.index=test.index
test.drop('Fare',axis=1,inplace=True)
 test=pd.concat([test,test_2],axis=1)
 test 
<create_dataframe>
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_oh=pd.DataFrame(encode.transform(test[categorical_cols]))
test_oh.index=test.index
test.drop(columns=categorical_cols,axis=1,inplace=True)
 test=pd.concat([test,test_oh],axis=1)
 test<concatenate>
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)
 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 = 0 if SKIP_VALIDATION else 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))
test_scale=pd.DataFrame(scale.transform(test[col_scale]))
test_scale.columns=col_scale
test_scale.index=test.index
test.drop(columns=col_scale,axis=1,inplace=True)
 test=pd.concat([test,test_scale],axis=1)
 test<choose_model_class>
models = []
histories = []
log_reg=lr(random_state=random_state)
 sgd=sg(random_state=random_state)
 random_forest=rf(random_state=random_state)
 tree_model=dt(random_state=random_state)
 svm_model=SVC(random_state=random_state)
 xgb=XGBClassifier(random_state=random_state)
 models={'Logistic Regression':log_reg,'SGD':sgd,'Random Forest':random_forest,'Decision Tree':tree_model,'SVM':svm_model,'XGBoost':xgb}
for model_name,model in models.items() :
model.fit(x_train,y_train)
 rslt=model.predict(x_val)
 print('{}:{}'.format(model_name,np.sum(rslt==y_val)/len(y_val)) ,end='
' )<predict_on_test>
!pip install -q efficientnet
result=random_forest.predict(test )<save_to_csv>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights='imagenet',
include_top=False 
)
 enet.trainable = True
model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()
models.append(model )
output=pd.DataFrame({'PassengerId':test.PassengerId,
'Survived':result})
 output.to_csv('submission.csv',index=False )<set_options>
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() 
)
 histories.append(history )
warnings.filterwarnings("ignore")
<import_modules>
from tensorflow.keras.applications import DenseNet201
from scipy import stats
from scipy.special import boxcox1p
from scipy.stats import skew
from sklearn.metrics import r2_score, mean_squared_log_error
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import RobustScaler
from sklearn.model_selection import KFold
from sklearn.pipeline import make_pipeline
from sklearn.kernel_ridge import KernelRidge 
<set_options>
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights='imagenet',
include_top=False 
)
 rnet.trainable = True
model = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()
models.append(model )
plt.style.use('seaborn')
 plt.rcParams['figure.figsize'] = [15, 5]
plt.rcParams['axes.labelsize'] = 15
plt.rcParams['axes.titlesize'] = 20
pd.set_option('display.max_columns', 500)
 pd.set_option('display.max_rows', 200 )<load_from_csv>
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() 
)
 histories.append(history )
df_train = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/train.csv')
 df_test = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/test.csv')
 df_all = pd.concat(( df_train,df_test),ignore_index=True )<feature_engineering>
if not SKIP_VALIDATION:
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()
cm_probabilities =(models[0].predict(images_ds)+ models[1].predict(images_ds)) / 2
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 )
train_len = len(df_train)
 df_all["Set"] = ["Train"]*train_len + ["Test"]*(len(df_all)- train_len )<train_model>
if not SKIP_VALIDATION:
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')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
print("Skewness of target: ",skew(df_all["SalePrice"].dropna()))<feature_engineering>
if not SKIP_VALIDATION:
cmat_norm =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat_norm, score, precision, recall )
<sort_values><EOS> 
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities =(models[0].predict(test_images_ds)+ models[1].predict(test_images_ds)) / 2
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='' )