{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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":32023,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":22114}],"dockerImageVersionId":30673,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# TF 2.15 блокнот","metadata":{}},{"cell_type":"code","source":"# !pip install -q efficientnet","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:10:27.430590Z","iopub.execute_input":"2024-04-16T16:10:27.431313Z","iopub.status.idle":"2024-04-16T16:10:27.436191Z","shell.execute_reply.started":"2024-04-16T16:10:27.431274Z","shell.execute_reply":"2024-04-16T16:10:27.435308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport tensorflow_hub as hub\n# предобученные модели\nfrom tensorflow.keras.applications import DenseNet201 \n# from efficientnet.tfkeras import EfficientNetB7\n# from tensorflow.keras.applications import Xception \nfrom tensorflow.keras.saving import load_model\n# последовательная модель (стек слоев)\nfrom tensorflow.keras.models import Sequential, Model, load_model\n# полносвязный слой и слой выпрямляющий матрицу в вектор\nfrom tensorflow.keras.layers import Dense, Flatten, Input, Activation, Concatenate, GlobalAveragePooling2D, Layer\n# слой выключения нейронов и слой нормализации выходных данных (нормализует данные в пределах текущей выборки)\nfrom tensorflow.keras.layers import Dropout, BatchNormalization, SpatialDropout2D, GaussianDropout\n# слои свертки и подвыборки\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D\n# работа с обратной связью от обучающейся нейронной сети\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, LearningRateScheduler\n# вспомогательные инструменты\nfrom tensorflow.keras import utils\nfrom tensorflow.keras.regularizers import *\nfrom sklearn.metrics import f1_score\nimport numpy as np\nimport pandas as pd\nimport os\nimport shutil\nimport re\nimport random\n\n#  библиотека для работы с наборами данных на Kaggle\nfrom kaggle_datasets import KaggleDatasets\nimport matplotlib.pyplot as plt\n%matplotlib inline \nprint(\"Tensorflow version \" + tf.__version__)\n\n# import warnings\n# # Disable all warnings\n# warnings.filterwarnings(\"ignore\")\n\n# tf.get_logger().setLevel(\"ERROR\")","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2024-04-16T16:10:27.437987Z","iopub.execute_input":"2024-04-16T16:10:27.438277Z","iopub.status.idle":"2024-04-16T16:10:32.144105Z","shell.execute_reply.started":"2024-04-16T16:10:27.438234Z","shell.execute_reply":"2024-04-16T16:10:32.143128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Определяем, какой ускоритель можем использовать","metadata":{}},{"cell_type":"code","source":"AUTO = tf.data.AUTOTUNE\n\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.TPUStrategy(tpu)\nelse:\n    #strategy = tf.distribute.get_strategy() # стратегия распространения по умолчанию в Tensorflow. Работает на CPU и одном GPU.\n    strategy = tf.distribute.MirroredStrategy() # for GPU or multi-GPU machines\n    \nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:10:32.145480Z","iopub.execute_input":"2024-04-16T16:10:32.146023Z","iopub.status.idle":"2024-04-16T16:10:32.600911Z","shell.execute_reply.started":"2024-04-16T16:10:32.145996Z","shell.execute_reply":"2024-04-16T16:10:32.599946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = '/kaggle/input/tpu-getting-started'","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:10:32.602603Z","iopub.execute_input":"2024-04-16T16:10:32.602900Z","iopub.status.idle":"2024-04-16T16:10:32.620271Z","shell.execute_reply.started":"2024-04-16T16:10:32.602875Z","shell.execute_reply":"2024-04-16T16:10:32.619435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Устанавливаем параметры","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224]\nEPOCHS = 50\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\n\nSEED = 2024 \nnp.random.seed(SEED)\nrandom.seed(SEED)\nos.environ['PYTHONHASHSEED'] = str(SEED)\ntf.random.set_seed(SEED)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:10:32.622810Z","iopub.execute_input":"2024-04-16T16:10:32.623137Z","iopub.status.idle":"2024-04-16T16:10:32.631410Z","shell.execute_reply.started":"2024-04-16T16:10:32.623111Z","shell.execute_reply":"2024-04-16T16:10:32.630593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\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","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:10:32.632489Z","iopub.execute_input":"2024-04-16T16:10:32.632766Z","iopub.status.idle":"2024-04-16T16:10:32.688304Z","shell.execute_reply.started":"2024-04-16T16:10:32.632733Z","shell.execute_reply":"2024-04-16T16:10:32.687240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Загружаем данные\n\nЭти данные загружаются из Kaggle и автоматически сегментируются для максимального распараллеливания.","metadata":{}},{"cell_type":"code","source":"def 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    return image\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    \"\"\"Читает из 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, 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    # возвращает набор данных пар (изображение, метка), если метка = Истина, или пар (изображение, идентификатор), если метка = Ложь\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    flag = random.randint(1,3)\n    coef_1 = random.randint(70, 90) * 0.01\n    coef_2 = random.randint(70, 90) * 0.01\n    if flag == 1:\n        image = tf.image.random_flip_left_right(image, seed=SEED)\n    elif flag == 2:\n        image = tf.image.random_flip_up_down(image, seed=SEED)\n    else:\n        image = tf.image.random_crop(image, [int(IMAGE_SIZE[0]*coef_1), int(IMAGE_SIZE[0]*coef_2), 3],seed=SEED)\n    return image, label   \n\ndef 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() # набор обучающих данных должен повторяться в течение нескольких эпох\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) #готовим следующий набор, пока предыдущий обучается\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache() # кешируем набор\n    dataset = dataset.prefetch(AUTO) #готовим следующий набор, пока предыдущий обучается\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) #готовим следующий набор, пока предыдущий обучается\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# training_dataset = get_training_dataset()\n# validation_dataset = get_validation_dataset()\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))","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:10:32.689897Z","iopub.execute_input":"2024-04-16T16:10:32.690510Z","iopub.status.idle":"2024-04-16T16:10:32.714698Z","shell.execute_reply.started":"2024-04-16T16:10:32.690475Z","shell.execute_reply":"2024-04-16T16:10:32.713753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Построение и обучение моделей","metadata":{}},{"cell_type":"code","source":"# функция управляющая изменениями шага обучения в процессе тренировки нейронной сети\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8\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":{"execution":{"iopub.status.busy":"2024-04-16T16:10:32.715949Z","iopub.execute_input":"2024-04-16T16:10:32.716316Z","iopub.status.idle":"2024-04-16T16:10:33.003882Z","shell.execute_reply.started":"2024-04-16T16:10:32.716281Z","shell.execute_reply":"2024-04-16T16:10:33.002836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model(use_model, weights):\n    base_model = use_model(\n        weights=weights, \n        include_top=False, pooling='avg',\n        #input_shape=(*IMAGE_SIZE, 3)\n    )\n    base_model.trainable = True\n    \n    model = tf.keras.Sequential([\n            Input((*IMAGE_SIZE, 3)),\n            base_model,\n            Dense(104, activation='softmax')\n        ])\n    \n    return model\n    \n    \ndef train_model(model, model_name='model'):    \n    \n    model.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n        \n    history = model.fit(\n    get_training_dataset(), \n    steps_per_epoch=STEPS_PER_EPOCH, \n    epochs=EPOCHS,\n    validation_data=get_validation_dataset(),\n    callbacks=[\n        lr_callback,\n        ModelCheckpoint(filepath=f'/kaggle/working/{model_name}.weights.h5', monitor='val_loss', save_best_only=True, save_weights_only=True),\n        EarlyStopping(monitor='val_loss', patience=7),\n        #ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, min_lr=1e-6),\n        ],\n    verbose=2\n    )\n\n    best_val_accuracy = max(history.history['val_sparse_categorical_accuracy'])\n    print(\"Best Validation Sparse Categorical Accuracy:\", best_val_accuracy)\n\n    plt.plot(history.history['sparse_categorical_accuracy'], label='accuracy train')\n    plt.plot(history.history['val_sparse_categorical_accuracy'], label='accuracy valid')\n    plt.xlabel('эпоха обучения')\n    plt.ylabel('accuracy')\n    plt.legend()\n    plt.show()\n    \n    #model.load_weights(f'kaggle/working/{model_name}.weights.h5')\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:15:58.095705Z","iopub.execute_input":"2024-04-16T16:15:58.096071Z","iopub.status.idle":"2024-04-16T16:15:58.107149Z","shell.execute_reply.started":"2024-04-16T16:15:58.096044Z","shell.execute_reply":"2024-04-16T16:15:58.106161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# with strategy.scope():\n#     xception = get_model(Xception, 'imagenet')\n#     #xception = load_model('/kaggle/working/xception.keras')\n    \n#     xception = train_model(xception, 'xception')\n    ","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:10:33.016530Z","iopub.execute_input":"2024-04-16T16:10:33.017134Z","iopub.status.idle":"2024-04-16T16:10:33.031727Z","shell.execute_reply.started":"2024-04-16T16:10:33.017101Z","shell.execute_reply":"2024-04-16T16:10:33.030585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    densenet = get_model(DenseNet201, 'imagenet')\n    #densenet = load_model('/kaggle/working/densenet.keras')\n    \n    densenet = train_model(densenet, 'densenet')\n","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:16:00.141355Z","iopub.execute_input":"2024-04-16T16:16:00.141743Z","iopub.status.idle":"2024-04-16T16:27:09.840216Z","shell.execute_reply.started":"2024-04-16T16:16:00.141713Z","shell.execute_reply":"2024-04-16T16:27:09.839126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# with strategy.scope():\n#     effnet = get_model(EfficientNetB7, 'imagenet')\n    \n#     effnet = train_model(effnet, 'effnet')","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:10:37.848298Z","iopub.execute_input":"2024-04-16T16:10:37.848690Z","iopub.status.idle":"2024-04-16T16:10:37.855204Z","shell.execute_reply.started":"2024-04-16T16:10:37.848654Z","shell.execute_reply":"2024-04-16T16:10:37.854245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Оценка моделей","metadata":{}},{"cell_type":"code","source":"model = get_model(DenseNet201, 'imagenet')\nmodel.load_weights('/kaggle/working/densenet.weights.h5')\nmodel.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:36:48.513283Z","iopub.execute_input":"2024-04-16T16:36:48.513986Z","iopub.status.idle":"2024-04-16T16:36:55.645682Z","shell.execute_reply.started":"2024-04-16T16:36:48.513954Z","shell.execute_reply":"2024-04-16T16:36:55.644619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eval_dataset = get_validation_dataset()\n\n\nmodel.evaluate(eval_dataset)","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:31:11.082174Z","iopub.execute_input":"2024-04-16T16:31:11.082899Z","iopub.status.idle":"2024-04-16T16:31:58.130984Z","shell.execute_reply.started":"2024-04-16T16:31:11.082866Z","shell.execute_reply":"2024-04-16T16:31:58.130005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# models = [xception, densenet]","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:11:19.550506Z","iopub.status.idle":"2024-04-16T16:11:19.550822Z","shell.execute_reply.started":"2024-04-16T16:11:19.550666Z","shell.execute_reply":"2024-04-16T16:11:19.550679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# def find_best_alpha(valid_dataset, model_lst):\n#     images_ds = valid_dataset.map(lambda image, label: image)\n#     labels_ds = valid_dataset.map(lambda image, label: label).unbatch()\n#     y_true = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() # get everything as one batch\n#     p = []\n#     for model in model_lst:\n#         p.append(model.predict(images_ds))\n\n#     scores = []\n#     for alpha in np.linspace(0,1,100):\n#         preds = np.argmax(alpha*p[0]+(1-alpha)*p[1], axis=-1)\n#         scores.append(f1_score(y_true, preds, labels=range(len(CLASSES)), average='macro'))\n\n#     best_alpha = np.argmax(scores)/100\n#     return best_alpha","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:11:19.552631Z","iopub.status.idle":"2024-04-16T16:11:19.552961Z","shell.execute_reply.started":"2024-04-16T16:11:19.552798Z","shell.execute_reply":"2024-04-16T16:11:19.552811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# valid_ds = get_validation_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and labels, order matters.\n# alpha = find_best_alpha(valid_ds, models)\n# print(f'Best alpha is {alpha}')","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:11:19.554449Z","iopub.status.idle":"2024-04-16T16:11:19.554799Z","shell.execute_reply.started":"2024-04-16T16:11:19.554629Z","shell.execute_reply":"2024-04-16T16:11:19.554643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Вычислите свои прогнозы на тестовом наборе!\n\nCоздадим файл, который можно будет отправить на конкурс.","metadata":{}},{"cell_type":"code","source":"# def predict_ensemble(dataset, model_lst, alpha):\n#     print('Calculating predictions...')\n#     images_ds = dataset.map(lambda image, idnum: image)\n#     probs = []\n#     for model in model_lst:\n#         p = model.predict(images_ds,verbose=0)\n#         probs.append(p)\n#     preds = np.argmax(alpha*probs[0] + (1-alpha)*probs[1], axis=-1)\n#     return preds","metadata":{"execution":{"iopub.status.busy":"2024-04-16T16:11:19.556172Z","iopub.status.idle":"2024-04-16T16:11:19.556529Z","shell.execute_reply.started":"2024-04-16T16:11:19.556364Z","shell.execute_reply":"2024-04-16T16:11:19.556378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_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":{"execution":{"iopub.status.busy":"2024-04-16T16:34:17.261950Z","iopub.execute_input":"2024-04-16T16:34:17.262909Z","iopub.status.idle":"2024-04-16T16:35:26.164664Z","shell.execute_reply.started":"2024-04-16T16:34:17.262874Z","shell.execute_reply":"2024-04-16T16:35:26.163626Z"},"trusted":true},"execution_count":null,"outputs":[]}]}