{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.15","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"},{"sourceId":9776905,"sourceType":"datasetVersion","datasetId":5989255}],"dockerImageVersionId":30786,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import math, re, os\nimport tensorflow as tf\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow.keras.applications import EfficientNetB7\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\n\nprint(\"Tensorflow version \" + tf.__version__)\n\nAUTO = tf.data.experimental.AUTOTUNE\n\ntpu = tf.distribute.cluster_resolver.TPUClusterResolver()\ntf.config.experimental_connect_to_cluster(tpu)\ntf.tpu.experimental.initialize_tpu_system(tpu)\nstrategy = tf.distribute.experimental.TPUStrategy(tpu)\n\nprint(\"TPU initialized and strategy created: \", strategy)\n\nGCS_DS_PATH = '/kaggle/input/tpu-getting-started'\n\nIMAGE_SIZE = [512, 512]\nEPOCHS = 20\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nGCS_PATH_SELECT = {\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]]\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\nCLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle', # 00 - 09\n           'snapdragon', \"colt's foot\", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily', # 10 - 19\n           'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william', # 20 - 29\n           'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose', # 30 - 39\n           'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion', # 40 - 49\n           'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia', # 50 - 59\n           'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy', # 60 - 69\n           'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium', # 70 - 79\n           'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen', 'watercress', 'canna lily', # 80 - 89\n           'hippeastrum', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower', # 90 - 99\n           'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\ndef read_labeled_tfrecord(example):\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    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    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    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    return dataset\n\ndef data_augment(image, label, seed=2020):\n    image = tf.image.random_flip_left_right(image, 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(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\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    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\ndef display_samples(dataset, predictions=None, text_labels=None, rows=5, cols=4):\n    ds_iter = iter(dataset.unbatch().take(rows * cols))\n    plt.figure(figsize=(15, int(15 * rows / cols)))\n    for i in range(rows * cols):\n        plt.subplot(rows, cols, i+1)\n        image, label = ds_iter.get_next()\n        plt.imshow(image)\n        if predictions is None:\n            plt.title(CLASSES[label.numpy()])\n        else:\n            if text_labels is None:\n                title = CLASSES[label.numpy()]\n            else:\n                title = f\"{CLASSES[label.numpy()]}\\n{CLASSES[predictions[i]]}\"\n            plt.title(title)\n        plt.axis('off')\n    plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-01T10:31:31.672063Z","iopub.execute_input":"2024-11-01T10:31:31.672306Z","iopub.status.idle":"2024-11-01T10:32:13.542519Z","shell.execute_reply.started":"2024-11-01T10:31:31.672280Z","shell.execute_reply":"2024-11-01T10:32:13.541635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 加载训练和验证数据集\ntrain_dataset = get_training_dataset()\n\n# 显示前20张训练样本图像及其标签\ndisplay_samples(train_dataset, rows=10, cols=10)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-01T10:32:47.301679Z","iopub.execute_input":"2024-11-01T10:32:47.302080Z","iopub.status.idle":"2024-11-01T10:32:55.595433Z","shell.execute_reply.started":"2024-11-01T10:32:47.302049Z","shell.execute_reply":"2024-11-01T10:32:55.594265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ndef data_augment(image, label, seed=2020):\n    # 随机水平翻转图像\n    image = tf.image.random_flip_left_right(image, seed=seed)\n    # 返回增强后的图像和标签\n    return image, label\n\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()  # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)  # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)  # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\n\ndef get_train_valid_datasets():\n    dataset = load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat()  # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)  # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\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)  # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\n\ndef read_unlabeled_tfrecord(example):\n    # 定义无标签 TFRecord 文件的解析格式\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),  # tf.string 表示字节字符串\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] 表示单个元素\n        # class 标签缺失，这是该竞赛的挑战之一，需要为测试数据集预测花卉类别\n    }\n    # 解析单个 TFRecord 示例\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    # 解码图像数据\n    image = decode_image(example['image'])\n    # 获取图像的 ID\n    idnum = example['id']\n    # 返回图像和图像 ID\n    return image, idnum\n\n\ndef count_data_items(filenames):\n    # 文件名中包含数据项的数量，例如 flowers00-230.tfrec 表示包含 230 个数据项\n    # 使用正则表达式从文件名中提取数据项的数量\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    # 返回所有文件的数据项总数\n    return np.sum(n)\n\n\ndef lrfn(epoch):\n    # 定义学习率的起始值\n    LR_START = 0.00001\n    # 定义学习率的最大值，取决于同步的副本数量\n    LR_MAX = 0.00005 * strategy.num_replicas_in_sync\n    # 定义学习率的最小值\n    LR_MIN = 0.00001\n    # 定义学习率从起始值爬升到最大值所需的 epochs 数\n    LR_RAMPUP_EPOCHS = 5\n    # 定义学习率维持在最大值的 epochs 数\n    LR_SUSTAIN_EPOCHS = 0\n    # 定义学习率的指数衰减率\n    LR_EXP_DECAY = .8\n\n    # 根据 epoch 动态计算学习率\n    if epoch < LR_RAMPUP_EPOCHS:\n        # 从 LR_START 线性爬升到 LR_MAX\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        # 维持在 LR_MAX\n        lr = LR_MAX\n    else:\n        # 进行指数衰减，从 LR_MAX 衰减到 LR_MIN\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY ** (epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n\n    # 返回计算得到的学习率\n    return lr\n\n\ndef freeze(model):\n    for layer in model.layers:\n        layer.trainable = False\n\n\ndef unfreeze(model):\n    for layer in model.layers:\n        layer.trainable = True\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-01T10:36:46.210487Z","iopub.execute_input":"2024-11-01T10:36:46.211744Z","iopub.status.idle":"2024-11-01T10:36:46.225521Z","shell.execute_reply.started":"2024-11-01T10:36:46.211675Z","shell.execute_reply":"2024-11-01T10:36:46.224517Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 计算训练数据集中的图像数量\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\n# 计算验证数据集中的图像数量\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\n# 计算测试数据集中的图像数量\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\n\n# 计算每个 epoch 的步数，即总共需要多少个批次\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\n# 输出数据集的统计信息\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES,\n                                                                                           NUM_VALIDATION_IMAGES,\n                                                                                           NUM_TEST_IMAGES))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-01T10:37:47.659615Z","iopub.execute_input":"2024-11-01T10:37:47.659975Z","iopub.status.idle":"2024-11-01T10:37:47.665419Z","shell.execute_reply.started":"2024-11-01T10:37:47.659945Z","shell.execute_reply":"2024-11-01T10:37:47.664753Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 继续模型定义和编译\nwith strategy.scope():\n    local_weights_path = '/kaggle/input/pre-train-efficient/efficientnetb7_notop.h5'\n    enet = EfficientNetB7(input_shape=(512, 512, 3), weights=local_weights_path, include_top=False)\n    \n    model = tf.keras.Sequential([\n        enet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    \n    model.compile(optimizer=tf.keras.optimizers.Adam(),\n                  loss='sparse_categorical_crossentropy',\n                  metrics=['sparse_categorical_accuracy'])\n    \n    model.summary()\n    \n    lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\n    \n    history = model.fit(get_train_valid_datasets(), \n                        steps_per_epoch=STEPS_PER_EPOCH, \n                        epochs=EPOCHS, \n                        callbacks=[lr_schedule])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-01T10:37:51.955919Z","iopub.execute_input":"2024-11-01T10:37:51.956750Z","iopub.status.idle":"2024-11-01T11:26:59.481587Z","shell.execute_reply.started":"2024-11-01T10:37:51.956684Z","shell.execute_reply":"2024-11-01T11:26:59.480317Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 获取测试数据集\ntest_ds = get_test_dataset(ordered=True)\ntest_images_ds = test_ds.map(lambda image, idnum: image)\n\n# 进行预测\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\n\n# 显示前20张测试图像及其预测结果\ndisplay_samples(test_ds, predictions, rows=4, cols=5)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-01T11:30:45.933983Z","iopub.execute_input":"2024-11-01T11:30:45.934406Z","iopub.status.idle":"2024-11-01T11:32:12.696848Z","shell.execute_reply.started":"2024-11-01T11:30:45.934374Z","shell.execute_reply":"2024-11-01T11:32:12.695291Z"}},"outputs":[],"execution_count":null}]}