Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<init_hyperparams>
!pip install -q efficientnet
pp = pprint.PrettyPrinter(indent=4)
 models = {}
cv_split = ShuffleSplit(n_splits = 10, test_size =.3, train_size =.6, random_state = 0)
<train_on_grid>
%matplotlib inline
print("Tensorflow version " + tf.__version__ )
model_name = 'lrc_model'
models[model_name] = {}
model = LogisticRegressionCV(random_state=1, cv=10, max_iter=1000)
 model.fit(train_X, train_Y)
 models[model_name]['model'] = model
models[model_name]['crossval_score'] = model.score(train_X, train_Y, sample_weight=None)
 pp.pprint(models[model_name] )<train_model>
GCS_DS_PATH = KaggleDatasets().get_gcs_path("tpu-getting-started" )
model_name = 'dtc_model'
models[model_name] = {}
model = DecisionTreeClassifier(random_state=1)
 model.fit(train_X, train_Y)
 models[model_name]['model'] = model
models[model_name]['score'] = model.score(train_X, train_Y, sample_weight=None)
 models[model_name]['cross_val_score'] = cross_val_score(model, train_X, \
train_Y, scoring="accuracy", cv=10 ).mean()
pp.pprint(models[model_name] )<train_model>
IMAGE_SIZE = [331, 331]
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_name = 'rfc_model'
models[model_name] = {}
model = RandomForestClassifier(random_state=1)
 model.fit(train_X, train_Y)
 models[model_name]['model'] = model
models[model_name]['score'] = model.score(train_X, train_Y, sample_weight=None)
 models[model_name]['cross_val_score'] = cross_val_score(model, train_X, \
train_Y, scoring="accuracy", cv=10 ).mean()
pp.pprint(models[model_name] )<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
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))
model_name = 'lrc_model'
models[model_name]['param_grid'] = [
{'max_iter':[1000]}]
grid_search = GridSearchCV(models[model_name]['model'], models[model_name]['param_grid'], cv=10,
scoring='accuracy', return_train_score=True)
 grid_search.fit(train_X, train_Y)
 models[model_name]['best_params'] = grid_search.best_params_
models[model_name]['best_estimator'] = grid_search.best_estimator_
models[model_name]['best_score'] = grid_search.best_score_
pp.pprint(models )<train_on_grid>
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/more-data-with-densenet201/my_ef_net_b7.h5" )
model_name = 'dtc_model'
models[model_name]['param_grid'] = [
{'max_features': ['auto'], 'max_depth': [7,8,9], 'criterion': ['gini', 'entropy']}
]
grid_search = GridSearchCV(models[model_name]['model'], models[model_name]['param_grid'], cv=cv_split,
scoring='accuracy', return_train_score=True)
 grid_search.fit(train_X, train_Y)
 models[model_name]['best_params'] = grid_search.best_params_
models[model_name]['best_estimator'] = grid_search.best_estimator_
models[model_name]['best_score'] = grid_search.best_score_
pp.pprint(models[model_name] )<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(NASNetLarge)
 model2.load_weights("/kaggle/input/more-data-with-nasnetlarge/my_ef_net_b7.h5" )
<save_to_csv><EOS> 
test_ds = get_test_dataset(ordered=True)
 best_alpha = 0.6
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='' )