{"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":"tpu1vmV38","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"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":{"execution":{"iopub.status.busy":"2023-12-18T12:58:29.738509Z","iopub.execute_input":"2023-12-18T12:58:29.738778Z","iopub.status.idle":"2023-12-18T12:58:36.960335Z","shell.execute_reply.started":"2023-12-18T12:58:29.738750Z","shell.execute_reply":"2023-12-18T12:58:36.959258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#предварительно обученные модели\nfrom 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":"2023-12-18T12:58:19.399153Z","iopub.execute_input":"2023-12-18T12:58:19.399808Z","iopub.status.idle":"2023-12-18T12:58:29.322133Z","shell.execute_reply.started":"2023-12-18T12:58:19.399775Z","shell.execute_reply":"2023-12-18T12:58:29.321354Z"},"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\n%matplotlib inline \nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2023-12-18T12:58:29.323430Z","iopub.execute_input":"2023-12-18T12:58:29.323834Z","iopub.status.idle":"2023-12-18T12:58:29.737560Z","shell.execute_reply.started":"2023-12-18T12:58:29.323806Z","shell.execute_reply":"2023-12-18T12:58:29.736788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Определяем, какой ускоритель можем использовать","metadata":{}},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n# Обнаружение оборудования, возврат соответствующей стратегии распространения: TPU, GPU, CPU\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # Обнаружение TPU. Параметры среды не требуются, если задана переменная среды TPU_NAME. На Kaggle это всегда так.\n    print('Running on TPU ')\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":"2023-12-18T12:58:43.015970Z","iopub.execute_input":"2023-12-18T12:58:43.016360Z","iopub.status.idle":"2023-12-18T12:58:51.417410Z","shell.execute_reply.started":"2023-12-18T12:58:43.016330Z","shell.execute_reply":"2023-12-18T12:58:51.416507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Получаем путь\nНо можно использоать просто строку, но оставим как есть","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() #получаем путь к наборам данных","metadata":{"execution":{"iopub.status.busy":"2023-12-18T12:58:54.322149Z","iopub.execute_input":"2023-12-18T12:58:54.322976Z","iopub.status.idle":"2023-12-18T12:59:02.062891Z","shell.execute_reply.started":"2023-12-18T12:58:54.322944Z","shell.execute_reply":"2023-12-18T12:59:02.061993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Параметры","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512] # при таком размере графическому процессору не хватит памяти. Используйте TPU\nEPOCHS = 20\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":"2023-12-18T12:59:03.906751Z","iopub.execute_input":"2023-12-18T12:59:03.907600Z","iopub.status.idle":"2023-12-18T12:59:03.927186Z","shell.execute_reply.started":"2023-12-18T12:59:03.907562Z","shell.execute_reply":"2023-12-18T12:59:03.926232Z"},"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":"2023-12-18T12:59:05.482479Z","iopub.execute_input":"2023-12-18T12:59:05.482800Z","iopub.status.idle":"2023-12-18T12:59:11.060294Z","shell.execute_reply.started":"2023-12-18T12:59:05.482772Z","shell.execute_reply":"2023-12-18T12:59:11.059357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Построить модель на TPU (или GPU, или CPU...) с Tensorflow 2.1!","metadata":{}},{"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 = .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":"2023-12-18T12:59:13.077864Z","iopub.execute_input":"2023-12-18T12:59:13.078191Z","iopub.status.idle":"2023-12-18T12:59:13.346756Z","shell.execute_reply.started":"2023-12-18T12:59:13.078163Z","shell.execute_reply":"2023-12-18T12:59:13.345971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Обучение\n","metadata":{}},{"cell_type":"code","source":"def get_model(use_model,weights):\n    base_model = use_model(weights=weights, \n                      include_top=False, pooling='avg',\n                      input_shape=(*IMAGE_SIZE, 3))\n#     base_model.trainable = False\n    x = base_model.output\n    predictions = Dense(104, activation='softmax')(x)\n    return Model(inputs=base_model.input, outputs=predictions)\n","metadata":{"execution":{"iopub.status.busy":"2023-12-18T12:59:17.171121Z","iopub.execute_input":"2023-12-18T12:59:17.172037Z","iopub.status.idle":"2023-12-18T12:59:20.687233Z","shell.execute_reply.started":"2023-12-18T12:59:17.172001Z","shell.execute_reply":"2023-12-18T12:59:20.686344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## VGG19","metadata":{}},{"cell_type":"code","source":"with strategy.scope():    \n    vgg19 = get_model(VGG19, 'imagenet')\n    ","metadata":{"execution":{"iopub.status.busy":"2023-12-18T13:02:13.326413Z","iopub.execute_input":"2023-12-18T13:02:13.326841Z","iopub.status.idle":"2023-12-18T13:04:39.827890Z","shell.execute_reply.started":"2023-12-18T13:02:13.326807Z","shell.execute_reply":"2023-12-18T13:04:39.826763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg19.compile(\n    optimizer='nadam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-12-18T13:04:39.829583Z","iopub.execute_input":"2023-12-18T13:04:39.829869Z","iopub.status.idle":"2023-12-18T13:04:40.079005Z","shell.execute_reply.started":"2023-12-18T13:04:39.829841Z","shell.execute_reply":"2023-12-18T13:04:40.078021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train_q = get_training_dataset()\ndata_train_q","metadata":{"execution":{"iopub.status.busy":"2023-12-18T13:04:40.080068Z","iopub.execute_input":"2023-12-18T13:04:40.080362Z","iopub.status.idle":"2023-12-18T13:04:41.484979Z","shell.execute_reply.started":"2023-12-18T13:04:40.080333Z","shell.execute_reply":"2023-12-18T13:04:41.483889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = vgg19.fit(data_train_q, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          callbacks=[lr_callback, ModelCheckpoint(filepath='VGG19.h5', monitor='val_loss',\n                                  save_best_only=True)],\n          workers = 3)","metadata":{"execution":{"iopub.status.busy":"2023-12-18T13:04:50.665183Z","iopub.execute_input":"2023-12-18T13:04:50.665594Z","iopub.status.idle":"2023-12-18T13:27:08.770186Z","shell.execute_reply.started":"2023-12-18T13:04:50.665560Z","shell.execute_reply":"2023-12-18T13:27:08.768836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## ResNet50V2","metadata":{}},{"cell_type":"code","source":"with strategy.scope():    \n    resnet = get_model(ResNet50V2, 'imagenet')\n        \nresnet.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)","metadata":{"execution":{"iopub.status.busy":"2023-12-18T13:27:08.772460Z","iopub.execute_input":"2023-12-18T13:27:08.772740Z","iopub.status.idle":"2023-12-18T13:27:24.602876Z","shell.execute_reply.started":"2023-12-18T13:27:08.772712Z","shell.execute_reply":"2023-12-18T13:27:24.601775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = resnet.fit(data_train_q, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n         callbacks=[lr_callback, ModelCheckpoint(filepath='ResNet50V2.h5', monitor='val_loss',\n                                  save_best_only=True)],workers = 3)","metadata":{"execution":{"iopub.status.busy":"2023-12-18T13:27:24.604082Z","iopub.execute_input":"2023-12-18T13:27:24.604364Z","iopub.status.idle":"2023-12-18T13:44:38.196634Z","shell.execute_reply.started":"2023-12-18T13:27:24.604336Z","shell.execute_reply":"2023-12-18T13:44:38.195670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## EfficientNetB7","metadata":{}},{"cell_type":"code","source":"with strategy.scope():    \n    efficientnet = get_model(EfficientNetB7, 'noisy-student')\n        \nefficientnet.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-12-18T13:44:38.198741Z","iopub.execute_input":"2023-12-18T13:44:38.199032Z","iopub.status.idle":"2023-12-18T13:45:36.198432Z","shell.execute_reply.started":"2023-12-18T13:44:38.198995Z","shell.execute_reply":"2023-12-18T13:45:36.197107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = efficientnet.fit(data_train_q, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          callbacks=[lr_callback, ModelCheckpoint(filepath='efficientnet_b7.h5', monitor='val_loss',\n                                  save_best_only=True)],workers = 3)","metadata":{"execution":{"iopub.status.busy":"2023-12-18T13:45:36.199852Z","iopub.execute_input":"2023-12-18T13:45:36.200163Z","iopub.status.idle":"2023-12-18T14:29:15.860952Z","shell.execute_reply.started":"2023-12-18T13:45:36.200133Z","shell.execute_reply":"2023-12-18T14:29:15.859802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Для сравнение 3 моделей должно быть достаточно.","metadata":{}},{"cell_type":"markdown","source":"# Сравнение моделей","metadata":{}},{"cell_type":"code","source":"eval_dataset = get_validation_dataset()\n\neval_results = {\n    'VGG19': vgg19.evaluate(eval_dataset)[1],\n    'ResNet50V2': resnet.evaluate(eval_dataset)[1],\n    'EfficientNetB7': efficientnet.evaluate(eval_dataset)[1],\n}\n\nfig, ax = plt.subplots()\nax.bar(list(eval_results.keys()), list(eval_results.values()))\nax.set_ylabel('sparse_categorical_accuracy')\nax.set_title('Метрика моделей на валидационных данных')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-18T14:29:15.863296Z","iopub.execute_input":"2023-12-18T14:29:15.863598Z","iopub.status.idle":"2023-12-18T14:30:29.887780Z","shell.execute_reply.started":"2023-12-18T14:29:15.863570Z","shell.execute_reply":"2023-12-18T14:30:29.886750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Лучшая модель EfficientNetB7, будем использовать её.","metadata":{}},{"cell_type":"markdown","source":"Процесс обучения EfficientNetB7 представлен в предыдущей версии NoteBook'а.","metadata":{}},{"cell_type":"markdown","source":"# Обучение для сабмита.","metadata":{}},{"cell_type":"markdown","source":"Чистим память","metadata":{}},{"cell_type":"code","source":"#del vgg19, resnet, efficientnet, history","metadata":{"execution":{"iopub.status.busy":"2023-12-17T22:27:28.737315Z","iopub.execute_input":"2023-12-17T22:27:28.737636Z","iopub.status.idle":"2023-12-17T22:27:28.742640Z","shell.execute_reply.started":"2023-12-17T22:27:28.737594Z","shell.execute_reply":"2023-12-17T22:27:28.741743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#with strategy.scope():    \n#    model = get_model(EfficientNetB7, 'noisy-student')\n        \n#model.compile(\n#    optimizer='adam',\n#    loss = 'sparse_categorical_crossentropy',\n#    metrics=['sparse_categorical_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-12-18T00:19:58.983858Z","iopub.execute_input":"2023-12-18T00:19:58.984304Z","iopub.status.idle":"2023-12-18T00:20:34.077048Z","shell.execute_reply.started":"2023-12-18T00:19:58.984262Z","shell.execute_reply":"2023-12-18T00:20:34.075929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Ставим 40 эпох, должно быть достаточно.","metadata":{}},{"cell_type":"code","source":"#EPOCHS = 35","metadata":{"execution":{"iopub.status.busy":"2023-12-18T00:03:28.719565Z","iopub.execute_input":"2023-12-18T00:03:28.719853Z","iopub.status.idle":"2023-12-18T00:03:28.724001Z","shell.execute_reply.started":"2023-12-18T00:03:28.719827Z","shell.execute_reply":"2023-12-18T00:03:28.723174Z"},"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='efficientnet_b7.h5', monitor='val_loss',\n#                                  save_best_only=True)],\n#          validation_data=get_validation_dataset(),\n#          workers = 3)","metadata":{"execution":{"iopub.status.busy":"2023-12-18T00:20:34.078623Z","iopub.execute_input":"2023-12-18T00:20:34.078909Z","iopub.status.idle":"2023-12-18T00:27:27.978652Z","shell.execute_reply.started":"2023-12-18T00:20:34.078865Z","shell.execute_reply":"2023-12-18T00:27:27.977298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Выводим графики хода обучения.","metadata":{}},{"cell_type":"code","source":"#plt.plot(history.history['sparse_categorical_accuracy'], \n#         label='Оценка точности на обучающем наборе')\n#plt.plot(history.history['val_sparse_categorical_accuracy'], \n#         label='Оценка точности на проверочном наборе')\n#plt.xlabel('Эпоха обучения')\n#plt.ylabel('Оценка точности')\n#plt.legend()\n#plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-18T00:28:41.943125Z","iopub.execute_input":"2023-12-18T00:28:41.943551Z","iopub.status.idle":"2023-12-18T00:28:42.114176Z","shell.execute_reply.started":"2023-12-18T00:28:41.943517Z","shell.execute_reply":"2023-12-18T00:28:42.113065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#plt.plot(history.history['loss'], \n#         label='Оценка потерь на обучающем наборе')\n#plt.plot(history.history['val_loss'], \n#         label='Оценка потерь на проверочном наборе')\n#plt.xlabel('Эпоха обучения')\n#plt.ylabel('Оценка потерь')\n#plt.legend()\n#plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-18T00:28:44.311727Z","iopub.execute_input":"2023-12-18T00:28:44.312077Z","iopub.status.idle":"2023-12-18T00:28:44.451013Z","shell.execute_reply.started":"2023-12-18T00:28:44.312048Z","shell.execute_reply":"2023-12-18T00:28:44.449907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Загружаем модель","metadata":{}},{"cell_type":"code","source":"model = tf.keras.models.load_model('efficientnet_b7.h5')","metadata":{"execution":{"iopub.status.busy":"2023-12-18T00:28:48.311038Z","iopub.execute_input":"2023-12-18T00:28:48.311416Z","iopub.status.idle":"2023-12-18T00:28:59.104606Z","shell.execute_reply.started":"2023-12-18T00:28:48.311384Z","shell.execute_reply":"2023-12-18T00:28:59.103425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Вычислите свои прогнозы на тестовом наборе!\n\nCоздадим файл, который можно будет отправить на конкурс.","metadata":{}},{"cell_type":"code","source":"# Поскольку мы разделяем набор данных и выполняем итерацию отдельно для изображений и идентификаторов, порядок имеет значение.\n#test_ds = get_test_dataset(ordered=True) \n\n#print('Вычисляем предсказания...')\n#test_images_ds = test_ds.map(lambda image, idnum: image)\n#probabilities = model.predict(test_images_ds)\n#predictions = np.argmax(probabilities, axis=-1)\n#print(predictions)\n\n#print('Создание файла submission.csv...')\n#test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n#test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # все в одной партии\n#np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"execution":{"iopub.status.busy":"2023-12-18T00:29:02.202777Z","iopub.execute_input":"2023-12-18T00:29:02.203171Z","iopub.status.idle":"2023-12-18T00:30:54.466919Z","shell.execute_reply.started":"2023-12-18T00:29:02.203139Z","shell.execute_reply":"2023-12-18T00:30:54.465466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}