{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.8.16","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpu1vmV38","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"dockerImageVersionId":30445,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# TF 2.2 блокнот\n[По сути, это перевод стартового блокнота от команды TensorFlow](https://www.kaggle.com/philculliton/a-simple-petals-tf-2-2-notebook)","metadata":{}},{"cell_type":"code","source":"!pip install -q efficientnet","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:29:00.281151Z","iopub.execute_input":"2024-12-03T04:29:00.281402Z","iopub.status.idle":"2024-12-03T04:29:07.728124Z","shell.execute_reply.started":"2024-12-03T04:29:00.281380Z","shell.execute_reply":"2024-12-03T04:29:07.727064Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n# последовательная модель (стек слоев)\nfrom tensorflow.keras.models import Sequential, Model\n# полносвязный слой и слой выпрямляющий матрицу в вектор\nfrom tensorflow.keras.layers import Dense, Flatten, Input\n# слой выключения нейронов и слой нормализации выходных данных (нормализует данные в пределах текущей выборки)\nfrom tensorflow.keras.layers import Dropout, BatchNormalization, SpatialDropout2D, GaussianDropout\n# слои свертки и подвыборки\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, GlobalAveragePooling2D\n# работа с обратной связью от обучающейся нейронной сети\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n# вспомогательные инструменты\nfrom tensorflow.keras import utils\nfrom tensorflow.keras.regularizers import *\nimport numpy as np\nimport os\nfrom tensorflow.random import set_seed\ndef seed_everything(seed):\n    np.random.seed(seed)\n    set_seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n\nseed = 42\nseed_everything(seed)\n\n# работа с изображениями\nfrom tensorflow.keras.preprocessing import image\nimport matplotlib.pyplot as plt\n%matplotlib inline \n\n#  библиотека для работы с наборами данных на Kaggle\nfrom kaggle_datasets import KaggleDatasets\nimport matplotlib.pyplot as plt\n%matplotlib inline \nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:29:14.222520Z","iopub.execute_input":"2024-12-03T04:29:14.222902Z","iopub.status.idle":"2024-12-03T04:29:53.679766Z","shell.execute_reply.started":"2024-12-03T04:29:14.222871Z","shell.execute_reply":"2024-12-03T04:29:53.678827Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Определяем, какой ускоритель можем использовать","metadata":{}},{"cell_type":"code","source":"# Обнаружение оборудования, возврат соответствующей стратегии распространения: 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.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:29:53.681572Z","iopub.execute_input":"2024-12-03T04:29:53.682270Z","iopub.status.idle":"2024-12-03T04:30:02.876667Z","shell.execute_reply.started":"2024-12-03T04:29:53.682239Z","shell.execute_reply":"2024-12-03T04:30:02.875691Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Get my data path","metadata":{}},{"cell_type":"code","source":"# GCS_DS_PATH = KaggleDatasets().get_gcs_path() #получаем путь к наборам данных\nGCS_DS_PATH = \"/kaggle/input/tpu-getting-started\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:30:02.878422Z","iopub.execute_input":"2024-12-03T04:30:02.878891Z","iopub.status.idle":"2024-12-03T04:30:02.883200Z","shell.execute_reply.started":"2024-12-03T04:30:02.878849Z","shell.execute_reply":"2024-12-03T04:30:02.882294Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Set some parameters","metadata":{}},{"cell_type":"code","source":"# IMAGE_SIZE = [192, 192] # при таком размере графическому процессору не хватит памяти. Используйте TPU\n# IMAGE_SIZE = [512, 512] # при таком размере графическому процессору не хватит памяти. Используйте TPU\nIMAGE_SIZE = [224, 224] # при таком размере графическому процессору не хватит памяти. Используйте TPU\nEPOCHS = 15\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE # находим количество шагов за эпоху","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:30:02.886202Z","iopub.execute_input":"2024-12-03T04:30:02.886794Z","iopub.status.idle":"2024-12-03T04:30:02.899029Z","shell.execute_reply.started":"2024-12-03T04:30:02.886756Z","shell.execute_reply":"2024-12-03T04:30:02.898031Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Загружаем данные\n\nЭти данные загружаются из Kaggle и автоматически сегментируются для максимального распараллеливания.","metadata":{}},{"cell_type":"code","source":"# !pip install tensorflow-addons","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:30:02.900424Z","iopub.execute_input":"2024-12-03T04:30:02.900811Z","iopub.status.idle":"2024-12-03T04:30:02.907774Z","shell.execute_reply.started":"2024-12-03T04:30:02.900776Z","shell.execute_reply":"2024-12-03T04:30:02.906813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import tensorflow_addons as tfa\n\ndef normalize_image(image):\n    \"\"\"\n    Нормализует изображение с использованием заданных средних значений и стандартных отклонений.\n    \"\"\"\n    mean = tf.constant([0.485, 0.456, 0.406], dtype=tf.float32)\n    std = tf.constant([0.229, 0.224, 0.225], dtype=tf.float32)\n    return (image - mean) / std\n    \ndef decode_image(image_data):\n    \"\"\"Декодирует изображение в vyjujvthye. vfnhbwe (тензор)\n    Нормализует данные и преобразовывает изображения к указанному размеру\"\"\"\n    image = tf.image.decode_jpeg(image_data, channels=3) # Декодирование изображения в формате JPEG в тензор uint8.\n    image = tf.cast(image, tf.float32) / 255.0  # преобразовать изображение в плавающее в диапазоне [0, 1]\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # явный размер, необходимый для TPU\n#     image = tf.keras.applications.inception_resnet_v2.preprocess_input(image)\n    image = normalize_image(image)\n    return image\n\n# аугментации уменьшают утилизацию GPU/TPU поэтому осталось только flip \ndef augment_image(image):\n    \"\"\"Применяет аугментации к изображению.\"\"\"\n    image = tf.image.random_flip_left_right(image)\n    # Случайный поворот\n    # image = tfa.image.rotate(image, tf.random.uniform([], -0.2, 0.2) * 3.1415926)\n    \n    # Случайное смещение\n    # image = tfa.image.translate(image, [tf.random.uniform([], -10, 10), tf.random.uniform([], -10, 10)])\n    \n    # Случайное масштабирование\n    # scale = tf.random.uniform([], 0.8, 1.2)\n    # image = tf.image.resize(image, [int(IMAGE_SIZE[0] * scale), int(IMAGE_SIZE[1] * scale)])\n    # image = tf.image.resize_with_crop_or_pad(image, IMAGE_SIZE[0], IMAGE_SIZE[1])  # Центрируем к оригинальному размеру\n\n    # Случайная яркость, контраст, насыщенность и оттенок\n    # image = tf.image.random_brightness(image, max_delta=0.2)\n    # image = tf.image.random_contrast(image, lower=0.8, upper=1.2)\n    # image = tf.image.random_saturation(image, lower=0.8, upper=1.2)\n    # image = tf.image.random_hue(image, max_delta=0.05)\n\n    # Замедляет обучение в 2 раза т.к. gpu начинает грузиться максимум на 50%\n    # augmenter = tf.keras.Sequential([\n    #     tf.keras.layers.RandomRotation(factor=0.2),  # Случайный поворот до ±20% от угла (0.2 * 360° = 72°)\n    #     tf.keras.layers.RandomTranslation(height_factor=0.1, width_factor=0.1),  # Сдвиг до ±10%\n    #     tf.keras.layers.RandomZoom(height_factor=(-0.2, 0.2), width_factor=(-0.2, 0.2))  # Масштабирование от -20% до +20%\n    # ])\n    # image = augmenter(image)\n    return image\n\ndef read_labeled_tfrecord(example, resnet=False):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string означает байтовую строку\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # [] означает отдельный элемент\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT) # парсим отдельный пример в указанном формате\n    # if resnet:\n    #     image = tf.keras.applications.resnet_v2.preprocess_input(image)\n    # else:\n    image = decode_image(example['image']) # преобразуем изображение к нужному нам формату\n    image = augment_image(image)\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # возвращает набор данных пар (изображение, метка)\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string означает байтовую строку\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # [] означает отдельный элемент\n        # класс отсутствует, задача этого конкурса - предсказать классы цветов для тестового набора данных\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    \"\"\"Читает из TFRecords. Для оптимальной производительности одновременное чтение из нескольких\n    файлов без учета порядка данных. Порядок не имеет значения, поскольку мы все равно будем перетасовывать данные\"\"\"\n\n    ignore_order = tf.data.Options() # Представляет параметры для tf.data.Dataset.\n    if not ordered:\n        ignore_order.experimental_deterministic = False # отключить порядок, увеличить скорость\n\n    dataset = tf.data.TFRecordDataset(filenames) # автоматически чередует чтение из нескольких файлов\n    dataset = dataset.with_options(ignore_order) # использует данные сразу после их поступления, а не в исходном порядке\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)\n    # возвращает набор данных пар (изображение, метка), если метка = Истина, или пар (изображение, идентификатор), если метка = Ложь\n    return dataset\n\ndef get_training_dataset():\n    # dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/train/*.tfrec'), labeled=True)\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-224x224/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # набор обучающих данных должен повторяться в течение нескольких эпох\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ndef get_validation_dataset():\n    # dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-224x224/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache() # кешируем набор\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    # dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-224x224/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:30:02.909665Z","iopub.execute_input":"2024-12-03T04:30:02.910072Z","iopub.status.idle":"2024-12-03T04:30:03.223877Z","shell.execute_reply.started":"2024-12-03T04:30:02.910036Z","shell.execute_reply":"2024-12-03T04:30:03.223067Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Изображения не отображаются на TPU**","metadata":{}},{"cell_type":"code","source":"# import matplotlib.pyplot as plt\n\n# def visualize_samples(dataset, num_samples=9):\n#     \"\"\"\n#     Визуализация случайных семплов из датасета.\n#     \"\"\"\n#     images, labels = next(iter(dataset.unbatch().shuffle(2048).batch(num_samples)))\n    \n#     grid_size = int(num_samples**0.5)\n#     fig, axes = plt.subplots(grid_size, grid_size, figsize=(10, 10))\n    \n#     for i, ax in enumerate(axes.flat):\n#         if i < num_samples:\n#             ax.imshow(images[i])\n#             ax.set_title(f\"Class: {labels[i]}\")\n#             ax.axis('off')\n#         else:\n#             ax.axis('off')\n#     plt.tight_layout()\n#     plt.show()\n\n# visualize_samples(training_dataset, num_samples=16)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:30:03.225078Z","iopub.execute_input":"2024-12-03T04:30:03.225715Z","iopub.status.idle":"2024-12-03T04:30:03.230543Z","shell.execute_reply.started":"2024-12-03T04:30:03.225677Z","shell.execute_reply":"2024-12-03T04:30:03.229622Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Построить модель на TPU (или GPU, или CPU...) с Tensorflow 2.1!","metadata":{}},{"cell_type":"code","source":"def create_InceptionResNetV2_model():\n    pretrained_model = tf.keras.applications.InceptionResNetV2(weights = 'imagenet', include_top = False, pooling='avg', input_shape = [*IMAGE_SIZE, 3])\n    pretrained_model.trainable = True\n    # pretrained_model.trainable = False\n\n    model = tf.keras.Sequential([\n        pretrained_model,\n        # tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation = 'softmax')\n    ])\n\n    return model\n\ndef create_ResNet101_model():\n    pretrained_model = tf.keras.applications.ResNet101(weights = 'imagenet', include_top = False, input_shape = [*IMAGE_SIZE, 3])\n    pretrained_model.trainable = True\n\n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation = 'softmax')\n    ])\n\n    return model\n\ndef create_DenseNet_model():\n    pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', \n                  include_top=False, pooling='avg',\n                  input_shape=(*IMAGE_SIZE, 3))\n    pretrained_model.trainable = True\n#     pretrained_model.trainable = False\n    x = pretrained_model.output\n    predictions = Dense(104, activation='softmax')(x)\n    model = Model(inputs=pretrained_model.input, outputs=predictions)\n\n    return model\n\nimport efficientnet.tfkeras as efficientnet\ndef create_EfficientNet_model():\n    pretrained_model = efficientnet.EfficientNetB7(weights = 'noisy-student', include_top = False, input_shape = [*IMAGE_SIZE, 3])\n    pretrained_model.trainable = True\n\n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation = 'softmax')\n    ])\n\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:30:03.231934Z","iopub.execute_input":"2024-12-03T04:30:03.232543Z","iopub.status.idle":"2024-12-03T04:30:03.923456Z","shell.execute_reply.started":"2024-12-03T04:30:03.232507Z","shell.execute_reply":"2024-12-03T04:30:03.922607Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# функция управляющая изменениями шага обучения в процессе тренировки нейронной сети\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync#0.0001\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .75\n\ndef 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    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\n# построим график изменения шага обучение в зависимости от эпох\nrng = [i for i in range(EPOCHS)]\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:30:03.924500Z","iopub.execute_input":"2024-12-03T04:30:03.924798Z","iopub.status.idle":"2024-12-03T04:30:04.246863Z","shell.execute_reply.started":"2024-12-03T04:30:03.924773Z","shell.execute_reply":"2024-12-03T04:30:04.245955Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n#     initial_learning_rate=1e-3,\n#     decay_steps=1000,\n#     decay_rate=0.96\n# )\n# optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:30:04.249670Z","iopub.execute_input":"2024-12-03T04:30:04.249945Z","iopub.status.idle":"2024-12-03T04:30:04.253272Z","shell.execute_reply.started":"2024-12-03T04:30:04.249922Z","shell.execute_reply":"2024-12-03T04:30:04.252543Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope(): \n    # Нельзя использовать на TPU т.к. \"GPU MaxPool gradient ops do not yet have a deterministic XLA implementation\"\n    # model1 = create_InceptionResNetV2_model()\n    # model = create_DenseNet_model()\n    \n    model1 = create_EfficientNet_model()\n    model2 = create_EfficientNet_model() ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:31:41.021419Z","iopub.execute_input":"2024-12-03T04:31:41.021759Z","iopub.status.idle":"2024-12-03T04:32:59.632964Z","shell.execute_reply.started":"2024-12-03T04:31:41.021733Z","shell.execute_reply":"2024-12-03T04:32:59.631712Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# callbacks_list = [EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True),\n#                   ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3),\n#                   ]\n\nmodel1.compile(\n    optimizer='adam',\n    # optimizer=optimizer,\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\nmodel2.compile(\n    optimizer='nadam',\n    # optimizer=optimizer,\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:32:59.634816Z","iopub.execute_input":"2024-12-03T04:32:59.635098Z","iopub.status.idle":"2024-12-03T04:32:59.922514Z","shell.execute_reply.started":"2024-12-03T04:32:59.635074Z","shell.execute_reply":"2024-12-03T04:32:59.921387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history1 = model1.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          callbacks=[lr_callback, ModelCheckpoint(filepath='my_IncRes_net.h5', monitor='val_loss',\n                                  save_best_only=True)],\n          validation_data=validation_dataset,\n          workers = 3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T04:32:59.923731Z","iopub.execute_input":"2024-12-03T04:32:59.923997Z","iopub.status.idle":"2024-12-03T05:26:13.918753Z","shell.execute_reply.started":"2024-12-03T04:32:59.923974Z","shell.execute_reply":"2024-12-03T05:26:13.917630Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history1.history['sparse_categorical_accuracy'], \n         label='Оценка точности на обучающем наборе')\nplt.plot(history1.history['val_sparse_categorical_accuracy'], \n         label='Оценка точности на проверочном наборе')\nplt.xlabel('Эпоха обучения')\nplt.ylabel('Оценка точности')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T05:26:13.922515Z","iopub.execute_input":"2024-12-03T05:26:13.922854Z","iopub.status.idle":"2024-12-03T05:26:14.110835Z","shell.execute_reply.started":"2024-12-03T05:26:13.922826Z","shell.execute_reply":"2024-12-03T05:26:14.110026Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history1.history['loss'], \n         label='Оценка потерь на обучающем наборе')\nplt.plot(history1.history['val_loss'], \n         label='Оценка потерь на проверочном наборе')\nplt.xlabel('Эпоха обучения') \nplt.ylabel('Оценка потерь')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T05:26:14.111891Z","iopub.execute_input":"2024-12-03T05:26:14.112162Z","iopub.status.idle":"2024-12-03T05:26:14.299721Z","shell.execute_reply.started":"2024-12-03T05:26:14.112138Z","shell.execute_reply":"2024-12-03T05:26:14.298885Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history2 = model2.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          callbacks=[lr_callback, ModelCheckpoint(filepath='my_Eff_net.h5', monitor='val_loss',\n                                  save_best_only=True)],\n          validation_data=validation_dataset,\n          workers = 3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T05:26:14.300664Z","iopub.execute_input":"2024-12-03T05:26:14.300900Z","iopub.status.idle":"2024-12-03T06:19:48.208726Z","shell.execute_reply.started":"2024-12-03T05:26:14.300879Z","shell.execute_reply":"2024-12-03T06:19:48.207425Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history2.history['sparse_categorical_accuracy'], \n         label='Оценка точности на обучающем наборе')\nplt.plot(history2.history['val_sparse_categorical_accuracy'], \n         label='Оценка точности на проверочном наборе')\nplt.xlabel('Эпоха обучения')\nplt.ylabel('Оценка точности')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T06:19:48.210926Z","iopub.execute_input":"2024-12-03T06:19:48.211224Z","iopub.status.idle":"2024-12-03T06:19:48.410061Z","shell.execute_reply.started":"2024-12-03T06:19:48.211199Z","shell.execute_reply":"2024-12-03T06:19:48.409111Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history2.history['loss'], \n         label='Оценка потерь на обучающем наборе')\nplt.plot(history2.history['val_loss'], \n         label='Оценка потерь на проверочном наборе')\nplt.xlabel('Эпоха обучения')\nplt.ylabel('Оценка потерь')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T06:19:48.411116Z","iopub.execute_input":"2024-12-03T06:19:48.411365Z","iopub.status.idle":"2024-12-03T06:19:48.610362Z","shell.execute_reply.started":"2024-12-03T06:19:48.411343Z","shell.execute_reply":"2024-12-03T06:19:48.609449Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model1 = tf.keras.models.load_model('my_IncRes_net.h5')\nmodel2 = tf.keras.models.load_model('my_Eff_net.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T06:19:48.611514Z","iopub.execute_input":"2024-12-03T06:19:48.611833Z","iopub.status.idle":"2024-12-03T06:20:11.438459Z","shell.execute_reply.started":"2024-12-03T06:19:48.611808Z","shell.execute_reply":"2024-12-03T06:20:11.437075Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install scikit-learn","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T06:20:11.441879Z","iopub.execute_input":"2024-12-03T06:20:11.442138Z","iopub.status.idle":"2024-12-03T06:20:21.274104Z","shell.execute_reply.started":"2024-12-03T06:20:11.442116Z","shell.execute_reply":"2024-12-03T06:20:21.272776Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import re\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/test/*.tfrec')\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\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint('Dataset: {} validation images, {} unlabeled test images'.format(NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-03T06:20:21.275680Z","iopub.execute_input":"2024-12-03T06:20:21.275993Z","iopub.status.idle":"2024-12-03T06:20:21.332480Z","shell.execute_reply.started":"2024-12-03T06:20:21.275964Z","shell.execute_reply":"2024-12-03T06:20:21.331567Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import f1_score\nfrom tqdm import tqdm\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\nm1 = model1.predict(images_ds)\nm2 = model2.predict(images_ds)\nscores = []\nfor alpha in tqdm(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":"2024-12-03T06:20:21.333665Z","iopub.execute_input":"2024-12-03T06:20:21.333926Z","iopub.status.idle":"2024-12-03T07:13:13.868574Z","shell.execute_reply.started":"2024-12-03T06:20:21.333903Z","shell.execute_reply":"2024-12-03T07:13:13.867597Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Вычислите свои прогнозы на тестовом наборе!\n\nCоздадим файл, который можно будет отправить на конкурс.","metadata":{}},{"cell_type":"code","source":"# Поскольку мы разделяем набор данных и выполняем итерацию отдельно для изображений и идентификаторов, порядок имеет значение.\ntest_ds = get_test_dataset(ordered=True) \n\nprint('Вычисляем предсказания...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\n\nprobabilities1 = model1.predict(test_images_ds)\nprobabilities2 = model2.predict(test_images_ds)\nprobabilities = best_alpha * probabilities1 + (1 - best_alpha) * probabilities2\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\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') # все в одной партии\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}