{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-12-20T09:23:05.880761Z","iopub.execute_input":"2022-12-20T09:23:05.881224Z","iopub.status.idle":"2022-12-20T09:23:06.082907Z","shell.execute_reply.started":"2022-12-20T09:23:05.881119Z","shell.execute_reply":"2022-12-20T09:23:06.081809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -q efficientnet","metadata":{"execution":{"iopub.status.busy":"2022-12-20T09:24:28.297629Z","iopub.execute_input":"2022-12-20T09:24:28.297968Z","iopub.status.idle":"2022-12-20T09:24:39.433022Z","shell.execute_reply.started":"2022-12-20T09:24:28.297935Z","shell.execute_reply":"2022-12-20T09:24:39.431533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.applications.vgg19 import VGG19\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras.applications.inception_resnet_v2 import InceptionResNetV2\nfrom tensorflow.keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201 \nfrom tensorflow.keras.applications.xception import Xception\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.applications.resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2\nfrom tensorflow.keras.applications.nasnet import NASNetLarge\nfrom efficientnet.tfkeras import EfficientNetB7, EfficientNetL2, EfficientNetB0, EfficientNetB1","metadata":{"execution":{"iopub.status.busy":"2022-12-20T09:24:50.862712Z","iopub.execute_input":"2022-12-20T09:24:50.863050Z","iopub.status.idle":"2022-12-20T09:24:59.211441Z","shell.execute_reply.started":"2022-12-20T09:24:50.863015Z","shell.execute_reply":"2022-12-20T09:24:59.210473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Dense, Flatten\nfrom tensorflow.keras.layers import Dropout, BatchNormalization, GaussianDropout\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n#  библиотека для работы с наборами данных на Kaggle\nfrom kaggle_datasets import KaggleDatasets\nimport re\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport math\nimport tensorflow.keras.backend as K\n%matplotlib inline \nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2022-12-20T09:25:16.966675Z","iopub.execute_input":"2022-12-20T09:25:16.969335Z","iopub.status.idle":"2022-12-20T09:25:16.984593Z","shell.execute_reply.started":"2022-12-20T09:25:16.969282Z","shell.execute_reply":"2022-12-20T09:25:16.983518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2022-12-20T09:25:55.213604Z","iopub.execute_input":"2022-12-20T09:25:55.214609Z","iopub.status.idle":"2022-12-20T09:26:01.733020Z","shell.execute_reply.started":"2022-12-20T09:25:55.214530Z","shell.execute_reply":"2022-12-20T09:26:01.732414Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() #получаем путь к наборам данных","metadata":{"execution":{"iopub.status.busy":"2022-12-20T09:26:05.126929Z","iopub.execute_input":"2022-12-20T09:26:05.127284Z","iopub.status.idle":"2022-12-20T09:26:05.505747Z","shell.execute_reply.started":"2022-12-20T09:26:05.127249Z","shell.execute_reply":"2022-12-20T09:26:05.504685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512] # при таком размере графическому процессору не хватит памяти. Используйте TPU\nEPOCHS = 30\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nGCS_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\nSEED = 2020","metadata":{"execution":{"iopub.status.busy":"2022-12-20T09:26:09.486843Z","iopub.execute_input":"2022-12-20T09:26:09.487768Z","iopub.status.idle":"2022-12-20T09:26:09.729326Z","shell.execute_reply.started":"2022-12-20T09:26:09.487726Z","shell.execute_reply":"2022-12-20T09:26:09.728456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n    rotation = math.pi * rotation / 180.\n    shear = math.pi * shear / 180.\n    \n    c1 = tf.math.cos(rotation)\n    s1 = tf.math.sin(rotation)\n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    rotation_matrix = tf.reshape( tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3] )\n        \n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape( tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3] )    \n    \n    zoom_matrix = tf.reshape( tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3] )\n    shift_matrix = tf.reshape( tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3] )\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))\n\ndef transform(image, label, DIM = IMAGE_SIZE[0]):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly rotated, sheared, zoomed, and shifted\n\n    XDIM = DIM % 2\n    \n    rot = 15. * tf.random.normal([1],dtype='float32')\n    shr = 5. * tf.random.normal([1],dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    h_shift = 16. * tf.random.normal([1],dtype='float32') \n    w_shift = 16. * tf.random.normal([1],dtype='float32') \n  \n    # GET TRANSFORMATION MATRIX\n    m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) \n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat( tf.range(DIM//2,-DIM//2,-1), DIM )\n    y = tf.tile( tf.range(-DIM//2,DIM//2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(m,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)\n    \n    # FIND ORIGIN PIXEL VALUES           \n    idx3 = tf.stack( [DIM//2-idx2[0,], DIM//2-1+idx2[1,]] )\n    d = tf.gather_nd(image,tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM,DIM,3]),label\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(transform, 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":"2022-12-20T09:26:12.879737Z","iopub.execute_input":"2022-12-20T09:26:12.880396Z","iopub.status.idle":"2022-12-20T09:26:12.916064Z","shell.execute_reply.started":"2022-12-20T09:26:12.880347Z","shell.execute_reply":"2022-12-20T09:26:12.915201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# tune\n# функция управляющая изменениями шага обучения в процессе тренировки нейронной сети\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync#0.0001\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 7\nLR_SUSTAIN_EPOCHS = 3\nLR_EXP_DECAY = 0.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":"2022-12-20T09:26:17.660449Z","iopub.execute_input":"2022-12-20T09:26:17.661098Z","iopub.status.idle":"2022-12-20T09:26:17.990432Z","shell.execute_reply.started":"2022-12-20T09:26:17.661044Z","shell.execute_reply":"2022-12-20T09:26:17.987247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model(use_model):\n    # tune\n    # noisy-student\n    base_model = use_model(weights='noisy-student', \n                      include_top=False, pooling='avg',\n                      input_shape=(*IMAGE_SIZE, 3))\n#     base_model.trainable = False\n    x = base_model.output\n    # tune\n    predictions = Dense(104, activation='softmax', name=\"dense_104\")(x)\n    return Model(inputs=base_model.input, outputs=predictions)\n\n\nwith strategy.scope():    \n    model = get_model(EfficientNetB7) # тут подставить свою модель\n        \nmodel.compile(\n    optimizer='nadam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n# Визуализируем архитектуру модели\n# tf.keras.utils.plot_model(\n#     model, to_file='model.png', show_shapes=True, show_layer_names=True,\n# )","metadata":{"execution":{"iopub.status.busy":"2022-12-20T09:26:21.025599Z","iopub.execute_input":"2022-12-20T09:26:21.026581Z","iopub.status.idle":"2022-12-20T09:27:03.379011Z","shell.execute_reply.started":"2022-12-20T09:26:21.026538Z","shell.execute_reply":"2022-12-20T09:27:03.377842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(get_training_dataset(), \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          callbacks=[lr_callback, ModelCheckpoint(filepath='my_ef_net_b7.h5', monitor='val_loss',\n                                  save_best_only=True)],\n          validation_data=get_validation_dataset(),\n          workers = 3)","metadata":{"execution":{"iopub.status.busy":"2022-12-20T09:27:20.113117Z","iopub.execute_input":"2022-12-20T09:27:20.113411Z","iopub.status.idle":"2022-12-20T10:24:48.762016Z","shell.execute_reply.started":"2022-12-20T09:27:20.113376Z","shell.execute_reply":"2022-12-20T10:24:48.760383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2022-12-20T10:25:31.007295Z","iopub.execute_input":"2022-12-20T10:25:31.007647Z","iopub.status.idle":"2022-12-20T10:25:31.290458Z","shell.execute_reply.started":"2022-12-20T10:25:31.007608Z","shell.execute_reply":"2022-12-20T10:25:31.289597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2022-12-20T10:25:33.993421Z","iopub.execute_input":"2022-12-20T10:25:33.994345Z","iopub.status.idle":"2022-12-20T10:25:34.270528Z","shell.execute_reply.started":"2022-12-20T10:25:33.994288Z","shell.execute_reply":"2022-12-20T10:25:34.269293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def evaluate(m, h, ds):\n    scores = m.evaluate(ds, verbose=1)\n    print(\"Доля правильных ответов на тестовых данных, в процентах:\", round(scores[1] * 100, 4))\n\n    plt.plot(h.history['sparse_categorical_accuracy'], \n             label='Доля правильных ответов на обучающем наборе')\n    plt.plot(h.history['val_sparse_categorical_accuracy'], \n             label='Доля правильных ответов на проверочном наборе')\n    plt.xlabel('Эпоха обучения')\n    plt.ylabel('Доля правильных ответов')\n    plt.legend()\n    plt.show()\n\n    plt.plot(h.history['loss'], \n             label='Оценка потерь на обучающем наборе')\n    plt.plot(h.history['val_loss'], \n             label='Оценка потерь на проверочном наборе')\n    plt.xlabel('Эпоха обучения')\n    plt.ylabel('Оценка потерь')\n    plt.legend()","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:25:36.396616Z","iopub.execute_input":"2022-12-20T10:25:36.396961Z","iopub.status.idle":"2022-12-20T10:25:36.406036Z","shell.execute_reply.started":"2022-12-20T10:25:36.396924Z","shell.execute_reply":"2022-12-20T10:25:36.404318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"evaluate(model, history, get_validation_dataset())","metadata":{"execution":{"iopub.status.busy":"2022-12-20T10:25:39.316038Z","iopub.execute_input":"2022-12-20T10:25:39.316385Z","iopub.status.idle":"2022-12-20T10:25:47.435731Z","shell.execute_reply.started":"2022-12-20T10:25:39.316348Z","shell.execute_reply":"2022-12-20T10:25:47.434742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2022-12-20T10:26:12.759805Z","iopub.execute_input":"2022-12-20T10:26:12.760556Z","iopub.status.idle":"2022-12-20T10:26:56.917736Z","shell.execute_reply.started":"2022-12-20T10:26:12.760504Z","shell.execute_reply":"2022-12-20T10:26:56.916358Z"},"trusted":true},"execution_count":null,"outputs":[]}]}