Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<count_missing_values>
!pip install efficientnet
Total = Total.drop(['Ticket','Cabin'], axis = 1)
 fare_mode = Total['Fare'].mode().iat[0]
Total['Fare'].fillna(fare_mode,inplace = True)
 embarked_mode = Total['Embarked'].mode().iat[0]
Total['Embarked'].fillna(embarked_mode, inplace = True)
 for column in Total:
if Total[column].isnull().sum() != 0:
print('Missing values in',column,':', Total[column].isnull().sum() )<categorify>
import random, re, math, os
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow_addons as tfa
from kaggle_datasets import KaggleDatasets
from tensorflow.keras.mixed_precision import experimental as mixed_precision
import tensorflow.keras.backend as K
import efficientnet.tfkeras as efn
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
import datetime
import tqdm
import json
from collections import Counter
import gc
sex_dummy = pd.get_dummies(Total['Sex'])
 Total = Total.drop('Sex', axis = 1)
 Total = pd.concat([Total, sex_dummy], axis = 1)
 embark_dummy = pd.get_dummies(Total['Embarked'])
 Total = Total.drop('Embarked', axis = 1)
 Total = pd.concat([Total, embark_dummy], axis = 1)
 Total<drop_column>
IMAGE_SIZE = [512, 512]
EPOCHS = 16
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
SEED = 100
title = lambda x: x.split(',')[1].split('.')[0].strip()
Total['Title']=Total['Name'].map(title)
 Total = Total.drop('Name', axis = 1)
 Total<categorify>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 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' )
title_dummy = pd.get_dummies(Total['Title'])
 title_dummy
title_dummy['Mil'] = title_dummy['Capt']+title_dummy['Col']+title_dummy['Major']
title_dummy = title_dummy.drop(['Capt','Col','Major'], axis = 1)
 title_dummy['Senior Male Honorific'] = title_dummy['Don']+title_dummy['Sir']
title_dummy = title_dummy.drop(['Don','Sir'], axis = 1)
 title_dummy['Senior Female Honorific'] = title_dummy['Dona']+title_dummy['Mme']+title_dummy['Lady']
title_dummy = title_dummy.drop(['Dona','Mme','Lady'], axis = 1)
 title_dummy['Ms+Mlle'] = title_dummy['Ms']+title_dummy['Mlle']
title_dummy = title_dummy.drop(['Ms','Mlle'], axis = 1)
 title_dummy['Fancy'] = title_dummy['Jonkheer']+title_dummy['the Countess']
title_dummy = title_dummy.drop(['Jonkheer','the Countess'], axis = 1)
 Total = Total.drop('Title', axis = 1)
 Total = pd.concat([Total, title_dummy], axis = 1)
 Total<filter>
MIXED_PRECISION = False
XLA_ACCELERATE = False
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )
Age_Total = Total
Age_Total = Age_Total.dropna()
Age_Total
def nans(df): return df[df.isnull().any(axis=1)]
Age_Total_Predict = nans(Total)
 Age_Total_Predict<drop_column>
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']
col = list(Age_Total.columns)
 col.remove('Age')
 col.remove('Survived')
 Age_Total[col]<normalization>
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), ', should 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()
x = Age_Total[col]
x_test = Age_Total_Predict[col]
y_train = Age_Total['Age']
x_train = StandardScaler().fit(x ).transform(x)
 x_test = StandardScaler().fit(x_test ).transform(x_test )<train_on_grid>
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
lasso = LassoCV(alphas = [0.01, 0.05, 0.1, 0.15,0.5] ).fit(x_train, y_train)
 alpha = 0.1
lasso_tuned = LassoCV(alphas = [0.8*alpha, 0.9*alpha, alpha, 1.1*alpha, 1.2*alpha] ).fit(x_train, y_train )<train_on_grid>
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_id_tfrecord(example):
LABELED_ID_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, LABELED_ID_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 idnum = example['id']
return image, label, idnum
svm_age = svm.SVR(kernel = 'rbf')
 svm_age.fit(x_train, y_train )<train_on_grid>
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
ridge = Ridge()
parameters = {'alpha': [1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20]}
ridge_age = GridSearchCV(ridge, parameters, scoring = 'neg_root_mean_squared_error', cv=5)
 ridge_age.fit(x_train, y_train)
 print(ridge_age.best_params_)
 print(-ridge_age.best_score_ )<compute_train_metric>
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_id_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
print('The average R squared score for the lasso model is:', -cross_val_score(lasso_tuned, x_train, y_train, scoring ='neg_root_mean_squared_error' ).mean())
 print('The average R squared score for the svm model is:', -cross_val_score(svm_age, x_train, y_train, scoring ='neg_root_mean_squared_error' ).mean())
 print('The average R squared score for the ridge model is:', -ridge_age.best_score_)
<predict_on_test>
def get_training_dataset() :
train = load_dataset(TRAINING_FILENAMES, labeled = True)
 train = train.map(lambda image, label, idnum: [image, label])
 train = train.repeat()
train = train.shuffle(2048)
 train = train.batch(BATCH_SIZE)
 train = train.prefetch(AUTO)
 return train
def get_training_dataset_preview(ordered = True):
train = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = ordered)
 train = train.batch(BATCH_SIZE)
 train = train.cache()
train = train.prefetch(AUTO)
 return train
predicted_ages = pd.DataFrame(lasso_tuned.predict(x_test), columns=['Age'])
 Age_Total_Predict.drop('Age',axis = 1)
 Age_Total_Predict = Age_Total_Predict.assign(Age = lasso_tuned.predict(x_test ).round())
 Age_Total_Predict['PassengerId'] = Age_Total_Predict.index
Age_Total_Predict = Age_Total_Predict.reset_index(drop=True)
 Age_Total_Predict<feature_engineering>
def get_validation_dataset(ordered = False):
validation = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = ordered)
 validation = validation.map(lambda image, label, idnum: [image, label])
 validation = validation.batch(BATCH_SIZE)
 validation = validation.cache()
validation = validation.prefetch(AUTO)
 return validation
Age_Total['PassengerId'] = Age_Total.index
Age_Total = Age_Total.reset_index(drop=True)
 Total_Processed = pd.concat([Age_Total_Predict,Age_Total])
 Total_Processed.set_index('PassengerId', inplace = True)
 Total_Processed = Total_Processed.sort_index()
fix_neg = lambda x: x + 11.148738330664404 if x < 0 else x
Total_Processed['Age'] = Total_Processed['Age'].apply(fix_neg)
 Total_Processed<split>
def get_test_dataset(ordered = False):
test = load_dataset(TEST_FILENAMES, labeled = False, ordered = ordered)
 test = test.batch(BATCH_SIZE)
 test = test.prefetch(AUTO)
 return test
Train_Processed = Total_Processed[:len(train)]
Test_Processed = Total_Processed[len(train):]<prepare_x_and_y>
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))
col = list(Train_Processed.columns)
 col.remove('Survived')
 x_train = Train_Processed[col]
y_train = Train_Processed['Survived']
y_train = y_train.astype('int')
 x_final = Test_Processed[col]
x_train = preprocessing.StandardScaler().fit(x_train ).transform(x_train)
 x_final= preprocessing.StandardScaler().fit(x_final ).transform(x_final )<train_on_grid>
train_dataset_aug = get_training_dataset()
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
k_score = []
k_range = range(1,16)
 for k in k_range:
neigh = KNeighborsClassifier(n_neighbors = k ).fit(x_train,y_train)
 score = -cross_val_score(neigh, x_train, y_train, scoring ='neg_root_mean_squared_error' ).mean()
k_score.append(score)
 Scores = pd.DataFrame(k_score, columns = ['Score'])
 Scores.index += 1
Scores.sort_values('Score' )<save_to_csv>
validation_dataset_aug = get_validation_dataset()
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
neigh = KNeighborsClassifier(n_neighbors = 8 ).fit(x_train,y_train)
 y_KNN = pd.DataFrame(neigh.predict(x_final), columns = ['Survived'])
 y_KNN = y_KNN.assign(PassengerId = Test_Processed.index)
 cols = y_KNN.columns.tolist()
cols = cols[-1:] + cols[:-1]
y_KNN = y_KNN[cols]
filename = 'Titanic Predictions KNN.csv'
y_KNN.to_csv(filename,index=False)
 print('Saved file: ' + filename )<compute_train_metric>
test_dataset_aug = get_test_dataset()
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
svm_lin = svm.SVC(kernel='linear' ).fit(x_train, y_train)
 print('The average R squared score for the svm_lin is:', cross_val_score(svm_lin, x_train, y_train, scoring ='accuracy' ).mean())
 svm_rbf = svm.SVC(kernel='rbf' ).fit(x_train, y_train)
 print('The average R squared score for the svm_rbf is:', cross_val_score(svm_rbf, x_train, y_train, scoring ='accuracy' ).mean() )<train_on_grid>
def lrfn(epoch):
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
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(25 if EPOCHS<25 else 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]))
gammas = [0.01,0.1, 1, 10, 100]
for gamma in gammas:
svm_rbf = svm.SVC(kernel='rbf' ).fit(x_train, y_train)
 print('The average R squared score for the svm_rbf with a gamma of',gamma,' is:', cross_val_score(svm_rbf, x_train, y_train, scoring ='accuracy' ).mean() )<compute_train_metric>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape =(512, 512, 3),
weights = 'imagenet',
include_top = False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'] 
)
 model.summary()
model.save('ML_finalproject.h5' )
cs = [0.65,0.67]
for c in cs:
svm_rbf = svm.SVC(kernel='rbf', C=c ).fit(x_train, y_train)
 print('The average R squared score for the svm_rbf with a C of',c,' is:', cross_val_score(svm_rbf, x_train, y_train, scoring ='accuracy' ).mean() )<save_to_csv>
gc.enable()
def get_training_dataset_raw() :
dataset = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = False)
 return dataset
raw_training_dataset = get_training_dataset_raw()
label_counter = Counter()
for images, labels, id in raw_training_dataset:
label_counter.update([labels.numpy() ])
 del raw_training_dataset
TARGET_NUM_PER_CLASS = 122
def get_weight_for_class(class_id):
counting = label_counter[class_id]
weight = TARGET_NUM_PER_CLASS / counting
return weight
weight_per_class = {class_id: get_weight_for_class(class_id)for class_id in range(104)}
svm_rbf = svm.SVC(kernel='rbf' ).fit(x_train, y_train)
 y_SVM = pd.DataFrame(svm_rbf.predict(x_final), columns = ['Survived'])
 y_SVM = y_SVM.assign(PassengerId = Test_Processed.index)
 cols = y_SVM.columns.tolist()
cols = cols[-1:] + cols[:-1]
y_SVM = y_SVM[cols]
filename = 'Titanic Predictions SVM.csv'
y_SVM.to_csv(filename,index=False)
 print('Saved file: ' + filename )<compute_test_metric>
history = model.fit(
 get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
class_weight = weight_per_class
)
print('The average accuracy score for the SVM model is:', cross_val_score(svm_rbf, x_train, y_train, scoring ='accuracy' ).mean())
<install_modules>
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 = model.predict(images_ds)
 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 )
!pip install category_encoders<install_modules>
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))
<import_modules><EOS> 
test_ds = get_test_dataset(ordered = True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis = -1)
 print(predictions)
 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')
 test = pd.DataFrame({"id": test_ids, "label": predictions})
 print(test.head)
 test.to_csv("submission.csv",index = False )