{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"\n# Introduction #\n\nWelcome to the [**Petals to the Metal**](https://www.kaggle.com/c/tpu-getting-started) competition! 在这场比赛中，你的挑战是建立一个机器学习模型，根据它们的图像对104种花进行分类。\n在本教程笔记本中，您将学习如何在Keras中构建一个图像分类器，并在张量处理单元(TPU)上训练它。最后，你会有一个完整的项目，你可以建立自己的想法。\n</blockquote>","metadata":{}},{"cell_type":"markdown","source":"# Step 1: Imports #\n\nWe begin by importing several Python packages.","metadata":{}},{"cell_type":"code","source":"import math, re, os\nimport numpy as np\nimport tensorflow as tf\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:56:58.396099Z","iopub.execute_input":"2023-04-17T02:56:58.397359Z","iopub.status.idle":"2023-04-17T02:57:06.963391Z","shell.execute_reply.started":"2023-04-17T02:56:58.397313Z","shell.execute_reply":"2023-04-17T02:57:06.962034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 2: Distribution Strategy #\n\n一个TPU有八个不同的核心，每个核心都充当自己的加速器。(一个TPU有点像在一台机器上有八个gpu。)我们告诉TensorFlow如何通过分发策略一次性使用所有这些核心。运行下面的单元格来创建稍后将应用于模型的分布策略。","metadata":{}},{"cell_type":"code","source":"# 检测TPU，返回适当的分配策略\ntry:\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() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:06.965719Z","iopub.execute_input":"2023-04-17T02:57:06.966635Z","iopub.status.idle":"2023-04-17T02:57:12.040039Z","shell.execute_reply.started":"2023-04-17T02:57:06.966592Z","shell.execute_reply":"2023-04-17T02:57:12.038845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"我们将在创建神经网络模型时使用分布策略。然后，TensorFlow将通过创建八个不同的模型副本(每个核心一个)，在八个TPU核心之间分配训练。\n\n# Step 3: 比赛数据加载 #\n\n## Get GCS Path ##\n\n与tpu配合使用时，需要将数据集存储在谷歌云存储桶中。你可以像使用'/kaggle/input'中的数据一样，通过给出它的路径来使用任何公共GCS桶中的数据。下面将检索本次竞赛数据集的GCS路径。","metadata":{}},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(GCS_DS_PATH) # what do gcs paths look like?","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:12.041655Z","iopub.execute_input":"2023-04-17T02:57:12.042096Z","iopub.status.idle":"2023-04-17T02:57:12.414341Z","shell.execute_reply.started":"2023-04-17T02:57:12.042053Z","shell.execute_reply":"2023-04-17T02:57:12.412929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"您可以以同样的方式使用Kaggle上任何公共数据集的数据。如果您想使用来自您的私有数据集之一的数据，请参阅这里。 [here](https://www.kaggle.com/docs/tpu#tpu3pt5).\n\n## Load Data ##\n\n当与tpu一起使用时，数据集通常被序列化到TFRecords中。这是一种便于将数据分发到每个tpu核心的格式。我们隐藏了为数据集读取TFRecords的单元格，因为这个过程有点长。稍后，您可以在tpu中使用自己的数据集，以获得一些指导。","metadata":{}},{"cell_type":"code","source":"\nIMAGE_SIZE = [512, 512]\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'\nAUTO = tf.data.experimental.AUTOTUNE\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\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']                                                                                                                                               # 100 - 102\n\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  # 将图像转换为[0,1]范围内的浮动\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # TPU所需的显式大小\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\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 means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\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 # 返回一个图像数据集\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # 阅读TFRecords。为了获得最佳性能，可以一次从多个文件中读取，并且忽略数据顺序。\n    # 顺序并不重要，因为我们无论如何都会打乱数据。\n\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    # 返回(image, label)对的数据集(如果tagged =True)或(image, id)对的数据集(如果tagged =False)\n    return dataset","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-04-17T02:57:12.417440Z","iopub.execute_input":"2023-04-17T02:57:12.417798Z","iopub.status.idle":"2023-04-17T02:57:12.586367Z","shell.execute_reply.started":"2023-04-17T02:57:12.417761Z","shell.execute_reply":"2023-04-17T02:57:12.585066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 创建数据管道 ##\n\n在最后一步中，我们将使用`tf.data`的API，为每个训练、验证和测试片段定义一个有效的数据管道。","metadata":{}},{"cell_type":"code","source":"\ndef data_augment(image, label):\n    # 多亏了下面函数中的dataset.prefetch(AUTO)语句，这在TPU上基本上是免费的。\n    # 数据管道代码在TPU的“CPU”部分执行，而TPU本身则在计算梯度。\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\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    # 数据项的个数写在\".tfrec\"文件的名称中，即“flowers00-230”。Tfrec = 230个数据项\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\n","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-04-17T02:57:12.587928Z","iopub.execute_input":"2023-04-17T02:57:12.588286Z","iopub.status.idle":"2023-04-17T02:57:12.602180Z","shell.execute_reply.started":"2023-04-17T02:57:12.588252Z","shell.execute_reply":"2023-04-17T02:57:12.600798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"下一个单元格将创建数据集，我们将在训练和推断期间使用Keras。注意我们如何将批的大小缩放到TPU核的数量。","metadata":{}},{"cell_type":"code","source":"# 定义批处理大小。TPU关闭时为16,TPU打开时为128 (=16*8)\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nds_train = get_training_dataset()\nds_valid = get_validation_dataset()\nds_test = get_test_dataset()\n\nprint(\"Training:\", ds_train)\nprint (\"Validation:\", ds_valid)\nprint(\"Test:\", ds_test)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:12.603920Z","iopub.execute_input":"2023-04-17T02:57:12.604373Z","iopub.status.idle":"2023-04-17T02:57:12.938801Z","shell.execute_reply.started":"2023-04-17T02:57:12.604302Z","shell.execute_reply":"2023-04-17T02:57:12.937882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"这些数据集是tf.data.Dataset对象。你可以把TensorFlow中的数据集看作数据记录流。训练集和验证集是(图像，标签)对的流。","metadata":{}},{"cell_type":"code","source":"np.set_printoptions(threshold=15, linewidth=80)\n\nprint(\"Training data shapes:\")\nfor image, label in ds_train.take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:12.940220Z","iopub.execute_input":"2023-04-17T02:57:12.940565Z","iopub.status.idle":"2023-04-17T02:57:17.786357Z","shell.execute_reply.started":"2023-04-17T02:57:12.940532Z","shell.execute_reply":"2023-04-17T02:57:17.784992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"测试集是(image, idnum)对的流;这里的Idnum是给图像的唯一标识符，我们稍后将使用它作为CSV文件提交。","metadata":{}},{"cell_type":"code","source":"print(\"Test data shapes:\")\nfor image, idnum in ds_test.take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:17.789115Z","iopub.execute_input":"2023-04-17T02:57:17.789562Z","iopub.status.idle":"2023-04-17T02:57:21.187665Z","shell.execute_reply.started":"2023-04-17T02:57:17.789514Z","shell.execute_reply":"2023-04-17T02:57:21.184901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 4: Explore Data #\n\n让我们花点时间看看数据集中的一些图像。","metadata":{}},{"cell_type":"code","source":"\nfrom matplotlib import pyplot as plt\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: # 二进制字符串，在这里，这些是图像ID字符串\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # 如果没有标签，只有图像id，标签返回None(测试数据就是这样)\n    return numpy_images, numpy_labels\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 \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\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(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\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    # 自动平方:这将删除不适合正方形或近似正方形的矩形的数据\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(zip(images[:rows*cols], labels[:rows*cols])):\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 = FIGSIZE*SPACING/max(rows,cols)*40+3 # 魔术公式测试工作从1x1到10x10图像\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\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\ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\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_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-04-17T02:57:21.189613Z","iopub.execute_input":"2023-04-17T02:57:21.190123Z","iopub.status.idle":"2023-04-17T02:57:21.211286Z","shell.execute_reply.started":"2023-04-17T02:57:21.190071Z","shell.execute_reply":"2023-04-17T02:57:21.209882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"您可以使用我们的另一个辅助函数显示数据集中的一批图像。下一个单元格将把数据集转换为20个图像批次的迭代器。","metadata":{}},{"cell_type":"code","source":"ds_iter = iter(ds_train.unbatch().batch(20))","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:21.215316Z","iopub.execute_input":"2023-04-17T02:57:21.215676Z","iopub.status.idle":"2023-04-17T02:57:21.237783Z","shell.execute_reply.started":"2023-04-17T02:57:21.215643Z","shell.execute_reply":"2023-04-17T02:57:21.236392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"使用Python ' next '函数弹出流中的下一个批处理，并使用helper函数显示它。","metadata":{}},{"cell_type":"code","source":"one_batch = next(ds_iter)\ndisplay_batch_of_images(one_batch)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:21.239955Z","iopub.execute_input":"2023-04-17T02:57:21.240874Z","iopub.status.idle":"2023-04-17T02:57:24.708450Z","shell.execute_reply.started":"2023-04-17T02:57:21.240802Z","shell.execute_reply":"2023-04-17T02:57:24.704283Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"通过在单独的单元格中定义“ds_iter”和“one_batch”，您只需要重新运行上面的单元格就可以看到一批新的图像。","metadata":{}},{"cell_type":"markdown","source":"# Step 5: 创建模型 #\n\n现在我们准备创建一个用于分类图像的神经网络!我们将使用所谓的迁移学习。通过迁移学习，您可以重用预训练模型的一部分，从而在新数据集上获得领先优势。\n\n在本教程中，我们将使用在ImageNet上预训练的VGG16模型)。稍后，您可能想尝试Keras包含的其他模型。(例外是个不错的选择。)\n\n我们在前面创建的分发策略包含一个上下文管理器strategy.scope。这个上下文管理器告诉TensorFlow如何在八个TPU核心之间分配训练工作。在TPU中使用TensorFlow时，在strategy.scope()上下文中定义你的模型是很重要的。","metadata":{}},{"cell_type":"code","source":"EPOCHS = 12\n\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.VGG16(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = False\n    \n    model = tf.keras.Sequential([\n        # 到在ImageNet上预训练的基础上从图像中提取特征…\n        pretrained_model,\n        # …附加一个新的头部作为分类器。\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:24.710732Z","iopub.execute_input":"2023-04-17T02:57:24.711244Z","iopub.status.idle":"2023-04-17T02:57:33.115860Z","shell.execute_reply.started":"2023-04-17T02:57:24.711195Z","shell.execute_reply":"2023-04-17T02:57:33.114337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"损失和度量的“sparse_categorical”版本适用于具有两个以上标签的分类任务，比如下面这个。","metadata":{}},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:33.118077Z","iopub.execute_input":"2023-04-17T02:57:33.118498Z","iopub.status.idle":"2023-04-17T02:57:33.193605Z","shell.execute_reply.started":"2023-04-17T02:57:33.118456Z","shell.execute_reply":"2023-04-17T02:57:33.191209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 6: Training #\n\n## 学习率表 ##\n\n我们会用一个特殊的学习率计划来训练这个网络。","metadata":{}},{"cell_type":"code","source":"\n# 微调学习率表 #\ndef exponential_lr(epoch,\n                   start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005,\n                   rampup_epochs = 5, 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        # 线性增长从开始到rampup_epochs\n        if epoch < rampup_epochs:\n            lr = ((max_lr - start_lr) /\n                  rampup_epochs * epoch + start_lr)\n        # 在sustain_epoch期间常量max_lr\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr\n        # 指数衰减到min_lr\n        else:\n            lr = ((max_lr - min_lr) *\n                  exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                  min_lr)\n        return lr\n    return lr(epoch,\n              start_lr,\n              min_lr,\n              max_lr,\n              rampup_epochs,\n              sustain_epochs,\n              exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)\n\nrng = [i for i in range(EPOCHS)]\ny = [exponential_lr(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-04-17T02:57:33.195051Z","iopub.execute_input":"2023-04-17T02:57:33.195374Z","iopub.status.idle":"2023-04-17T02:57:33.448732Z","shell.execute_reply.started":"2023-04-17T02:57:33.195341Z","shell.execute_reply":"2023-04-17T02:57:33.447217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fit Model ##\n\n现在我们准备训练模型了。在定义了几个参数之后，我们就可以开始了!","metadata":{}},{"cell_type":"code","source":"# 定义定义时间\nEPOCHS = 12\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n    ds_train,\n    validation_data=ds_valid,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_callback],\n)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T02:57:33.451939Z","iopub.execute_input":"2023-04-17T02:57:33.452312Z","iopub.status.idle":"2023-04-17T03:02:55.729676Z","shell.execute_reply.started":"2023-04-17T02:57:33.452278Z","shell.execute_reply":"2023-04-17T03:02:55.728318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"下一个单元格显示了损失和指标在训练期间的进展情况。谢天谢地，它收敛了!","metadata":{}},{"cell_type":"code","source":"display_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T03:02:55.732326Z","iopub.execute_input":"2023-04-17T03:02:55.732943Z","iopub.status.idle":"2023-04-17T03:02:56.275606Z","shell.execute_reply.started":"2023-04-17T03:02:55.732892Z","shell.execute_reply":"2023-04-17T03:02:56.274209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 7: 评估预测 #\n\n在对测试集进行最终预测之前，在验证集中评估模型的预测是一个好主意。这可以帮助您诊断训练中的问题，或者建议您的模型可以改进的方法。我们将讨论两种常见的验证方法:绘制**混淆矩阵**和**视觉验证**。","metadata":{}},{"cell_type":"code","source":"\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\n\ndef display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(15,15))\n    ax = plt.gca()\n    ax.matshow(cmat, cmap='Reds')\n    ax.set_xticks(range(len(CLASSES)))\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(CLASSES)))\n    ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n    titlestring = \"\"\n    if score is not None:\n        titlestring += 'f1 = {:.3f} '.format(score)\n    if precision is not None:\n        titlestring += '\\nprecision = {:.3f} '.format(precision)\n    if recall is not None:\n        titlestring += '\\nrecall = {:.3f} '.format(recall)\n    if len(titlestring) > 0:\n        ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'})\n    plt.show()\n    \ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\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_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-04-17T03:02:56.277677Z","iopub.execute_input":"2023-04-17T03:02:56.278080Z","iopub.status.idle":"2023-04-17T03:02:56.836410Z","shell.execute_reply.started":"2023-04-17T03:02:56.278042Z","shell.execute_reply":"2023-04-17T03:02:56.835354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 混淆矩阵 ##\n\n混淆矩阵显示了图像的实际类别与其预测类别相比较。它是用于评估分类器性能的最佳工具之一。\n\n下面的单元格对验证数据进行一些处理，然后使用scikit-learn中包含的confusi_matrix函数创建矩阵。","metadata":{}},{"cell_type":"code","source":"cmdataset = get_validation_dataset(ordered=True)\nimages_ds = cmdataset.map(lambda image, label: image)\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch()\n\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy()\ncm_probabilities = model.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\nlabels = range(len(CLASSES))\ncmat = confusion_matrix(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n)\ncmat = (cmat.T / cmat.sum(axis=1)).T # normalize","metadata":{"execution":{"iopub.status.busy":"2023-04-17T03:02:56.838311Z","iopub.execute_input":"2023-04-17T03:02:56.838750Z","iopub.status.idle":"2023-04-17T03:03:09.690308Z","shell.execute_reply.started":"2023-04-17T03:02:56.838703Z","shell.execute_reply":"2023-04-17T03:03:09.688873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"你可能对f1分数或精确度和召回率等指标很熟悉。该单元格将计算这些指标，并将其与混淆矩阵的图形一起显示。(这些指标在Scikit-learn模块sklearn.metrics中定义;我们已经在帮助脚本中为您导入了它们。)","metadata":{}},{"cell_type":"code","source":"score = f1_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nprecision = precision_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nrecall = recall_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\ndisplay_confusion_matrix(cmat, score, precision, recall)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T03:03:09.692137Z","iopub.execute_input":"2023-04-17T03:03:09.693090Z","iopub.status.idle":"2023-04-17T03:03:14.473364Z","shell.execute_reply.started":"2023-04-17T03:03:09.693046Z","shell.execute_reply":"2023-04-17T03:03:14.472138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 视觉验证 ##\n\n查看验证集中的一些示例并查看您的模型预测的类也会有所帮助。这可以帮助揭示你的模型有问题的图像类型的模式。\n\n这个单元格将设置验证集，一次显示20张图像——如果您愿意，可以将其更改为显示更多或更少的图像。","metadata":{}},{"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T03:03:14.475051Z","iopub.execute_input":"2023-04-17T03:03:14.475923Z","iopub.status.idle":"2023-04-17T03:03:14.522484Z","shell.execute_reply.started":"2023-04-17T03:03:14.475883Z","shell.execute_reply":"2023-04-17T03:03:14.521126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"这是一组花和它们预测的种类。再次运行单元格以查看另一组。","metadata":{}},{"cell_type":"code","source":"images, labels = next(batch)\nprobabilities = model.predict(images)\npredictions = np.argmax(probabilities, axis=-1)\ndisplay_batch_of_images((images, labels), predictions)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T03:03:14.523961Z","iopub.execute_input":"2023-04-17T03:03:14.524405Z","iopub.status.idle":"2023-04-17T03:03:23.493246Z","shell.execute_reply.started":"2023-04-17T03:03:14.524354Z","shell.execute_reply":"2023-04-17T03:03:23.491881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 8: Make Test Predictions #\n\n一旦你对所有内容都感到满意，你就可以对测试集进行预测了。","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\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)","metadata":{"execution":{"iopub.status.busy":"2023-04-17T03:03:23.494730Z","iopub.execute_input":"2023-04-17T03:03:23.495111Z","iopub.status.idle":"2023-04-17T03:03:41.258690Z","shell.execute_reply.started":"2023-04-17T03:03:23.495076Z","shell.execute_reply":"2023-04-17T03:03:41.257575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"我们将生成一个文件submission.csv。你要提交这个文件才能在排行榜上获得分数。","metadata":{}},{"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\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')\n\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)\n\n# 看看前几个预测\n!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2023-04-17T03:03:41.260473Z","iopub.execute_input":"2023-04-17T03:03:41.261257Z","iopub.status.idle":"2023-04-17T03:03:44.346187Z","shell.execute_reply.started":"2023-04-17T03:03:41.261207Z","shell.execute_reply":"2023-04-17T03:03:44.344195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 9: Make a submission #\n\nIf you haven't already, create your own editable copy of this notebook by clicking on the **Copy and Edit** button in the top right corner. Then, submit to the competition by following these steps:\n\n1. Begin by clicking on the blue **Save Version** button in the top right corner of the window.  This will generate a pop-up window.  \n2. Ensure that the **Save and Run All** option is selected, and then click on the blue **Save** button.\n3. This generates a window in the bottom left corner of the notebook.  After it has finished running, click on the number to the right of the **Save Version** button.  This pulls up a list of versions on the right of the screen.  Click on the ellipsis **(...)** to the right of the most recent version, and select **Open in Viewer**.  This brings you into view mode of the same page. You will need to scroll down to get back to these instructions.\n4. Click on the **Output** tab on the right of the screen.  Then, click on the file you would like to submit, and click on the blue **Submit** button to submit your results to the leaderboard.\n\nYou have now successfully submitted to the competition!\n\nIf you want to keep working to improve your performance, select the blue **Edit** button in the top right of the screen. Then you can change your code and repeat the process. There's a lot of room to improve, and you will climb up the leaderboard as you work.\n","metadata":{}},{"cell_type":"markdown","source":"---\n\n\n\n\n*Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum/161321) to chat with other Learners.*","metadata":{}}]}