{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam\nimport matplotlib.pyplot as plt","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-23T01:45:47.729831Z","iopub.execute_input":"2024-05-23T01:45:47.730185Z","iopub.status.idle":"2024-05-23T01:46:00.182574Z","shell.execute_reply.started":"2024-05-23T01:45:47.730158Z","shell.execute_reply":"2024-05-23T01:46:00.181816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\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()  # Default strategy that works on CPU and single GPU\n\nprint('Number of replicas:', strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2024-05-23T01:46:00.184195Z","iopub.execute_input":"2024-05-23T01:46:00.184684Z","iopub.status.idle":"2024-05-23T01:46:00.193054Z","shell.execute_reply.started":"2024-05-23T01:46:00.184659Z","shell.execute_reply":"2024-05-23T01:46:00.192200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\ndata_dir = GCS_DS_PATH + \"/tfrecords-jpeg-224x224\"","metadata":{"execution":{"iopub.status.busy":"2024-05-23T01:46:00.194118Z","iopub.execute_input":"2024-05-23T01:46:00.194373Z","iopub.status.idle":"2024-05-23T01:46:03.507550Z","shell.execute_reply.started":"2024-05-23T01:46:00.194350Z","shell.execute_reply":"2024-05-23T01:46:03.506344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224] # при таком размере графическому процессору не хватит памяти. Используйте TPU\nEPOCHS = 100\nBATCH_SIZE = 32 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\ndata_augmentation = tf.keras.Sequential([\n  tf.keras.layers.RandomFlip(\"horizontal\"),\n  tf.keras.layers.RandomRotation(0.25),\n  tf.keras.layers.RandomZoom(0.1),\n  tf.keras.layers.RandomContrast(0.1)    \n])\n","metadata":{"execution":{"iopub.status.busy":"2024-05-23T01:46:03.508974Z","iopub.execute_input":"2024-05-23T01:46:03.509274Z","iopub.status.idle":"2024-05-23T01:46:04.253607Z","shell.execute_reply.started":"2024-05-23T01:46:03.509248Z","shell.execute_reply":"2024-05-23T01:46:04.252791Z"},"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) # автоматически чередует чтение из нескольких файлов\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_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-224x224/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # набор обучающих данных должен повторяться в течение нескольких эпох\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-224x224/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-224x224/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()\n\nAUTOTUNE = tf.data.AUTOTUNE\n\ndata_augmentation = tf.keras.Sequential([\n  tf.keras.layers.RandomFlip(\"horizontal\"),\n  tf.keras.layers.RandomRotation(0.25),\n  tf.keras.layers.RandomZoom(0.1),\n  tf.keras.layers.RandomContrast(0.1)    \n])\n\n\ndef prepare(ds,  augment=False):\n    if augment:\n        ds = ds.map(lambda x, y: (data_augmentation(x, training=True), y),\n                num_parallel_calls=AUTOTUNE)\n    return ds.prefetch(buffer_size=AUTOTUNE)\n\ntraining_dataset = prepare(training_dataset, augment=True)","metadata":{"execution":{"iopub.status.busy":"2024-05-23T01:46:04.255768Z","iopub.execute_input":"2024-05-23T01:46:04.256082Z","iopub.status.idle":"2024-05-23T01:46:04.767526Z","shell.execute_reply.started":"2024-05-23T01:46:04.256058Z","shell.execute_reply":"2024-05-23T01:46:04.766768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Activation, MaxPooling2D, Dropout, GlobalAveragePooling2D, Dense, Multiply, Reshape\n\ndef se_block(input_tensor, reduction_ratio=16):\n    channel_axis = -1\n    filters = input_tensor.shape[channel_axis]\n\n    se_shape = (1, 1, filters)\n\n    se = GlobalAveragePooling2D()(input_tensor)\n    se = Reshape(se_shape)(se)\n    se = Dense(filters // reduction_ratio, activation='relu', kernel_initializer='he_normal', use_bias=False)(se)\n    se = Dense(filters, activation='sigmoid', kernel_initializer='he_normal', use_bias=False)(se)\n    se = Multiply()([input_tensor, se])\n    return se\n\ndef conv_block(input_tensor, filters, kernel_size, strides=(1, 1)):\n    x = Conv2D(filters, kernel_size, strides=strides, padding='same', activation='relu')(input_tensor)\n    x = BatchNormalization()(x)\n    return x\n\ndef build_model(input_shape=(224, 224, 3), num_classes=104):\n    inputs = Input(shape=input_shape)\n\n    ## Первый сверточный блок с SE-блоком\n    x = conv_block(inputs, filters=32, kernel_size=(3, 3))\n    x = conv_block(x, filters=32, kernel_size=(3, 3))\n    x = se_block(x)\n    x = MaxPooling2D(pool_size=(2, 2))(x)\n    x = Dropout(0.25)(x)\n\n    ## Второй сверточный блок с SE-блоком\n    x = conv_block(x, filters=64, kernel_size=(3, 3))\n    x = conv_block(x, filters=64, kernel_size=(3, 3))\n    x = se_block(x)\n    x = MaxPooling2D(pool_size=(2, 2))(x)\n    x = Dropout(0.35)(x)\n\n    ## Третий сверточный блок с SE-блоком\n    x = conv_block(x, filters=128, kernel_size=(3, 3))\n    x = conv_block(x, filters=128, kernel_size=(3, 3))\n    x = se_block(x)\n    x = MaxPooling2D(pool_size=(2, 2))(x)\n    x = Dropout(0.45)(x)\n\n    ## Полносвязный блок\n    x = GlobalAveragePooling2D()(x)\n    x = Dense(256, activation='relu')(x)\n    x = BatchNormalization()(x)\n    x = Dropout(0.5)(x)\n\n    # Выходной полносвязный слой\n    outputs = Dense(num_classes, activation='softmax')(x)\n\n    model = Model(inputs=inputs, outputs=outputs)\n    return model\n\n# Пример создания модели\nmodel = build_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-23T01:46:04.768650Z","iopub.execute_input":"2024-05-23T01:46:04.768943Z","iopub.status.idle":"2024-05-23T01:46:05.063790Z","shell.execute_reply.started":"2024-05-23T01:46:04.768920Z","shell.execute_reply":"2024-05-23T01:46:05.062945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras.metrics import Precision, Recall\n\ncallbacks_list = [\n    EarlyStopping(monitor='val_loss', patience=7, restore_best_weights=True),\n    ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=5),\n    ModelCheckpoint(filepath='best_model.keras', monitor='val_loss', save_best_only=True)\n]\n\nmodel.compile(\n    optimizer='nadam',  # Устанавливаем начальный learning rate\n    loss='sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical = model.fit(\n    training_dataset, \n    steps_per_epoch=STEPS_PER_EPOCH, \n    epochs=100, \n    callbacks=callbacks_list,\n    validation_data=validation_dataset\n)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-23T01:49:26.854219Z","iopub.execute_input":"2024-05-23T01:49:26.854598Z","iopub.status.idle":"2024-05-23T01:49:31.810699Z","shell.execute_reply.started":"2024-05-23T01:49:26.854568Z","shell.execute_reply":"2024-05-23T01:49:31.808545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Получение значений метрик из истории обучения\ntrain_accuracy = historical.history['sparse_categorical_accuracy']\nval_accuracy = historical.history['val_sparse_categorical_accuracy']\ntrain_loss = historical.history['loss']\nval_loss = historical.history['val_loss']\n\n# Построение графиков точности и потерь\nepochs = range(1, len(train_accuracy) + 1)\n\n# График точности\nplt.plot(epochs, train_accuracy, 'b', label='Training Accuracy')\nplt.plot(epochs, val_accuracy, 'r', label='Validation Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\n# График потерь\nplt.plot(epochs, train_loss, 'b', label='Training Loss')\nplt.plot(epochs, val_loss, 'r', label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-23T01:46:05.895524Z","iopub.status.idle":"2024-05-23T01:46:05.895890Z","shell.execute_reply.started":"2024-05-23T01:46:05.895705Z","shell.execute_reply":"2024-05-23T01:46:05.895720Z"},"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-05-23T01:46:05.897248Z","iopub.status.idle":"2024-05-23T01:46:05.897550Z","shell.execute_reply.started":"2024-05-23T01:46:05.897400Z","shell.execute_reply":"2024-05-23T01:46:05.897413Z"},"trusted":true},"execution_count":null,"outputs":[]}]}