{"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"},{"sourceId":1005170,"sourceType":"datasetVersion","datasetId":550538},{"sourceId":1138814,"sourceType":"datasetVersion","datasetId":601927}],"dockerImageVersionId":30448,"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-11T16:32:34.961554Z","iopub.execute_input":"2024-12-11T16:32:34.961870Z","iopub.status.idle":"2024-12-11T16:32:42.446970Z","shell.execute_reply.started":"2024-12-11T16:32:34.961848Z","shell.execute_reply":"2024-12-11T16:32:42.446081Z"}},"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-11T16:32:43.633506Z","iopub.execute_input":"2024-12-11T16:32:43.633969Z","iopub.status.idle":"2024-12-11T16:33:23.336448Z","shell.execute_reply.started":"2024-12-11T16:32:43.633924Z","shell.execute_reply":"2024-12-11T16:33:23.335648Z"}},"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-11T16:33:39.931395Z","iopub.execute_input":"2024-12-11T16:33:39.932152Z","iopub.status.idle":"2024-12-11T16:33:48.649526Z","shell.execute_reply.started":"2024-12-11T16:33:39.932119Z","shell.execute_reply":"2024-12-11T16:33:48.648663Z"}},"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\"\nMORE_IMAGES_GCS_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T16:34:26.875996Z","iopub.execute_input":"2024-12-11T16:34:26.876883Z","iopub.status.idle":"2024-12-11T16:34:26.881202Z","shell.execute_reply.started":"2024-12-11T16:34:26.876849Z","shell.execute_reply":"2024-12-11T16:34:26.880397Z"}},"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 = 20\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 # находим количество шагов за эпоху\n\nGCS_PATH_SELECT = {\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}\n\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\nTRAINING_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\n\n#############################\nMOREIMAGES_PATH_SELECT = {\n    192: '/tfrecords-jpeg-192x192',\n    224: '/tfrecords-jpeg-224x224',\n    331: '/tfrecords-jpeg-331x331',\n    512: '/tfrecords-jpeg-512x512'\n}\nMOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]\n\nIMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')\nINATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')\nOPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')\nOXFORD_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/oxford_102' + MOREIMAGES_PATH + '/*.tfrec')\nTENSORFLOW_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/tf_flowers' + MOREIMAGES_PATH + '/*.tfrec')\n\nADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES \n\nTRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES + VALIDATION_FILENAMES ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T16:48:03.312659Z","iopub.execute_input":"2024-12-11T16:48:03.312951Z","iopub.status.idle":"2024-12-11T16:48:03.380358Z","shell.execute_reply.started":"2024-12-11T16:48:03.312926Z","shell.execute_reply":"2024-12-11T16:48:03.379081Z"}},"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-02T10:47:02.80472Z","iopub.execute_input":"2024-12-02T10:47:02.804971Z","iopub.status.idle":"2024-12-02T10:47:02.813884Z","shell.execute_reply.started":"2024-12-02T10:47:02.804951Z","shell.execute_reply":"2024-12-02T10:47:02.813109Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import tensorflow_addons as tfa\nimport re\nAUTO = tf.data.experimental.AUTOTUNE\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, label):\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, label\n\ndef read_labeled_tfrecord(example):\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    image = decode_image(example['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    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)\n    dataset = dataset.with_options(ignore_order)\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTO)\n    return dataset\n#\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled = True)\n    dataset = dataset.map(augment_image, num_parallel_calls=AUTO)\n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n#\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)\n    return dataset\n#\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)\n    return dataset\n#\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n#\n\nNUM_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\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T16:45:38.325416Z","iopub.execute_input":"2024-12-11T16:45:38.326142Z","iopub.status.idle":"2024-12-11T16:45:38.532534Z","shell.execute_reply.started":"2024-12-11T16:45:38.326097Z","shell.execute_reply":"2024-12-11T16:45:38.531508Z"}},"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-11T16:45:47.038149Z","iopub.execute_input":"2024-12-11T16:45:47.038487Z","iopub.status.idle":"2024-12-11T16:45:47.042704Z","shell.execute_reply.started":"2024-12-11T16:45:47.038461Z","shell.execute_reply":"2024-12-11T16:45:47.041902Z"}},"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, 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', 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\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-11T16:46:55.026166Z","iopub.execute_input":"2024-12-11T16:46:55.026998Z","iopub.status.idle":"2024-12-11T16:46:55.887193Z","shell.execute_reply.started":"2024-12-11T16:46:55.026966Z","shell.execute_reply":"2024-12-11T16:46:55.886324Z"}},"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-11T16:46:56.506047Z","iopub.execute_input":"2024-12-11T16:46:56.506978Z","iopub.status.idle":"2024-12-11T16:46:56.804136Z","shell.execute_reply.started":"2024-12-11T16:46:56.506928Z","shell.execute_reply":"2024-12-11T16:46:56.803393Z"}},"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-11T16:47:00.384620Z","iopub.execute_input":"2024-12-11T16:47:00.384947Z","iopub.status.idle":"2024-12-11T16:47:00.388462Z","shell.execute_reply.started":"2024-12-11T16:47:00.384921Z","shell.execute_reply":"2024-12-11T16:47:00.387664Z"}},"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    # model = create_InceptionResNetV2_model() # тут подставить свою модель\n    # model = create_DenseNet_model() \n    model = create_EfficientNet_model() ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T16:47:00.649289Z","iopub.execute_input":"2024-12-11T16:47:00.649645Z","iopub.status.idle":"2024-12-11T16:48:03.310697Z","shell.execute_reply.started":"2024-12-11T16:47:00.649619Z","shell.execute_reply":"2024-12-11T16:48:03.309040Z"}},"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\nmodel.compile(\n    optimizer='adam',\n    # optimizer=optimizer,\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T16:48:07.036311Z","iopub.execute_input":"2024-12-11T16:48:07.036728Z","iopub.status.idle":"2024-12-11T16:48:07.250429Z","shell.execute_reply.started":"2024-12-11T16:48:07.036699Z","shell.execute_reply":"2024-12-11T16:48:07.249095Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          callbacks=[lr_callback, ModelCheckpoint(filepath='my_EfficientNetB7.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-11T16:48:39.409926Z","iopub.execute_input":"2024-12-11T16:48:39.411105Z","iopub.status.idle":"2024-12-11T17:41:34.354547Z","shell.execute_reply.started":"2024-12-11T16:48:39.411056Z","shell.execute_reply":"2024-12-11T17:41:34.353362Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['sparse_categorical_accuracy'], \n         label='Оценка точности на обучающем наборе')\nplt.plot(history.history['val_sparse_categorical_accuracy'], \n         label='Оценка точности на проверочном наборе')\nplt.xlabel('Эпоха обучения')\nplt.ylabel('Оценка точности')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:41:34.357140Z","iopub.execute_input":"2024-12-11T17:41:34.357512Z","iopub.status.idle":"2024-12-11T17:41:34.546383Z","shell.execute_reply.started":"2024-12-11T17:41:34.357488Z","shell.execute_reply":"2024-12-11T17:41:34.545388Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['loss'], \n         label='Оценка потерь на обучающем наборе')\nplt.plot(history.history['val_loss'], \n         label='Оценка потерь на проверочном наборе')\nplt.xlabel('Эпоха обучения')\nplt.ylabel('Оценка потерь')\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:41:34.547425Z","iopub.execute_input":"2024-12-11T17:41:34.547660Z","iopub.status.idle":"2024-12-11T17:41:34.721641Z","shell.execute_reply.started":"2024-12-11T17:41:34.547640Z","shell.execute_reply":"2024-12-11T17:41:34.720635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = tf.keras.models.load_model('my_EfficientNetB7.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:41:34.723431Z","iopub.execute_input":"2024-12-11T17:41:34.723719Z","iopub.status.idle":"2024-12-11T17:41:46.046669Z","shell.execute_reply.started":"2024-12-11T17:41:34.723684Z","shell.execute_reply":"2024-12-11T17:41:46.045561Z"}},"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)\nprobabilities = model.predict(test_images_ds)\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,"execution":{"iopub.status.busy":"2024-12-11T17:41:46.049185Z","iopub.execute_input":"2024-12-11T17:41:46.049457Z","iopub.status.idle":"2024-12-11T18:34:34.630694Z","shell.execute_reply.started":"2024-12-11T17:41:46.049435Z","shell.execute_reply":"2024-12-11T18:34:34.629388Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}