{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","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"},{"sourceId":211686443,"sourceType":"kernelVersion"},{"sourceId":211728858,"sourceType":"kernelVersion"}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# TF 2.2 блокнот","metadata":{}},{"cell_type":"code","source":"!pip install -q efficientnet","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T15:05:30.934422Z","iopub.execute_input":"2024-12-07T15:05:30.934680Z","iopub.status.idle":"2024-12-07T15:05:40.545877Z","shell.execute_reply.started":"2024-12-07T15:05:30.934653Z","shell.execute_reply":"2024-12-07T15:05:40.544789Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.applications.densenet import DenseNet201\nfrom efficientnet.tfkeras import EfficientNetB7\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense\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","trusted":true,"execution":{"iopub.status.busy":"2024-12-07T15:06:14.050637Z","iopub.execute_input":"2024-12-07T15:06:14.051571Z","iopub.status.idle":"2024-12-07T15:06:25.202454Z","shell.execute_reply.started":"2024-12-07T15:06:14.051520Z","shell.execute_reply":"2024-12-07T15:06:25.201581Z"}},"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.\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T15:06:28.919941Z","iopub.execute_input":"2024-12-07T15:06:28.921408Z","iopub.status.idle":"2024-12-07T15:06:28.928108Z","shell.execute_reply.started":"2024-12-07T15:06:28.921356Z","shell.execute_reply":"2024-12-07T15:06:28.927023Z"}},"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-07T15:06:30.802066Z","iopub.execute_input":"2024-12-07T15:06:30.803027Z","iopub.status.idle":"2024-12-07T15:06:31.106475Z","shell.execute_reply.started":"2024-12-07T15:06:30.802988Z","shell.execute_reply":"2024-12-07T15:06:31.105620Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Set some parameters","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512] # при таком размере графическому процессору не хватит памяти. Используйте 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\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')\n\nSEED = 2020","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T15:11:32.697645Z","iopub.execute_input":"2024-12-07T15:11:32.697998Z","iopub.status.idle":"2024-12-07T15:11:33.877937Z","shell.execute_reply.started":"2024-12-07T15:11:32.697968Z","shell.execute_reply":"2024-12-07T15:11:33.877001Z"}},"outputs":[],"execution_count":null},{"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 get_validation_dataset():\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)\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\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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T15:11:33.879429Z","iopub.execute_input":"2024-12-07T15:11:33.879714Z","iopub.status.idle":"2024-12-07T15:11:33.893506Z","shell.execute_reply.started":"2024-12-07T15:11:33.879689Z","shell.execute_reply":"2024-12-07T15:11:33.892594Z"}},"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#     # Create DenseNet201 model\n#     rnet = DenseNet201(\n#         input_shape = (224, 224, 3),\n#         weights = 'imagenet',  # Use the preset parameters of ImageNet\n#         #include_top = False  # Drop the fully connected network on the top\n#     )\n    \n#     rnet.trainable = True\n#     model = tf.keras.Sequential([\n#         rnet,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(104, activation = 'softmax')\n#     ])\n\n#     return model\n# with strategy.scope():    \n#     model1 = get_model(DenseNet201) # тут подставить свою модель\n\n# model1.load_weights('/kaggle/input/pretraindensenet-201/dense201_net.keras')\nmodel1 = tf.keras.models.load_model('/kaggle/input/pretraindensenet-201/dense201_net.keras')","metadata":{"execution":{"iopub.status.busy":"2024-12-07T15:11:33.900616Z","iopub.execute_input":"2024-12-07T15:11:33.900873Z","iopub.status.idle":"2024-12-07T15:12:08.792278Z","shell.execute_reply.started":"2024-12-07T15:11:33.900848Z","shell.execute_reply":"2024-12-07T15:12:08.790965Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# def get_model(use_model):\n#     pretrained_model = use_model(weights = 'noisy-student', include_top = False, input_shape = [*IMAGE_SIZE, 3])\n#     #pretrained_model.trainable = True\n\n#     model = tf.keras.Sequential([\n#         pretrained_model,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(104, activation = 'softmax')\n#     ])\n\n#     return model\n\n# with strategy.scope():    \n#     model2 = get_model(EfficientNetB7) # тут подставить свою модель\n# model2.load_weights(\"/kaggle/input/pre-train-3/ef_net.keras\") \nmodel2 = tf.keras.models.load_model('/kaggle/input/pre-train-3/ef_net2.keras')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T15:12:44.521071Z","iopub.execute_input":"2024-12-07T15:12:44.521780Z","iopub.status.idle":"2024-12-07T15:14:08.513442Z","shell.execute_reply.started":"2024-12-07T15:12:44.521748Z","shell.execute_reply":"2024-12-07T15:14:08.512658Z"}},"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-07T15:14:08.516159Z","iopub.execute_input":"2024-12-07T15:14:08.516406Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Вычислите свои прогнозы на тестовом наборе!\n\nCоздадим файл, который можно будет отправить на конкурс.","metadata":{}},{"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},"outputs":[],"execution_count":null}]}