{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.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"}],"dockerImageVersionId":31261,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import kagglehub","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:12:14.565326Z","iopub.execute_input":"2026-01-21T08:12:14.566023Z","iopub.status.idle":"2026-01-21T08:12:15.209669Z","shell.execute_reply.started":"2026-01-21T08:12:14.565997Z","shell.execute_reply":"2026-01-21T08:12:15.209101Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"tpu_getting_started_path = kagglehub.competition_download('tpu-getting-started')\n\nprint('Data source import complete.')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:12:16.494039Z","iopub.execute_input":"2026-01-21T08:12:16.494461Z","iopub.status.idle":"2026-01-21T08:12:17.009259Z","shell.execute_reply.started":"2026-01-21T08:12:16.494433Z","shell.execute_reply":"2026-01-21T08:12:17.008680Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n!pip install efficientnet\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:12:36.723111Z","iopub.execute_input":"2026-01-21T08:12:36.723890Z","iopub.status.idle":"2026-01-21T08:12:41.216376Z","shell.execute_reply.started":"2026-01-21T08:12:36.723846Z","shell.execute_reply":"2026-01-21T08:12:41.215373Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\nimport efficientnet.tfkeras as efficientnet\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nimport re\nimport warnings\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom sklearn.metrics import classification_report, f1_score\nfrom sklearn.model_selection import train_test_split\n\nwarnings.filterwarnings(\"ignore\")\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:12:44.340443Z","iopub.execute_input":"2026-01-21T08:12:44.341121Z","iopub.status.idle":"2026-01-21T08:12:44.667390Z","shell.execute_reply.started":"2026-01-21T08:12:44.341089Z","shell.execute_reply":"2026-01-21T08:12:44.666659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = (\n        tf.distribute.cluster_resolver.TPUClusterResolver()\n    )  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\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 = (\n        tf.distribute.get_strategy()\n    )  # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:12:50.315457Z","iopub.execute_input":"2026-01-21T08:12:50.316457Z","iopub.status.idle":"2026-01-21T08:12:50.322511Z","shell.execute_reply.started":"2026-01-21T08:12:50.316429Z","shell.execute_reply":"2026-01-21T08:12:50.321858Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Загрузка данных","metadata":{}},{"cell_type":"code","source":"size = 224\nIMAGE_SIZE = [224, 224]\nBATCH_SIZE = 8\nEPOCHS = 30\n\nprint(f\"Размер изображения: {IMAGE_SIZE[0]}x{IMAGE_SIZE[1]}\")\n\nGCS_PATH = \"/kaggle/input/tpu-getting-started\"\nTRAIN_PATH = f\"{GCS_PATH}/tfrecords-jpeg-{IMAGE_SIZE[0]}x{IMAGE_SIZE[1]}/train\"\nVAL_PATH = f\"{GCS_PATH}/tfrecords-jpeg-{IMAGE_SIZE[0]}x{IMAGE_SIZE[1]}/val\"\nTEST_PATH = f\"{GCS_PATH}/tfrecords-jpeg-{IMAGE_SIZE[0]}x{IMAGE_SIZE[1]}/test\"\n\nsubmission_df = pd.read_csv(f\"{GCS_PATH}/sample_submission.csv\")\nprint(f\"Количество образцов: {len(submission_df)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:12:53.622914Z","iopub.execute_input":"2026-01-21T08:12:53.623436Z","iopub.status.idle":"2026-01-21T08:12:53.646271Z","shell.execute_reply.started":"2026-01-21T08:12:53.623409Z","shell.execute_reply":"2026-01-21T08:12:53.645557Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Необходимые функции","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data):\n    \"\"\"Декодирует изображение из формата TFRecord\"\"\"\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # Нормализация\n    image = tf.image.resize(image, IMAGE_SIZE)\n    return image\n\ndef read_labeled_tfrecord(example):\n    \"\"\"Читает размеченные данные из TFRecord\"\"\"\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], 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    \"\"\"Читает немаркированные данные из TFRecord (для теста)\"\"\"\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"id\": tf.io.FixedLenFeature([], tf.string),\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\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    \"\"\"Загружает датасет из TFRecord файлов\"\"\"\n    ignore_order = tf.data.Options()\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\n    if labeled:\n        dataset = dataset.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n    else:\n        dataset = dataset.map(read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n\n    return dataset\n\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    \"\"\"Загружает датасет из TFRecord файлов\"\"\"\n    ignore_order = tf.data.Options()\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\n    if labeled:\n        dataset = dataset.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n    else:\n        dataset = dataset.map(read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n\n    return dataset\ndef data_augment(x, y):\n    #x = tf.image.random_flip_left_right(x)\n    #x = tf.image.random_flip_up_down(x)\n    #x = tf.image.random_crop(x, size = [size,size,3])\n    #p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    # if p_rotate > .8:\n    #    x = tf.image.rot90(x, k=3)\n    # elif p_rotate > .6:\n    #    x = tf.image.rot90(x, k=2)\n    # elif p_rotate > .4:\n    #    x = tf.image.rot90(x, k=1)\n    #x = tf.image.random_saturation(x,0.5,2)\n    #x = tf.image.random_brightness(x, 2)\n    #x = tf.image.random_contrast(x,0.8,1.2)\n    return x, y\n\n### Getting training, validation and test dataset\ndef get_training_dataset(filenames):\n    \"\"\"Создает тренировочный датасет с аугментацией\"\"\"\n    dataset = load_dataset(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(filenames, ordered=False):\n    \"\"\"Создает валидационный датасет\"\"\"\n    dataset = load_dataset(filenames, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(\n        tf.io.gfile.glob(GCS_PATH + f\"/tfrecords-jpeg-{size}x{size}/test/*.tfrec\"),\n        labeled=False,\n        ordered=ordered,\n    )\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\n\n\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object:  # binary string in this case,\n        # these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is\n    # the case for test data)\n    return numpy_images, numpy_labels\n\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = label == correct_label\n    return (\n        \"{} [{}{}{}]\".format(\n            CLASSES[label],\n            \"OK\" if correct else \"NO\",\n            \"\\u2192\" if not correct else \"\",\n            CLASSES[correct_label] if not correct else \"\",\n        ),\n        correct,\n    )\n\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis(\"off\")\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(\n            title,\n            fontsize=int(titlesize) if not red else int(titlesize / 1.2),\n            color=\"red\" if red else \"black\",\n            fontdict={\"verticalalignment\": \"center\"},\n            pad=int(titlesize / 1.5),\n        )\n    return (subplot[0], subplot[1], subplot[2] + 1)\n\n\ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n\n    # auto-squaring: this will drop data that does not fit into square\n    # or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images) // rows\n\n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot = (rows, cols, 1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE, FIGSIZE / cols * rows))\n    else:\n        plt.figure(figsize=(FIGSIZE / rows * cols, FIGSIZE))\n\n    # display\n    for i, (image, label) in enumerate(\n        zip(images[: rows * cols], labels[: rows * cols])\n    ):\n        title = \"\" if label is None else CLASSES[label]\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = (\n            FIGSIZE * SPACING / max(rows, cols) * 40 + 3\n        )  # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(\n            image, title, subplot, not correct, titlesize=dynamic_titlesize\n        )\n\n    # layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n\n\n### Defining the evolution of loss parameter\ndef lr_function(epoch):\n    start_lr = 1e-3\n    min_lr = 5e-5\n    max_lr = 1e-3\n    rampup_epochs = 5\n    sustain_epochs = 0\n    exp_decay = 0.8\n\n    def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):\n        if epoch < rampup_epochs:\n            lr = (max_lr - start_lr) / rampup_epochs * epoch + start_lr\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr\n        else:  # E\n            lr = (max_lr - min_lr) * exp_decay ** (\n                epoch - rampup_epochs - sustain_epochs\n            ) + min_lr\n        return lr\n\n    return lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay)\n\n\ncallbacks = [\n    tf.keras.callbacks.EarlyStopping(monitor='val_loss',\n                                    patience=5,\n                                    restore_best_weights=True),\n    tf.keras.callbacks.LearningRateScheduler(\n        lambda epoch: lr_function(epoch), verbose=True  # B\n    )\n]\n\n### Define function to display results\ndef display_training_curves(training, validation, title, subplot):\n    if subplot % 10 == 1:\n        plt.subplots(figsize=(10, 10), facecolor=\"#F0F0F0\")\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor(\"#F8F8F8\")\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title(\"model \" + title)\n    ax.set_ylabel(title)\n    ax.set_xlabel(\"epoch\")\n    ax.legend([\"train \", \"valid\"])\n        \ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec\n    # 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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:12:56.040959Z","iopub.execute_input":"2026-01-21T08:12:56.041589Z","iopub.status.idle":"2026-01-21T08:12:56.064376Z","shell.execute_reply.started":"2026-01-21T08:12:56.041555Z","shell.execute_reply":"2026-01-21T08:12:56.063631Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"VAL_FILENAMES = tf.io.gfile.glob(GCS_PATH + f\"/tfrecords-jpeg-{size}x{size}/val/*.tfrec\")\nTEST_FILESNAMES = tf.io.gfile.glob(GCS_PATH + f\"/tfrecords-jpeg-{size}x{size}/test/*.tfrec\")\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + f\"/tfrecords-jpeg-{size}x{size}/train/*.tfrec\") + VAL_FILENAMES","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:13:00.195423Z","iopub.execute_input":"2026-01-21T08:13:00.195698Z","iopub.status.idle":"2026-01-21T08:13:00.215539Z","shell.execute_reply.started":"2026-01-21T08:13:00.195677Z","shell.execute_reply":"2026-01-21T08:13:00.215003Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:13:01.821154Z","iopub.execute_input":"2026-01-21T08:13:01.821472Z","iopub.status.idle":"2026-01-21T08:13:01.825643Z","shell.execute_reply.started":"2026-01-21T08:13:01.821449Z","shell.execute_reply":"2026-01-21T08:13:01.824890Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Подготовка датасета","metadata":{}},{"cell_type":"code","source":"\ntrain_files = tf.io.gfile.glob(TRAIN_PATH + \"/*.tfrec\")\nval_files = tf.io.gfile.glob(VAL_PATH + \"/*.tfrec\")\n\nprint(f\"Тренировочных файлов: {len(train_files)}\")\nprint(f\"Валидационных файлов: {len(val_files)}\")\n\nnum_train_images = count_data_items(train_files)\nnum_val_images = count_data_items(val_files)\n\nprint(f\"Тренировочных изображений: {num_train_images}\")\nprint(f\"Валидационных изображений: {num_val_images}\")\n\n\n\ntrain_dataset = get_training_dataset(train_files)\nval_dataset = get_validation_dataset(val_files)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:13:05.209067Z","iopub.execute_input":"2026-01-21T08:13:05.209382Z","iopub.status.idle":"2026-01-21T08:13:06.114221Z","shell.execute_reply.started":"2026-01-21T08:13:05.209356Z","shell.execute_reply":"2026-01-21T08:13:06.113419Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.Xception(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[224,224, 3]\n    )\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    ])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:25:58.746710Z","iopub.execute_input":"2026-01-21T08:25:58.747429Z","iopub.status.idle":"2026-01-21T08:25:59.601399Z","shell.execute_reply.started":"2026-01-21T08:25:58.747400Z","shell.execute_reply":"2026-01-21T08:25:59.600775Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:16:51.942463Z","iopub.execute_input":"2026-01-21T08:16:51.943170Z","iopub.status.idle":"2026-01-21T08:16:51.963328Z","shell.execute_reply.started":"2026-01-21T08:16:51.943145Z","shell.execute_reply":"2026-01-21T08:16:51.962766Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"EPOCHS = 30\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n    train_dataset,\n    validation_data=val_dataset,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=callbacks,\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:17:50.557318Z","iopub.execute_input":"2026-01-21T08:17:50.558037Z","iopub.status.idle":"2026-01-21T08:21:50.744433Z","shell.execute_reply.started":"2026-01-21T08:17:50.558009Z","shell.execute_reply":"2026-01-21T08:21:50.743501Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Создание submission","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(\n    ordered=True\n) \n\nprint(\"Computing predictions...\")\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(\"Generating submission.csv file...\")\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = (\n    next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype(\"U\")\n)  \nnp.savetxt(\n    \"submission.csv\",\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=[\"%s\", \"%d\"],\n    delimiter=\",\",\n    header=\"id,label\",\n    comments=\"\",\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-21T08:23:18.779723Z","iopub.execute_input":"2026-01-21T08:23:18.780037Z","iopub.status.idle":"2026-01-21T08:23:52.435952Z","shell.execute_reply.started":"2026-01-21T08:23:18.780013Z","shell.execute_reply":"2026-01-21T08:23:52.435397Z"}},"outputs":[],"execution_count":null}]}