{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","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":211071664,"sourceType":"kernelVersion"},{"sourceId":211051890,"sourceType":"kernelVersion"}],"dockerImageVersionId":30448,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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-04T05:26:37.091494Z","iopub.execute_input":"2024-12-04T05:26:37.091907Z","iopub.status.idle":"2024-12-04T05:26:48.228230Z","shell.execute_reply.started":"2024-12-04T05:26:37.091872Z","shell.execute_reply":"2024-12-04T05:26:48.227014Z"}},"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 random\nimport os\nimport re\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","execution":{"iopub.status.busy":"2024-12-04T05:27:50.839902Z","iopub.execute_input":"2024-12-04T05:27:50.840323Z","iopub.status.idle":"2024-12-04T05:27:57.910086Z","shell.execute_reply.started":"2024-12-04T05:27:50.840285Z","shell.execute_reply":"2024-12-04T05:27:57.908984Z"},"trusted":true},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T05:28:01.200888Z","iopub.execute_input":"2024-12-04T05:28:01.202603Z","iopub.status.idle":"2024-12-04T05:28:01.780042Z","shell.execute_reply.started":"2024-12-04T05:28:01.202554Z","shell.execute_reply":"2024-12-04T05:28:01.779214Z"}},"outputs":[],"execution_count":null},{"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 ', 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":{"execution":{"iopub.status.busy":"2024-12-04T05:28:01.847096Z","iopub.execute_input":"2024-12-04T05:28:01.847971Z","iopub.status.idle":"2024-12-04T05:28:01.861147Z","shell.execute_reply.started":"2024-12-04T05:28:01.847938Z","shell.execute_reply":"2024-12-04T05:28:01.859864Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Get my data path","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path(\"tpu-getting-started\") #получаем путь к наборам данных","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T05:28:02.548297Z","iopub.execute_input":"2024-12-04T05:28:02.548752Z","iopub.status.idle":"2024-12-04T05:28:02.912005Z","shell.execute_reply.started":"2024-12-04T05:28:02.548719Z","shell.execute_reply":"2024-12-04T05:28:02.911168Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512] # при таком размере графическому процессору не хватит памяти. Используйте TPU\n# IMAGE_SIZE = [224, 224] # при таком размере графическому процессору не хватит памяти. Используйте TPU\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":"2024-12-04T05:28:02.913812Z","iopub.execute_input":"2024-12-04T05:28:02.914781Z","iopub.status.idle":"2024-12-04T05:28:05.476415Z","shell.execute_reply.started":"2024-12-04T05:28:02.914738Z","shell.execute_reply":"2024-12-04T05:28:05.475240Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Set some parameters","metadata":{}},{"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    return image\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    image = tf.image.random_flip_left_right(image, seed=SEED)\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    \"\"\"Читает из TFRecords. Для оптимальной производительности одновременное чтение из нескольких\n    файлов без учета порядка данных. Порядок не имеет значения, поскольку мы все равно будем перетасовывать данные\"\"\"\n\n    ignore_order = tf.data.Options() # Представляет параметры для tf.data.Dataset.\n    if not ordered:\n        ignore_order.experimental_deterministic = False # отключить порядок, увеличить скорость\n\n    dataset = tf.data.TFRecordDataset(filenames) # автоматически чередует чтение из нескольких файлов\n    dataset = dataset.with_options(ignore_order) # использует данные сразу после их поступления, а не в исходном порядке\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)\n    # возвращает набор данных пар (изображение, метка), если метка = Истина, или пар (изображение, идентификатор), если метка = Ложь\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache() # кешируем набор\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\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\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint('Dataset: {} validation images, {} unlabeled test images'.format(NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2024-12-04T05:28:05.478953Z","iopub.execute_input":"2024-12-04T05:28:05.479299Z","iopub.status.idle":"2024-12-04T05:28:05.498253Z","shell.execute_reply.started":"2024-12-04T05:28:05.479268Z","shell.execute_reply":"2024-12-04T05:28:05.497334Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Построить модель на TPU (или GPU, или CPU...) с Tensorflow 2.1!","metadata":{}},{"cell_type":"code","source":"def get_model(use_model):\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    predictions = Dense(104, activation='softmax')(x)\n    model = Model(inputs=base_model.input, outputs=predictions)\n    model.compile(\n                optimizer='nadam',\n                loss = 'sparse_categorical_crossentropy',\n                metrics=['sparse_categorical_accuracy']\n                )\n    return model ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T05:28:05.499451Z","iopub.execute_input":"2024-12-04T05:28:05.500165Z","iopub.status.idle":"2024-12-04T05:28:05.513445Z","shell.execute_reply.started":"2024-12-04T05:28:05.500137Z","shell.execute_reply":"2024-12-04T05:28:05.512620Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():    \n    model1 = get_model(EfficientNetB7)\nmodel1.load_weights(\"/kaggle/input/start-with-pre-train-effisientnet/my_ef_net_b7.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T05:28:05.515295Z","iopub.execute_input":"2024-12-04T05:28:05.515946Z","iopub.status.idle":"2024-12-04T05:28:22.337961Z","shell.execute_reply.started":"2024-12-04T05:28:05.515909Z","shell.execute_reply":"2024-12-04T05:28:22.337019Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():    \n    model2 = get_model(EfficientNetB7)\nmodel2.load_weights(\"/kaggle/input/start-with-pre-train-efficientnet-v2/my_efficientnet_v2.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T05:28:22.339534Z","iopub.execute_input":"2024-12-04T05:28:22.339851Z","iopub.status.idle":"2024-12-04T05:28:32.930483Z","shell.execute_reply.started":"2024-12-04T05:28:22.339793Z","shell.execute_reply":"2024-12-04T05:28:32.929607Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import f1_score\nval_dataset = get_validation_dataset()\nimages_ds = val_dataset.map(lambda image, label: image)\nlabels_ds = val_dataset.map(lambda image, label: label).unbatch()\nval_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() # get everything as one batch\nm1 = model1.predict(images_ds)\nm2 = model2.predict(images_ds)\nscores = []\nfor alpha in np.linspace(0,1,100):\n    val_probabilities = alpha*m1+(1-alpha)*m2\n    val_predictions = np.argmax(val_probabilities, axis=-1)\n    scores.append(f1_score(val_labels, val_predictions, labels=range(104), average='macro'))\n\nbest_alpha = np.argmax(scores)/100\n    \nprint('Best alpha: ' + str(best_alpha))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T05:28:32.931767Z","iopub.execute_input":"2024-12-04T05:28:32.932106Z","iopub.status.idle":"2024-12-04T05:33:38.133652Z","shell.execute_reply.started":"2024-12-04T05:28:32.932077Z","shell.execute_reply":"2024-12-04T05:33:38.132287Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Поскольку мы разделяем набор данных и выполняем итерацию отдельно для изображений и идентификаторов, порядок имеет значение.\ntest_ds = get_test_dataset(ordered=True) \n\nprint('Вычисляем предсказания...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\n\nprobabilities1 = model1.predict(test_images_ds)\nprobabilities2 = model2.predict(test_images_ds)\nprobabilities = best_alpha * probabilities1 + (1 - best_alpha) * probabilities2\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('Создание файла submission.csv...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # все в одной партии\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T05:33:38.135719Z","iopub.execute_input":"2024-12-04T05:33:38.136128Z","iopub.status.idle":"2024-12-04T05:42:55.841952Z","shell.execute_reply.started":"2024-12-04T05:33:38.136098Z","shell.execute_reply":"2024-12-04T05:42:55.841005Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}