Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<choose_model_class>
%matplotlib inline
print("Tensorflow version " + tf.__version__ )
model_1 = build_model()<define_variables>
GCS_DS_PATH = KaggleDatasets().get_gcs_path("tpu-getting-started" )
utils.plot_model(model_1, to_file='model_1_plot.png', show_shapes=True, show_layer_names=True)
<choose_model_class>
IMAGE_SIZE = [512, 512]
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]]
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 SEED = 2020
model = define_model()
model.compile(loss = 'binary_crossentropy' , optimizer = 'adam' , metrics = ['accuracy' , 'mse'] )<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 get_validation_dataset() :
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)
 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_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 print('Dataset: {} validation images, {} unlabeled test images'.format(NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
def func(x , thres):
if x>thres:
return 1
else:
return 0
def save_csv(df , name):
pd.DataFrame(df ).to_csv(name , index = False)
 def train_model(data =data , model = model , train_data_x = [data.train_df_gaf , x_train_embeddings.numpy() , data.train_df,x_data] , train_data_y = y_data ,
bs = BATCH_SIZE , epochs_each_step = 1 ,total_epochs = 2 , vd = [[data.test_df_gaf , x_test_embeddings.numpy() , data.test_df , x_test], data.leaked_data.target.values] ,
verb = 2 , cbs = callbacks):
submit = []
for i in range(total_epochs//epochs_each_step):
model.fit(train_data_x , train_data_y , batch_size = bs , epochs = epochs_each_step ,validation_data = vd , verbose = verb , callbacks = cbs)
 data.submit_data['target'] = model.predict(vd[0])
 median = data.submit_data.sort_values(by = ['target'], ascending = True)['target'].values[1861]
data.submit_data.target = data.submit_data.target.apply(func , thres = median)
 f1_s= f1_score(data.leaked_data.target , data.submit_data.target)
 name = '/kaggle/working/disaster_submission_'+str(i)+'_f1_'+str(int(f1_s*10000)) +'.h5'
model.save(name)
 submit.append(data.submit_data)
 print("F1 Score of This Layer is ", f1_score(data.leaked_data.target , data.submit_data.target))
return submit<train_model>
def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
 model = Model(inputs=base_model.input, outputs=predictions)
 model.compile(
 optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
with strategy.scope() :
model1 = get_model(DenseNet201)
 model1.load_weights("/kaggle/input/start-with-densenet201/my_densenet_201.h5" )
submit = train_model()<choose_model_class>
def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
 model = Model(inputs=base_model.input, outputs=predictions)
 model.compile(
 optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
with strategy.scope() :
model2 = get_model(ResNet50)
 model2.load_weights("/kaggle/input/start-with-pre-train/my_ef_net_b7.h5" )
MLA = [
neighbors.KNeighborsClassifier(n_jobs = -1),
neighbors.NearestCentroid() ,
tree.DecisionTreeClassifier() ,
tree.ExtraTreeClassifier() ,
naive_bayes.GaussianNB() ,
naive_bayes.BernoulliNB() ,
semi_supervised.LabelPropagation() ,
discriminant_analysis.LinearDiscriminantAnalysis() ,
discriminant_analysis.QuadraticDiscriminantAnalysis() ,
svm.LinearSVC(multi_class='crammer_singer'),
svm.SVC(probability=True),
svm.NuSVC() ,
linear_model.LogisticRegressionCV(multi_class='multinomial'),
linear_model.RidgeClassifier() ,
linear_model.RidgeClassifierCV() ,
linear_model.Perceptron() ,
linear_model.PassiveAggressiveClassifier() ,
linear_model.SGDClassifier() ,
neural_network.MLPClassifier() ,
ensemble.RandomForestClassifier(n_jobs = -1),
ensemble.ExtraTreesClassifier(n_jobs = -1),
ensemble.AdaBoostClassifier() ,
ensemble.GradientBoostingClassifier() ,
ensemble.BaggingClassifier(n_jobs = -1),
gaussian_process.GaussianProcessClassifier(n_jobs = -1),
calibration.CalibratedClassifierCV() ,
]
MLA_new = [
linear_model.LogisticRegressionCV(multi_class='multinomial'),
ensemble.RandomForestClassifier() ,
linear_model.RidgeClassifier() ,
naive_bayes.BernoulliNB() ,
]<compute_train_metric>
val_dataset = get_validation_dataset()
images_ds = val_dataset.map(lambda image, label: image)
 labels_ds = val_dataset.map(lambda image, label: label ).unbatch()
val_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
m1 = model1.predict(images_ds)
 m2 = model2.predict(images_ds)
 scores = []
for alpha in np.linspace(0,1,100):
val_probabilities = alpha*m1+(1-alpha)*m2
val_predictions = np.argmax(val_probabilities, axis=-1)
 scores.append(f1_score(val_labels, val_predictions, labels=range(104), average='macro'))
best_alpha = np.argmax(scores)/100
print('Best alpha: ' + str(best_alpha))
<sort_values><EOS> 
test_ds = get_test_dataset(ordered=True)
 print('Вычисляем предсказания...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities1 = model1.predict(test_images_ds)
 probabilities2 = model2.predict(test_images_ds)
 probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Создание файла submission.csv...')
 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='' )