{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"},{"sourceId":1138814,"sourceType":"datasetVersion","datasetId":601927},{"sourceId":10421266,"sourceType":"datasetVersion","datasetId":6459084},{"sourceId":216869094,"sourceType":"kernelVersion"}],"dockerImageVersionId":30804,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Ensemble DenseNet201 и EfficientNetV2M\n\nhttps://www.kaggle.com/code/mashakholodenko/start-with-ensemble-v3?scriptVersionId=212208041  \n*  4 версия блокнота DenseNet201+EfficientNetB7 GPU \n*  224, 224 EPOCHS=30 BATCH_SIZE=16 adam\n*  LB нет, потому что соревнование не принимает долгие блокноты на GPU\n*  баг с TPU => запустился на tpu только в новом окружении, но возникли конфликты библиотек\n\nhttps://www.kaggle.com/code/mashakholodenko/start-with-ensemble-v3?scriptVersionId=216731772\n*  13-14 версия блокнота DenseNet201+InceptionResNetV2 TPU \n*  224, 224 EPOCHS=35 BATCH_SIZE=128 adam\n*  LB 0.93873 V13 (bestalpha умножение), 0.93124 V14 (bestalpha сред.арифм)\n\nhttps://www.kaggle.com/code/mashakholodenko/start-with-ensemble-v3/notebook?scriptVersionId=216801098\n*  15 версия блокнота DenseNet201+EfficientNetB7 noisy-student TPU 3.5.0 keras \n*  224, 224 EPOCHS=35 BATCH_SIZE=128 adam\n*  LB ----- (bestalpha сред.арифм) не получилось, ошибка в бестальфе дурацкой\n*  EPOCHS=23 EfficientNetB7 метрика уже останавливает рост\n*  обновлен датасет, правильное добавление дополнительного датасета\n\nhttps://www.kaggle.com/code/mashakholodenko/start-with-ensemble-v3?scriptVersionId=216869094\n*  17 версия блокнота DenseNet201+EfficientNetV2M TPU 3.5.0 keras \n*  224, 224 EPOCHS=35 BATCH_SIZE=128 adam\n*  LB 0.97532 \n*  EfficientNetB7 очень жирный и долгий \n  \nhttps://www.kaggle.com/code/mashakholodenko/start-with-pre-train \n* DenseNet201 GPU\n* 224, 224 EPOCHS=30 BATCH_SIZE=8 adam\n* LB 0.92348\n\nhttps://www.kaggle.com/code/mashakholodenko/start-with-more-data-ensemble-v4\n* черновик для ансамбля с доп датасетом, создан отдельно из-за бага с TPU kernel died (баг из-за старой версии окружения форкнутого блокнота)\n* 15 версия Start_with_ensemble_v3 полное вычисление LB -----\n* 17 версия Start_with_ensemble_v3 загрузка сабмита LB 0.97532\n* объединение 3хDenseNet201+EfficientNetB7+EfficientNetV2M+InceptionResNetV2 LB -----","metadata":{}},{"cell_type":"markdown","source":"# Вычисление 15 версии \nПредсказание модели 15-ой версии https://www.kaggle.com/code/mashakholodenko/start-with-ensemble-v3/output?scriptVersionId=216801098\n\nВынесен в датасет так, кагл не дает скачать output старых версий https://www.kaggle.com/datasets/mashakholodenko/efficientnetb7-densenet201/data","metadata":{}},{"cell_type":"code","source":"# !cp /kaggle/input/start-with-ensemble-v3/submission.csv /kaggle/working/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:09:50.417122Z","iopub.execute_input":"2025-01-10T16:09:50.417702Z","iopub.status.idle":"2025-01-10T16:09:50.421596Z","shell.execute_reply.started":"2025-01-10T16:09:50.417669Z","shell.execute_reply":"2025-01-10T16:09:50.420650Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# !pip cache purge\n!pip install -q efficientnet\n# !pip install virtualenv\n# !virtualenv myenv\n# !source myenv/bin/activate\n!pip install keras==3.5.0 --no-deps\n# !pip install keras==3.5.0 tensorflow==2.16.1\n# !pip install kaggle","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:09:50.567426Z","iopub.execute_input":"2025-01-10T16:09:50.568019Z","iopub.status.idle":"2025-01-10T16:10:04.356228Z","shell.execute_reply.started":"2025-01-10T16:09:50.567988Z","shell.execute_reply":"2025-01-10T16:10:04.355368Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport tensorflow as tf\n# from tensorflow.keras.applications.densenet import DenseNet201\nimport efficientnet.tfkeras as efn\nfrom tensorflow.keras.applications import EfficientNetB7, EfficientNetV2M\n# import tensorflow_addons as tfa\n# from tensorflow_addons.optimizers import AdamW\nfrom tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.layers import GlobalAveragePooling2D,Dense\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\n#  библиотека для работы с наборами данных на Kaggle\n# from kaggle_datasets import KaggleDatasets\nimport re\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n%matplotlib inline \n\nimport warnings\nwarnings.filterwarnings('ignore')\n# import absl.logging\n# absl.logging.set_verbosity(absl.logging.ERROR)\n# import os\n# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # Уровень 2 — только ошибки\n# # Отключение вывода логов XLA\n# os.environ['XLA_FLAGS'] = '--xla_disable_jit=1'\n\nprint(\"Tensorflow version \" + tf.__version__)\nimport keras\nprint(\"keras \" + keras.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:04.358430Z","iopub.execute_input":"2025-01-10T16:10:04.358847Z","iopub.status.idle":"2025-01-10T16:10:16.127103Z","shell.execute_reply.started":"2025-01-10T16:10:04.358787Z","shell.execute_reply":"2025-01-10T16:10:16.126284Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# from kaggle_secrets import UserSecretsClient\n\n# # Получаем секрет\n# user_secrets = UserSecretsClient()\n# kaggle_json = user_secrets.get_secret(\"kaggle.json\")\n\n# # Создаем директорию для файла kaggle.json\n# import os\n# os.makedirs(\"/root/.kaggle\", exist_ok=True)\n\n# # Записываем секрет в файл\n# with open('/root/.kaggle/kaggle.json', 'w') as f:\n#     f.write(kaggle_json)\n\n# # Устанавливаем правильные права доступа\n# os.chmod('/root/.kaggle/kaggle.json', 0o600)\n\n# print(\"Файл kaggle.json успешно создан.\")\n\n# !kaggle kernels output mashakholodenko/start-with-ensemble-v3 -p ./output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.128355Z","iopub.execute_input":"2025-01-10T16:10:16.129010Z","iopub.status.idle":"2025-01-10T16:10:16.133645Z","shell.execute_reply.started":"2025-01-10T16:10:16.128970Z","shell.execute_reply":"2025-01-10T16:10:16.132731Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Определяем, какой ускоритель можем использовать","metadata":{}},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n# Обнаружение оборудования, возврат соответствующей стратегии распространения: TPU, GPU, CPU\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # Обнаружение TPU. Параметры среды не требуются, если задана переменная среды TPU_NAME. На Kaggle это всегда так.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # стратегия распространения по умолчанию в Tensorflow. Работает на CPU и одном GPU.\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.135356Z","iopub.execute_input":"2025-01-10T16:10:16.135664Z","iopub.status.idle":"2025-01-10T16:10:16.165513Z","shell.execute_reply.started":"2025-01-10T16:10:16.135638Z","shell.execute_reply":"2025-01-10T16:10:16.164606Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Параметры","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224] \n# IMAGE_SIZE = [512, 512] # при таком размере графическому процессору не хватит памяти. Используйте TPU\n# 224 вытягивает на гпу с BATCH_SIZE = 16 до 30 эпох\n# EPOCHS = 35\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nEPOCHS = 35\nif tpu:\n    BATCH_SIZE = 16 * strategy.num_replicas_in_sync\nelse:\n    BATCH_SIZE = 128 * strategy.num_replicas_in_sync\n    EPOCHS = 2\n\n\nSEED = 752\n\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntf.random.set_seed(SEED)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.166850Z","iopub.execute_input":"2025-01-10T16:10:16.167483Z","iopub.status.idle":"2025-01-10T16:10:16.177693Z","shell.execute_reply.started":"2025-01-10T16:10:16.167443Z","shell.execute_reply":"2025-01-10T16:10:16.177004Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Загрузка датасета и допдатасета","metadata":{}},{"cell_type":"code","source":"# GCS_DS_PATH = KaggleDatasets().get_gcs_path(\"tpu-getting-started\") #получаем путь к наборам данных\n# MORE_IMAGES_GCS_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')\nGCS_DS_PATH = \"/kaggle/input/tpu-getting-started\"\nGCS_DS_PATH_EXT  = \"/kaggle/input/tf-flower-photo-tfrec\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.178707Z","iopub.execute_input":"2025-01-10T16:10:16.178975Z","iopub.status.idle":"2025-01-10T16:10:16.192633Z","shell.execute_reply.started":"2025-01-10T16:10:16.178951Z","shell.execute_reply":"2025-01-10T16:10:16.191877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"GCS_PATH_SELECT = { # available image sizes\n    192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',\n    224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',\n    331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',\n    512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n}\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\n\n# # External data\n# GCS_PATH_SELECT_EXT = {\n#     192: '/tfrecords-jpeg-192x192',\n#     224: '/tfrecords-jpeg-224x224',\n#     331: '/tfrecords-jpeg-331x331',\n#     512: '/tfrecords-jpeg-512x512'\n# }\n# GCS_PATH_EXT = GCS_PATH_SELECT_EXT[IMAGE_SIZE[0]]\n\n# IMAGENET_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/imagenet' + GCS_PATH_EXT + '/*.tfrec')\n# INATURELIST_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/inaturalist' + GCS_PATH_EXT + '/*.tfrec')\n# OPENIMAGE_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/openimage' + GCS_PATH_EXT + '/*.tfrec')\n# OXFORD_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/oxford_102' + GCS_PATH_EXT + '/*.tfrec')\n# TENSORFLOW_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/tf_flowers' + GCS_PATH_EXT + '/*.tfrec')\n\n# ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES\n\n# TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')\n\n# TRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.193577Z","iopub.execute_input":"2025-01-10T16:10:16.193883Z","iopub.status.idle":"2025-01-10T16:10:16.237735Z","shell.execute_reply.started":"2025-01-10T16:10:16.193847Z","shell.execute_reply":"2025-01-10T16:10:16.236854Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Аугментация\n\nчасть взята отсюда\nhttps://www.kaggle.com/code/luongduongminh/effnet-densenet#Random-blockout-augmentation\n\nhttps://www.kaggle.com/code/lkatran/more-data-with-densenet-v2","metadata":{}},{"cell_type":"code","source":"def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):\n    p=random.random()\n    if p>=0.25:\n        w, h, c = IMAGE_SIZE[0], IMAGE_SIZE[1], 3\n        origin_area = tf.cast(h*w, tf.float32)\n\n        e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)), tf.int32)\n        e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)), tf.int32)\n\n        e_height_h = tf.minimum(e_size_h, h)\n        e_width_h = tf.minimum(e_size_h, w)\n\n        erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)\n        erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)\n\n        erase_area = tf.zeros(shape=[erase_height, erase_width, c])\n        erase_area = tf.cast(erase_area, tf.uint8)\n\n        pad_h = h - erase_height\n        pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)\n        pad_bottom = pad_h - pad_top\n\n        pad_w = w - erase_width\n        pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)\n        pad_right = pad_w - pad_left\n\n        erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)\n        erase_mask = tf.squeeze(erase_mask, axis=0)\n        erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))\n\n        return tf.cast(erased_img, img.dtype)\n    else:\n        return tf.cast(img, img.dtype)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.239111Z","iopub.execute_input":"2025-01-10T16:10:16.239380Z","iopub.status.idle":"2025-01-10T16:10:16.247586Z","shell.execute_reply.started":"2025-01-10T16:10:16.239356Z","shell.execute_reply":"2025-01-10T16:10:16.246745Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Загружаем данные\n\nЭти данные загружаются из Kaggle и автоматически сегментируются для максимального распараллеливания.","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef data_augment(image, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n\n    image = tf.image.random_flip_left_right(image, seed=SEED)\n    image = random_blockout(image)\n    return image, label   \n\n# def get_training_dataset():\n#     dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n#     dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n#     dataset = dataset.repeat() # the training dataset must repeat for several epochs\n#     dataset = dataset.shuffle(2048)\n#     dataset = dataset.batch(BATCH_SIZE)\n#     dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n#     return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\n\n# training_dataset = get_training_dataset()\n# validation_dataset = get_validation_dataset()\n\nNUM_TRAINING_IMAGES = 68094\n# NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nVALIDATION_STEPS = -(-NUM_VALIDATION_IMAGES // BATCH_SIZE)\nTEST_STEPS = -(-NUM_TEST_IMAGES // BATCH_SIZE)  \n\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\nprint('STEPS_PER_EPOCH', STEPS_PER_EPOCH)\nprint('TEST_STEPS  {}, VALIDATION_STEPS {}'.format(TEST_STEPS , VALIDATION_STEPS))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.248903Z","iopub.execute_input":"2025-01-10T16:10:16.249161Z","iopub.status.idle":"2025-01-10T16:10:16.266513Z","shell.execute_reply.started":"2025-01-10T16:10:16.249137Z","shell.execute_reply":"2025-01-10T16:10:16.265680Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"validation_size = round(NUM_VALIDATION_IMAGES / BATCH_SIZE)\ntest_size= round(NUM_TEST_IMAGES / BATCH_SIZE)\ntrain_size= round(NUM_TRAINING_IMAGES / BATCH_SIZE)\nprint(\"Train size:\", train_size)   \nprint(\"Validation size:\", validation_size)\nprint(\"Test size:\", test_size)             ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.268735Z","iopub.execute_input":"2025-01-10T16:10:16.269068Z","iopub.status.idle":"2025-01-10T16:10:16.281387Z","shell.execute_reply.started":"2025-01-10T16:10:16.269043Z","shell.execute_reply":"2025-01-10T16:10:16.280542Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Построить модель на TPU","metadata":{}},{"cell_type":"code","source":"# # функция управляющая изменениями шага обучения в процессе тренировки нейронной сети\n# LR_START = 0.00001\n# LR_MAX = 0.00005 * strategy.num_replicas_in_sync#0.0001\n# LR_MIN = 0.00001\n# LR_RAMPUP_EPOCHS = 5\n# LR_SUSTAIN_EPOCHS = 0\n# LR_EXP_DECAY = .75\n\n# def lrfn(epoch):\n#     if epoch < LR_RAMPUP_EPOCHS:\n#         lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n#     elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n#         lr = LR_MAX\n#     else:\n#         lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n#     return lr\n    \n# lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\n# # построим график изменения шага обучение в зависимости от эпох\n# rng = [i for i in range(EPOCHS)]\n# y = [lrfn(x) for x in rng]\n# plt.plot(rng, y)\n# print(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.282636Z","iopub.execute_input":"2025-01-10T16:10:16.283016Z","iopub.status.idle":"2025-01-10T16:10:16.559231Z","shell.execute_reply.started":"2025-01-10T16:10:16.282978Z","shell.execute_reply":"2025-01-10T16:10:16.558343Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Проверка данных\n# train_dataset = get_training_dataset()\nval_dataset = get_validation_dataset()\ntest_dataset = get_test_dataset()\n# print(train_dataset, '\\n ', val_dataset)\nprint(test_dataset, '\\n ', val_dataset)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:16.560143Z","iopub.execute_input":"2025-01-10T16:10:16.560394Z","iopub.status.idle":"2025-01-10T16:10:17.476622Z","shell.execute_reply.started":"2025-01-10T16:10:16.560371Z","shell.execute_reply":"2025-01-10T16:10:17.475762Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"##  Веса EfficientNetV2M","metadata":{}},{"cell_type":"code","source":"with strategy.scope():\n    efficientnet = EfficientNetV2M(input_shape=[*IMAGE_SIZE, 3], \n                                   weights='imagenet', \n                                   include_top=False)\n    efficientnet.trainable = True  # Размораживаем веса для fine-tuning\n\n    model1 = Sequential([\n        efficientnet,\n        GlobalAveragePooling2D(),\n        Dense(104, activation='softmax')  # 104 — число классов\n    ])\n\n    model1.compile(\n        optimizer=tf.keras.optimizers.Adam(),\n        loss='sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n\n    model1.load_weights(\"/kaggle/input/start-with-ensemble-v3/EfficientNetV2M_best.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:10:17.477738Z","iopub.execute_input":"2025-01-10T16:10:17.478118Z","iopub.status.idle":"2025-01-10T16:11:41.612263Z","shell.execute_reply.started":"2025-01-10T16:10:17.478080Z","shell.execute_reply":"2025-01-10T16:11:41.611395Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Веса DenseNet201","metadata":{}},{"cell_type":"code","source":"with strategy.scope():\n    densenet = tf.keras.applications.DenseNet201(input_shape=[*IMAGE_SIZE, 3], \n                                                 weights='imagenet', \n                                                 include_top=False)\n    densenet.trainable = True\n    \n    model2 = tf.keras.Sequential([\n        densenet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \n    model2.compile(\n        optimizer=tf.keras.optimizers.Adam(),\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n\n    model2.load_weights(\"/kaggle/input/start-with-ensemble-v3/densenet201_best.keras\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:11:41.613846Z","iopub.execute_input":"2025-01-10T16:11:41.614674Z","iopub.status.idle":"2025-01-10T16:12:17.260431Z","shell.execute_reply.started":"2025-01-10T16:11:41.614631Z","shell.execute_reply":"2025-01-10T16:12:17.259469Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Вычислите свои прогнозы на тестовом наборе!\n\nCоздадим файл, который можно будет отправить на конкурс.","metadata":{}},{"cell_type":"markdown","source":"##   Best alpha","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import f1_score\nval_dataset = get_validation_dataset()\nimages_ds = val_dataset.map(lambda image, label: image)\nlabels_ds = val_dataset.map(lambda image, label: label).unbatch()\nval_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() # get everything as one batch","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:12:17.261977Z","iopub.execute_input":"2025-01-10T16:12:17.262273Z","iopub.status.idle":"2025-01-10T16:12:21.700187Z","shell.execute_reply.started":"2025-01-10T16:12:17.262247Z","shell.execute_reply":"2025-01-10T16:12:21.699361Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"m1 = model1.predict(images_ds, verbose=2)\nm2 = model2.predict(images_ds, verbose=2)\nscores = []\nfor alpha in np.linspace(0,1,100):\n    val_probabilities = alpha*m1+(1-alpha)*m2\n    val_predictions = np.argmax(val_probabilities, axis=-1)\n    scores.append(f1_score(val_labels, val_predictions, labels=range(104), average='macro'))\n\nbest_alpha = np.argmax(scores)/100\n    \nprint('Best alpha: ' + str(best_alpha))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:13:02.079855Z","iopub.execute_input":"2025-01-10T16:13:02.080552Z","iopub.status.idle":"2025-01-10T16:13:55.495980Z","shell.execute_reply.started":"2025-01-10T16:13:02.080517Z","shell.execute_reply":"2025-01-10T16:13:55.495063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cm_probabilities_big_alpha = best_alpha * m1 + (1-best_alpha) * m2\ncm_probabilities_low_alpha = best_alpha * m2 + (1-best_alpha) * m1\n    \ncm_probabilities=[cm_probabilities_big_alpha, cm_probabilities_low_alpha]\n\n# for i in cm_probabilities:\n#     val_predictions = np.argmax(i, axis=-1)\n#     # cmat = confusion_matrix(val_labels, val_predictions, labels=range(104))\n#     score = f1_score(val_labels, val_predictions, labels=range(104), average='macro')\n#     precision = precision_score(val_labels, val_predictions, labels=range(104), average='macro')\n#     recall = recall_score(val_labels, val_predictions, labels=range(104), average='macro')\n#     #cmat = (cmat.T / cmat.sum(axis=1)).T # normalized\n#     # display_confusion_matrix(cmat, score, precision, recall)\n#     # print(cmat)\n#     print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))\n\nval_predictions1 = np.argmax(cm_probabilities_big_alpha, axis=-1)\nscore1 = f1_score(val_labels, val_predictions1, labels=range(104), average='macro')\nprecision1 = precision_score(val_labels, val_predictions1, labels=range(104), average='macro')\nrecall1 = recall_score(val_labels, val_predictions1, labels=range(104), average='macro')\nprint('big_alpha: f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score1, precision1, recall1))\n\nval_predictions2 = np.argmax(cm_probabilities_low_alpha, axis=-1)\nscore2 = f1_score(val_labels, val_predictions2, labels=range(104), average='macro')\nprecision2 = precision_score(val_labels, val_predictions2, labels=range(104), average='macro')\nrecall2 = recall_score(val_labels, val_predictions2, labels=range(104), average='macro')\nprint('low_alpha: f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score2, precision2, recall2))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:13:55.522688Z","iopub.execute_input":"2025-01-10T16:13:55.522985Z","iopub.status.idle":"2025-01-10T16:13:55.547589Z","shell.execute_reply.started":"2025-01-10T16:13:55.522958Z","shell.execute_reply":"2025-01-10T16:13:55.546502Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# print(type(val_labels))\n# print(val_labels.shape)\n# print(val_labels[:20])  # Вывод первых 5 элементов","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:12:49.315847Z","iopub.status.idle":"2025-01-10T16:12:49.316275Z","shell.execute_reply.started":"2025-01-10T16:12:49.316052Z","shell.execute_reply":"2025-01-10T16:12:49.316075Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Предсказание\nPredictions using Test Time Augmentation (TTA)","metadata":{}},{"cell_type":"code","source":"TTA_NUM = 5\n# Поскольку мы разделяем набор данных и выполняем итерацию отдельно для изображений и идентификаторов, порядок имеет значение.\ndef predict_tta(model, n_iter):\n    probs  = []\n    for i in range(n_iter):\n        test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n        test_images_ds = test_ds.map(lambda image, idnum: image)\n        probs.append(model.predict(test_images_ds,verbose=2))\n        \n    return probs\n\n# def run_inference(model):\n#     test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n#     test_images_ds = test_ds.map(lambda image, idnum: image)\n#     preds = model.predict(test_images_ds,verbose=2)\n#     return preds\n\nprint('Вычисляем предсказания...')\ntest_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\ntest_images_ds = test_ds.map(lambda image, idnum: image)\n# best_alpha = 0.1\n# best_alpha = 0.48\n\nprint('предсказания модели 1...')\nprobabilities1 = np.mean(predict_tta(model1, TTA_NUM), axis=0)\n# probabilities1 = run_inference(model1)\nprint('завершение предсказания модели 1...')\n\nprint('предсказания модели 2...')\nprobabilities2 = np.mean(predict_tta(model2, TTA_NUM), axis=0)\n# probabilities2 = run_inference(model2)\nprint('завершение предсказания модели 2...')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:13:55.549337Z","iopub.execute_input":"2025-01-10T16:13:55.549607Z","iopub.status.idle":"2025-01-10T16:15:26.051016Z","shell.execute_reply.started":"2025-01-10T16:13:55.549581Z","shell.execute_reply":"2025-01-10T16:15:26.050022Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print('расчет probabilities...')\nprobabilities_big_alpha = best_alpha * probabilities1 + (1 - best_alpha) * probabilities2\nprobabilities_low_alpha = best_alpha * probabilities2 + (1 - best_alpha) * probabilities1\nprobabilities_2 = (probabilities1 + probabilities2)/2\nprobabilities_3 = np.maximum(probabilities1, probabilities2)\n\n\npredictions_big_alpha = np.argmax(probabilities_big_alpha, axis=-1)\npredictions_low_alpha = np.argmax(probabilities_low_alpha, axis=-1)\npredictions2 = np.argmax(probabilities_2, axis=-1)\npredictions3 = np.argmax(probabilities_3, axis=-1)\n\nprint('predictions big_alpha', predictions_big_alpha)\nprint('predictions low_alpha', predictions_low_alpha)\nprint('predictions2', predictions2)\nprint('predictions3', predictions3)\n\n \nprint('Создание файла submission.csv...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # все в одной партии\n\nif score2 > score1:\n    np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions_big_alpha]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n    np.savetxt('submission_4.csv', np.rec.fromarrays([test_ids, predictions_low_alpha]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\nelse:\n    np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions_low_alpha]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n    np.savetxt('submission_4.csv', np.rec.fromarrays([test_ids, predictions_big_alpha]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n\nnp.savetxt('submission2.csv', np.rec.fromarrays([test_ids, predictions2]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\nnp.savetxt('submission3.csv', np.rec.fromarrays([test_ids, predictions3]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:15:28.636175Z","iopub.execute_input":"2025-01-10T16:15:28.636538Z","iopub.status.idle":"2025-01-10T16:15:31.134992Z","shell.execute_reply.started":"2025-01-10T16:15:28.636493Z","shell.execute_reply":"2025-01-10T16:15:31.134261Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Сравнение расчета предсказаний","metadata":{}},{"cell_type":"code","source":"# Загрузка CSV файлов\nsubmission = pd.read_csv('submission.csv')\nsubmission2 = pd.read_csv('submission2.csv')\nsubmission3 = pd.read_csv('submission3.csv')\nsubmission4 = pd.read_csv('submission_4.csv')\n\n# Объединяем DataFrame по 'id'\nmerged_1 = submission.merge(submission2, on='id', suffixes=('_1', '_mean'))\nmerged_2 = merged_1.merge(submission3, on='id', suffixes=('_mean', '_max'))\nmerged_all = merged_2.merge(submission4, on='id', suffixes=('_max', '_4'))\n\n# Фильтруем результаты, чтобы найти строки, где метки не совпадают\nmismatches = merged_all[\n    (merged_all['label_1'] != merged_all['label_mean']) | \n    (merged_all['label_1'] != merged_all['label_4']) | \n    (merged_all['label_mean'] != merged_all['label_4']) |\n    (merged_all['label_max'] != merged_all['label_4']) \n]\n\n# Выводим id и label из всех трех DataFrame\noutput = mismatches[['id', 'label_1', 'label_mean','label_max', 'label_4']]\n\n# Печатаем или сохраняем результат\nprint(output)\n\n# Сохраняем в новый CSV файл\noutput.to_csv('mismatches.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:15:31.136715Z","iopub.execute_input":"2025-01-10T16:15:31.137003Z","iopub.status.idle":"2025-01-10T16:15:31.199312Z","shell.execute_reply.started":"2025-01-10T16:15:31.136977Z","shell.execute_reply":"2025-01-10T16:15:31.198415Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Решение с учетом согласия","metadata":{}},{"cell_type":"code","source":"merged_all['final_label'] = merged_all.apply(\n    lambda row: row['label_mean'] if (row['label_mean'] == row['label_4']) else row['label_1'],\n    axis=1\n)\n\n# Сохраняем итоговые предсказания\nfinal_submission = pd.DataFrame({'id': merged_all['id'], 'label': merged_all['final_label']})\nfinal_submission.to_csv('final_submission.csv', index=False)\n# Печатаем или сохраняем результат\nfinal_submission","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:15:31.200457Z","iopub.execute_input":"2025-01-10T16:15:31.200737Z","iopub.status.idle":"2025-01-10T16:15:31.288739Z","shell.execute_reply.started":"2025-01-10T16:15:31.200711Z","shell.execute_reply":"2025-01-10T16:15:31.287743Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission_final = pd.read_csv('final_submission.csv')\nmerged_final = submission.merge(submission_final, on='id', suffixes=('_big_alpha', '_final'))\nmismatches_final = merged_final[(merged_final['label_big_alpha'] != merged_final['label_final'])] \n# Выводим id и label из всех трех DataFrame\noutput_final = mismatches_final[['id', 'label_big_alpha', 'label_final']]\n# Печатаем или сохраняем результат\nprint(output_final)\n\n# Сохраняем в новый CSV файл\noutput_final.to_csv('mismatches_final.csv', index=False)\n                     ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-10T16:15:31.290014Z","iopub.execute_input":"2025-01-10T16:15:31.290400Z","iopub.status.idle":"2025-01-10T16:15:31.310422Z","shell.execute_reply.started":"2025-01-10T16:15:31.290359Z","shell.execute_reply":"2025-01-10T16:15:31.309496Z"}},"outputs":[],"execution_count":null}]}