{"cells":[{"metadata":{"_uuid":"ff369766-42df-4776-820d-4dad1e373cfc","_cell_guid":"53cbe44d-f020-4f1e-8ed5-7f1123f3d986","trusted":true},"cell_type":"markdown","source":"# 版本更新情况\n以下准确率全都是验证准确率，和比赛提交以后的准确率有一定区别，因为算法不一样\n* V1：官方给出的代码，用了VGG模型，准确率40%\n* V2-V8：不断增删层，并调超参数，更换损失函数与优化器 准确率增长到60%就遇到瓶颈了\n* V9：尝试通过仅在5分钟内训练softmax层来预热，然后再释放所有重量。准确率下降到50%\n* V10：更多数据扩充 准确率55%\n* V11：使用LR Scheduler 准确率62%\n* V12：同时使用训练和验证数据来训练模型。 准确率68%\n* V13；使用谷歌开源新模型 EfficientNetB7 准确率91%，害怕\n* V14：训练更长的时间（25个轮次）。准确率82%，下降了，是因为过拟合吧\n* V15：回到20个轮次； Global Max Pooling instead of Average。（全局最大池而不是平均。） 准确率67%，不适合\n* V16：回滚到global average pooling （全局平均池） 准确率81%\n* V18：回滚到V13，并调节部分参数 准确率99.9%，恐怖如斯，我好无敌"},{"metadata":{"_uuid":"ec35c771-49ac-48f5-88b8-f72739913851","_cell_guid":"273bdbd8-6fd8-4329-a338-ade00b4f83d0","trusted":true},"cell_type":"markdown","source":"# 1. 安装efficientnet"},{"metadata":{"_uuid":"30808689-34e4-4b23-960a-906d7ccfbd44","_cell_guid":"15e3c406-0efe-4e72-97ab-c68e1e117c32","trusted":true},"cell_type":"code","source":"!pip install -q efficientnet #因为我们想用 EfficientNet模型，所以我们先进行安装efficientnet，\n# 感叹号表示调用控制台，这句代码等价于于在控制台输入了pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c718445f-7e48-45d8-88a4-4e6ddde26c2a","_cell_guid":"082feeac-cfbd-4e29-85aa-9f4ee06bbba6","trusted":true},"cell_type":"markdown","source":"# 2. 导入需要的包"},{"metadata":{"_uuid":"3fcc57c4-ee0b-4cb2-aaa6-cd3f646ed572","_cell_guid":"01cc3c09-c2d6-44b8-9059-d59f34727dda","trusted":true},"cell_type":"code","source":"# 导入需要的包\nimport math, re, os # math：包括一些通用的数学公式；re：字符串正则匹配；os：操作系统接口\nimport tensorflow as tf # tensorflow包\nimport numpy as np # numpy操作数组\nfrom matplotlib import pyplot as plt   # matplotlib进行画图\nfrom kaggle_datasets import KaggleDatasets # Kaggle数据集\nimport efficientnet.tfkeras as efn    # 导入efficientnet模型\n# 从python的sklearn机器学习中导入f1值、精度、召回率和混淆矩阵\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix  \n\nprint(\"Tensorflow version \" + tf.__version__) #检查tensorflow的版本","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"53549e5c-8926-4aab-a937-eee2da832377","_cell_guid":"c8261476-8ec1-4352-a2a9-92ddb9be3359","trusted":true},"cell_type":"markdown","source":"# 3. 检测TPU和GPU\n我这里注释掉的原因是我们已经知道TPU和GPU存在，而且我们打算完全用TPU而不用GPU"},{"metadata":{"_uuid":"fb76fffb-c79a-4e9d-9fec-029a7144aa05","_cell_guid":"fb2de923-c175-4047-83da-d95cfb388aa0","trusted":true},"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\n# try:\n      # TPU检测。 如果设置了TPU_NAME环境变量，则不需要任何参数。 在Kaggle上，情况总是如此。\n#     tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  \n#     print('Running on TPU ', tpu.master())\n# except ValueError:\n#     tpu = None\n\n# if tpu:\n#     tf.config.experimental_connect_to_cluster(tpu)\n#     tf.tpu.experimental.initialize_tpu_system(tpu)\n#     strategy = tf.distribute.experimental.TPUStrategy(tpu)\n# else:\n#     strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\n# print(\"REPLICAS: \", strategy.num_replicas_in_sync) #输出副本数","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b7563c6d-e898-4e4b-80a0-a304024b4dfa","_cell_guid":"bf367e94-625b-4d38-a6c3-6854e771ae72","trusted":true},"cell_type":"markdown","source":"# 4. 配置TPU、访问路径等"},{"metadata":{"_uuid":"26b1f1dd-de81-45eb-b810-9ce166cc692b","_cell_guid":"e2608472-b2a0-4a89-9a11-2d6aac4b0a64","trusted":true},"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE # 可以让程序自动的选择最优的线程并行个数\n\n# Create strategy from tpu\n# 从TPU创建部署\ntpu = tf.distribute.cluster_resolver.TPUClusterResolver() #如果先前设置好了ＴＰＵ＿ＮＡＭＥ环境变量，不需要再给参数．\ntf.config.experimental_connect_to_cluster(tpu) # 配置实验连接到群集\ntf.tpu.experimental.initialize_tpu_system(tpu) # 初始化tpu系统\nstrategy = tf.distribute.experimental.TPUStrategy(tpu) # 设置TPU部署\n\n\n# 官方给出的竞赛数据访问注释\n# Competition data access\n# TPUs read data directly from Google Cloud Storage (GCS). \n# This Kaggle utility will copy the dataset to a GCS bucket co-located with the TPU. \n# If you have multiple datasets attached to the notebook, \n# you can pass the name of a specific dataset to the get_gcs_path function. \n# The name of the dataset is the name of the directory it is mounted in. \n# Use !ls /kaggle/input/ to list attached datasets.\n# 比赛数据访问\n# TPU直接从Google Cloud Storage（GCS）读取数据。\n# 该Kaggle实用程序会将数据集复制到与TPU并置的GCS存储桶中。\n# 如果笔记本有多个数据集，\n# 您可以将特定数据集的名称传递给get_gcs_path函数。\n# 数据集的名称是其安装目录的名称。\n# 使用！ls / kaggle / input /列出附加的数据集。\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path() #设置Kaggle数据的访问路径\n\n# Configuration\n\nIMAGE_SIZE = [512, 512] # 配置像素点矩阵大小\nEPOCHS = 20 # # 配置模型训练的轮次\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync # 设置每个小批量的大小","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d994d42d-894e-4d08-892b-146017594a34","_cell_guid":"f22bc596-bd51-4dc3-9850-4a944966a80e","trusted":true},"cell_type":"code","source":"# 配置不同大小图片的路径\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\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') # 测试集路径 predictions on this dataset should be submitted for the competition","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0175acd4-0c2c-4e5d-8e93-2876d4ea7477","_cell_guid":"a1f60004-5726-44c2-a401-0799a27f7949","trusted":true},"cell_type":"code","source":"# 104种花的名称\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']","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3962bd45-6cb8-4437-b3cc-4685fc3c50a2","_cell_guid":"9c8fd0ee-c054-44bb-8383-6585bb9152a1","trusted":true},"cell_type":"markdown","source":"# 5. 各种函数"},{"metadata":{"_uuid":"4621c628-4f3a-4fb6-996c-618ba53e6224","_cell_guid":"44484d48-0f93-4ef9-a8aa-3189784154fe","trusted":true},"cell_type":"markdown","source":"## 5.1. 可视化函数"},{"metadata":{"_uuid":"ae36da06-3803-4be1-b1a6-426d5e7fcd89","_cell_guid":"95306bb2-de38-437b-95c0-b4561942801e","trusted":true},"cell_type":"code","source":"# 展示训练和验证曲线，也就是损失和准确率随轮次的变化\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) #设置y轴标题\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch') #设置x轴标题\n    ax.legend(['train', 'valid.']) #设置图例\n    \n# 绘制混淆矩阵\ndef display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(15,15))  # 设置画布大小\n    ax = plt.gca() #返回当前axes(matplotlib.axes.Axes) 获取当前子图\n    ax.matshow(cmat, cmap='Reds') #绘制矩阵\n    ax.set_xticks(range(len(CLASSES)))  #根据花朵类别数（其实就是104）设置x轴范围\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7}) #设置x轴下标字体的大小\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\") #更换x轴下标角度\n    ax.set_yticks(range(len(CLASSES)))  #根据花朵类别数（其实就是104）设置y轴范围\n    ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7}) #设置y轴下标字体的大小\n    plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\") #更换y轴下标角度\n    titlestring = \"\"\n    if score is not None:\n        titlestring += 'f1 = {:.3f} '.format(score) #更改格式为有3位小数的浮点数\n    if precision is not None:\n        titlestring += '\\nprecision = {:.3f} '.format(precision) #更改格式为有3位小数的浮点数\n    if recall is not None:\n        titlestring += '\\nrecall = {:.3f} '.format(recall) #更改格式为有3位小数的浮点数\n    if len(titlestring) > 0:\n        ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'}) #添加文本注释\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1b3fac31-f166-4851-aa85-d86b902907bc","_cell_guid":"65b904e2-87ea-4def-a748-768442092f81","trusted":true},"cell_type":"code","source":"# 设置numpy数组基本属性，设置显示15个数字，用于插入换行符的每行字符数（默认为75）。\n# threshold : int, optional，Total number of array elements which trigger summarization rather than full repr (default 1000).\n# 当数组数目过大时，设置显示几个数字，其余用省略号\n# linewidth : int, optional，The number of characters per line for the purpose of inserting line breaks (default 75).\n# 用于插入换行符的每行字符数（默认为75）。\nnp.set_printoptions(threshold=15, linewidth=80)\n\n# 将小批量图片和标签处理为numpy向量格式\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data \n    numpy_images = images.numpy() #将图像转换为numpy向量格式\n    numpy_labels = labels.numpy() #将label标签转换为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\n# 把实际类型和模型预测出来的模型一起显示在图片上方，这是用给验证集的，当对验证集预测完标签后和验证集的实际标签进行比较\n# label,图片中花朵的实际类别\n# correct_label，当前我们预测的类别\ndef title_from_label_and_target(label, correct_label):\n    # 如果没有预测的类别，则返回实际类别，比如训练集\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label) #判断一下实际类别和我们预测的类别是否一致\n    # 如果一致，则返回OK，不一致则返回NO加实际类别\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\n# 绘制一朵花\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off') # 不显示坐标尺寸\n    plt.imshow(image) #函数负责对图像进行处理，并显示其格式；而plt.show()则是将plt.imshow()处理后的函数显示出来。\n    if len(title) > 0:\n        #绘制图片的标题\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', \n                  fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \n# 展示小批量图片，我们在下面的代码中经常展示20张照片\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    # 读取图片和实际标签数据，而且这些数据被转换成numpy向量的格式\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    # 如果没有实际标签（即if labels is None为true），比如测试集，那么我们需要将labels变量设为每个元素都为none\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    # 大小和间距\n    FIGSIZE = 13.0  #画图大小\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        # 如果行大于列\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()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"775bb8f1-2f1e-479e-b4e3-2b02332410fb","_cell_guid":"eb2afddb-fad6-434f-88a1-339b16c09463","trusted":true},"cell_type":"markdown","source":"## 5.2. 数据集函数"},{"metadata":{"_uuid":"96027da9-3a91-49cc-b530-bcc72b7014e9","_cell_guid":"e8c7f1c6-6fec-4fca-922b-a8afc569b62f","trusted":true},"cell_type":"code","source":"# 准备图像数据\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3) # 将图片解码\n    # 之前训练图像保存在一个 uint8 类型的数组中，取值区间为 [0, 255]。我们需要将其变换为一个 float32 数组，其形取值范围为 0~1。\n    # 将图片转换为[0，1]范围内的浮点数\n    image = tf.cast(image, tf.float32) / 255.0  \n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # TPU所需的精确的大小\n    return image\n\n# 读取带有标签的TFRecord 格式文件\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 # returns a dataset of (image, label) pairs\n\n# 读取没有标签的TFRecord 格式文件\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        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\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\n# 加载数据集\n# 这三个参数分别为：文件路径、是否有标签、是否按顺序（就是要不要把数据顺序打乱）\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # 从TFRecords读取。 为了获得最佳性能，请一次从多个文件中读取数据，而不考虑数据顺序。 顺序无关紧要，因为无论如何我们都会对数据进行混洗。\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    # 如果标记为True则返回（图像，label）对的数据集，如果标记为False，则返回（图像，id）对的数据集\n    return dataset\n\n# 按水平 (从左向右) 随机翻转图像.返回图片的参数image和label\ndef data_augment(image, label, seed=2020):\n    # TensorFlow函数：tf.image.random_flip_left_right\n    # 按水平 (从左向右) 随机翻转图像.\n    # 以1比2的概率,输出image沿着第二维翻转的内容,即,width.否则按原样输出图像.\n    # 参数：\n    # image：形状为[height, width, channels]的三维张量.\n    # seed：一个Python整数,用于创建一个随机种子.查看tf.set_random_seed行为.\n    # 返回：一个与image具有相同类型和形状的三维张量.\n    image = tf.image.random_flip_left_right(image, seed=seed)\n    \n#     image = tf.image.random_flip_up_down(image, seed=seed)\n#     image = tf.image.random_brightness(image, 0.1, seed=seed)\n#     image = tf.image.random_jpeg_quality(image, 85, 100, seed=seed)\n#     image = tf.image.resize(image, [530, 530])\n#     image = tf.image.random_crop(image, [512, 512], seed=seed)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \n\n# 获取训练集\ndef get_training_dataset():\n    # 加载训练集，第一个参数为训练集路径，第二个参数表示有标签\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    # 将数据转换并行化\n    # 为num_parallel_calls 参数选择最佳值取决于您的硬件、训练数据的特征（例如其大小和形状）、Map 功能的成本以及在 CPU 上同时进行的其他处理；\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    # 重复此数据集count次数\n    # 函数形式：repeat(count=None)\n    # 参数count:(可选）表示数据集应重复的次数。默认行为（如果count是None或-1）是无限期重复的数据集。\n    dataset = dataset.repeat() # 数据集必须重复几个轮次\n    dataset = dataset.shuffle(2048) #将数据打乱，括号中数值越大，混乱程度越大\n    dataset = dataset.batch(BATCH_SIZE) # 按照顺序将小批量中样本数目行数据合成一个小批量，最后一个小批量可能小于20\n    # pipeline（管道）读取数据，在训练时预取下一批（自动调整预取缓冲区大小）\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\n# 获取验证集\ndef get_validation_dataset(ordered=False):\n    # 加载训练集，第一个参数为验证集路径，第二个参数表示有标签，第三个参数为不按照顺序\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE) ## 按照顺序将小批量中样本数目行数据合成一个小批量，最后一个小批量可能小于20\n    dataset = dataset.cache() # 使用.cache()方法：当计算缓存空间足够时，将preprocess的数据存储在缓存空间中将大幅提高计算速度。\n    # pipeline（管道）读取数据，在训练时预取下一批（自动调整预取缓冲区大小）\n    dataset = dataset.prefetch(AUTO)  \n    return dataset\n\n# 将训练集和验证集合并\ndef get_train_valid_datasets():\n    dataset = load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES, labeled=True)\n       # 将数据转换并行化\n    # 加载训练集，第一个参数为训练集路径，第二个参数表示有标签\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    # 重复此数据集count次数\n    # 函数形式：repeat(count=None)\n    # 参数count:(可选）表示数据集应重复的次数。默认行为（如果count是None或-1）是无限期重复的数据集。\n    dataset = dataset.repeat() # 数据集必须重复几个轮次\n    dataset = dataset.shuffle(2048) # 将数据打乱，括号中数值越大，混乱程度越大\n    dataset = dataset.batch(BATCH_SIZE)\n    # pipeline（管道）读取数据，在训练时预取下一批（自动调整预取缓冲区大小）\n    dataset = dataset.prefetch(AUTO)\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    # pipeline（管道）读取数据，在训练时预取下一批（自动调整预取缓冲区大小）\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\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)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"38c4dac6-fc72-4325-94bb-880516d99b84","_cell_guid":"0e0540fe-84ea-42ae-871e-8a3c6fc452ab","trusted":true},"cell_type":"markdown","source":"## 5.3. 模型函数"},{"metadata":{"_uuid":"404eb3c6-418c-4bc4-9a6b-688af09784c4","_cell_guid":"a0938148-9c2f-43a3-8a2c-aeb1b9788204","trusted":true},"cell_type":"code","source":"# LearningRate Function 自己编写的学习率函数\n# 返回学习率·\ndef lrfn(epoch):\n    LR_START = 0.00001 # 初始学习率\n    LR_MAX = 0.00005 * strategy.num_replicas_in_sync # 最大学习率\n    LR_MIN = 0.00001 # 最小学习率\n    LR_RAMPUP_EPOCHS = 5\n    LR_SUSTAIN_EPOCHS = 0\n    LR_EXP_DECAY = .8\n    \n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b5081707-428d-47e6-86a2-f61209684fdb","_cell_guid":"932ff413-a481-48d2-b332-ca1792600e87","trusted":true},"cell_type":"markdown","source":"# 6. 数据集可视化"},{"metadata":{"_uuid":"79adee50-4f56-4776-a1d0-12aa57b853ac","_cell_guid":"2b6cedf9-09db-459d-9e4f-9936df51e514","trusted":true},"cell_type":"code","source":"# 数据展示\nprint(\"Training data shapes:\")\n# 输出训练集前3个小批量的图像数据形状、标签形状\nfor image, label in get_training_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\n# 训练数据标签示例\nprint(\"Training data label examples:\", label.numpy())\n\nprint(\"Validation data shapes:\")\n# 输出验证集前3个小批量的图像数据形状、标签形状\nfor image, label in get_validation_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\n# 验证数据标签示例\nprint(\"Validation data label examples:\", label.numpy())\n\nprint(\"Test data shapes:\")\n# 输出测试集前3个小批量的图像数据形状、标签形状\nfor image, idnum in get_test_dataset().take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\n# 测试集的id示例\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b7314bff-6a62-4006-883d-0f8870c0e0ab","_cell_guid":"01119f5d-301b-4ac8-8144-6f88feca4332","trusted":true},"cell_type":"code","source":"# 查看训练集\ntraining_dataset = get_training_dataset() #通过一个函数来获取训练集\ntraining_dataset = training_dataset.unbatch().batch(20) # 将训练集分成大小为20的小批量\ntrain_batch = iter(training_dataset) # 首先获得Iterator对象","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"79eda8f4-1557-4f46-977a-f0c6d0c83e92","_cell_guid":"b8d4d18d-6392-4e3a-98cd-603eef61a2c7","trusted":true},"cell_type":"code","source":"# 再次运行该单元格以获取下一组图像\ndisplay_batch_of_images(next(train_batch))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"38f629d9-4f18-4422-a181-ddce70567890","_cell_guid":"84ee27db-7180-4aa8-a614-a2130b99065e","trusted":true},"cell_type":"code","source":"# 查看测试集\ntest_dataset = get_test_dataset() #通过一个函数来获取测试集\ntest_dataset = test_dataset.unbatch().batch(20) # 将训练集分成大小为20的小批量\ntest_batch = iter(test_dataset) # 首先获得Iterator对象","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1d90ddf9-219f-49d9-a946-8142f1e98cdf","_cell_guid":"47e82220-f6af-43a3-80c7-3315b7c344e2","trusted":true},"cell_type":"code","source":"# 再次运行该单元格以获取下一组图像\ndisplay_batch_of_images(next(test_batch))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7036739d-4007-46b3-ac20-d5f2b68bc5d3","_cell_guid":"2cacdf80-8e34-419a-94b4-61c8aed8a64c","trusted":true},"cell_type":"markdown","source":"# 7. 训练模型"},{"metadata":{"_uuid":"5498d052-dba4-4d2f-b482-debb25abc1e7","_cell_guid":"19b7730f-62df-4637-b2e0-7c2782f54ddb","trusted":true},"cell_type":"code","source":"NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES) # 训练集样本数目\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES) # 验证集样本数目\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES) # 测试集样本数目\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE # 每轮次中的步数=训练集样本数除以每个小批量中样本数目\n# 输出训练集、验证集和测试集的数目\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c0645b2c-3f62-4ce7-9a05-07da130d99de","_cell_guid":"6591cf64-ae71-4a1e-85f0-fc8ad230b772","trusted":true},"cell_type":"markdown","source":"# 7.1. 创建模型并加载到TPU"},{"metadata":{"_uuid":"db467a2f-23a9-4270-852e-73593f2dac64","_cell_guid":"7b50f769-2def-4436-a708-d187a4199b49","trusted":true},"cell_type":"code","source":"# 创建模型并加载到TPU\nwith strategy.scope():\n    # 创建EfficientNetB7模型\n    enet = efn.EfficientNetB7( # 选择EfficientNet中的EfficientNetB7模型\n        input_shape=(512, 512, 3), # 规定输入数据的形状\n        weights='imagenet', # 用ImageNet的参数初始化模型的参数。如果不想使用ImageNet上预训练到的权重初始话模型，可以将各语句的中'imagenet'替换为'None'。\n        include_top=False # include_top：是否保留顶层的3个全连接网络，False为不保留\n    )\n    \n    # 创建模型\n    model = tf.keras.Sequential([ #Sequential类（仅用于层的线性堆叠，这是目前最常见的网络架构）\n        enet, # EfficientNetB7模型\n        tf.keras.layers.GlobalAveragePooling2D(), #全局平均池\n        # len(CLASSES)：表示这个层将返回一个大小为类别个数（104）的张量\n        # activation='softmax'：表示这个层将返回图片在104个类别上的概率，其中最大的概率表示这个图片的预测类别\n        # softmax激活函数的本质就是将一个K维的任意实数向量压缩（映射）成另一个K维的实数向量，其中向量中的每个元素取值都介于（0，1）之间并且和为1。\n        # 在多分类单标签问题中，可以用softmax作为最后的激活层，取概率最高的作为结果\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    \n    # 编译模型\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(), #优化器：Adam 是一种可以替代传统随机梯度下降（SGD）过程的一阶优化算法，它能基于训练数据迭代地更新神经网络权重\n        # 损失函数：\n        # 对于多分类问题，可以用分类交叉熵（categorical crossentropy）或稀疏分类交叉熵（sparse_categorical_crossentropy）损失函数\n        # 这个sparse_categorical_crossentropy损失函数在数学上与 categorical_crossentropy 完全相同，\n        # 如果目标是 one-hot 编码的，那么使用 categorical_crossentropy 作为损失；\n        # 如果目标是整数，那么使用 sparse_categorical_crossentropy 作为损失。\n        loss = 'sparse_categorical_crossentropy', \n        metrics=['sparse_categorical_accuracy'] # 监控指标：分类准确率\n    )\n    \n     #模型的摘要\n    model.summary()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d44c273d-c870-4298-a3ab-e269bd984fb6","_cell_guid":"4f479ae3-79e0-4e36-b2c7-694d5090f53f","trusted":true},"cell_type":"markdown","source":"保存全模型\n\n可以对整个模型进行保存，其保存的内容包括：\n\n1. 该模型的架构\n1. 模型的权重（在训练期间学到的）\n1. 模型的训练配置（你传递给编译的），如果有的话\n1. 优化器及其状态（如果有的话）（这使您可以从中断的地方重新启动训练"},{"metadata":{"_uuid":"aa26138c-fc61-4bff-a955-2e287ca36285","_cell_guid":"0368da1b-bfd1-4a78-b5fc-53c73000bdfa","trusted":true},"cell_type":"code","source":"model.save('the_save_model.h5') #保存全模型","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e26ff2bf-fd4b-4e3b-a221-e607e7c8c787","_cell_guid":"18b29fbb-3ce3-4bc8-b418-89ede8f644b8","trusted":true},"cell_type":"markdown","source":"## 7.2. 训练模型"},{"metadata":{"_uuid":"e19e9f75-7e50-4f17-8448-df8cc80bea57","_cell_guid":"0f0ebca8-66d0-4ce6-a911-ce7d9299e2e9","trusted":true},"cell_type":"code","source":"# scheduler = tf.keras.callbacks.ReduceLROnPlateau(patience=3, verbose=1)\n# 作为回调函数的一员,LearningRateScheduler 可以按照epoch的次数自动调整学习率,\n# 参数：\n# schedule：一个函数，它将一个epoch索引作为输入（整数，从0开始索引）并返回一个新的学习速率作为输出（浮点数）。\n# 我们这里用lrfn（epoch）函数\n# verbose：int；当其为0时，保持安静；当其为1时，表示更新消息。\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1) \n\n# 训练模型\nhistory = model.fit(\n    get_train_valid_datasets(),  # 获取训练集\n    steps_per_epoch=STEPS_PER_EPOCH, # 设置每轮的步数\n    epochs=EPOCHS,  # 设置轮次\n    callbacks=[lr_schedule], # 设置回调函数\n    validation_data=get_validation_dataset() # 设置验证集\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"4bb90387-e514-4420-8526-3803f0eafd3f","_cell_guid":"ddc54e71-f439-4810-9cb0-4690efb50ab3","trusted":true},"cell_type":"markdown","source":"## 7.3. 绘制损失和准确率曲线"},{"metadata":{"_uuid":"34282c96-8c9d-4fca-a8ce-8c033c47ab7f","_cell_guid":"aab2e497-5710-4304-8a19-da1b2e7cf31c","trusted":true},"cell_type":"code","source":"# 画出训练集和验证集随轮次变化的损失和准确率\ndisplay_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 211) #损失曲线\ndisplay_training_curves(history.history['sparse_categorical_accuracy'], history.history['val_sparse_categorical_accuracy'], 'accuracy', 212) #准确率曲线\n# display_training_curves(history.history['loss'], history.history['loss'], 'loss', 211)\n# display_training_curves(history.history['sparse_categorical_accuracy'], history.history['sparse_categorical_accuracy'], 'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c16cf7b5-9ad1-49af-bb14-079e0c4b8e7e","_cell_guid":"6c2f235f-e400-46cf-9250-11fbd6671dea","trusted":true},"cell_type":"markdown","source":"## 7.4. 绘制混淆矩阵"},{"metadata":{"_uuid":"3a80856f-e0a3-4847-aac5-5857eaac4f6d","_cell_guid":"e84a7ebb-cf75-4fcc-bd69-73296d795fa5","trusted":true},"cell_type":"code","source":"# 因为我们要分割数据集并分别对图像和标签进行迭代，所以顺序很重要。\ncmdataset = get_validation_dataset(ordered=True)  # 验证集\nimages_ds = cmdataset.map(lambda image, label: image)  # 图像集\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch() # 标签集 \ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy() # get everything as one batch\ncm_probabilities = model.predict(images_ds) # 图片在104个类别上的概率\ncm_predictions = np.argmax(cm_probabilities, axis=-1) # 其中最大的概率表示这个图片的预测类别\nprint(\"Correct   labels: \", cm_correct_labels.shape, cm_correct_labels) # 输出正确（实际）标签的形状、输出正确标签 \nprint(\"Predicted labels: \", cm_predictions.shape, cm_predictions) # 输出预测标签的形状、输出预测标签","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b7ff59ca-1ad7-4cc4-a943-1223b4037bda","_cell_guid":"2a2bb8db-ecd1-4918-b26e-80a66476418e","trusted":true},"cell_type":"code","source":"# 计算混淆矩阵\n# 参数为实际标签和预测的标签\ncmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\n# 计算f1分数\nscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n# 计算精确率\nprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n# 计算召回率\nrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\n# 归一化\ncmat = (cmat.T / cmat.sum(axis=1)).T # normalized\n# 绘制混淆矩阵\ndisplay_confusion_matrix(cmat, score, precision, recall)\n# 输出f1分数、精确率、召回率\nprint('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"658e5958-1f49-4128-bcf1-5d29ea44759b","_cell_guid":"fff9019d-1dc0-4877-b61b-6d90ee1b156c","trusted":true},"cell_type":"markdown","source":"# 8. 预测"},{"metadata":{"_uuid":"e9ae37c1-c8fc-4a8b-8cf1-2700db859f5d","_cell_guid":"bca898e9-2e4d-4a41-b327-67f54ef550da","trusted":true},"cell_type":"code","source":"# 因为我们要分割数据集并分别对图像和ID进行迭代，所以顺序很重要。\ntest_ds = get_test_dataset(ordered=True) # 测试集\n\n# 对测试集进行预测\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image) #测试集的图片\nprobabilities = model.predict(test_images_ds) # 图片在104个类别上的概率\npredictions = np.argmax(probabilities, axis=-1) # 其中最大的概率表示这个图片的预测类别\nprint(predictions) # 输出预测类别\n\n# 生成提交文件\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch() #测试集的id\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # 准换id的数据类型 # all in one batch\n\n# 第一种存储文件方式，不需要pandas\n# np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n# 第二种存储文件的方式，需要pandas\nimport pandas as pd\ntest = pd.DataFrame({\"id\":test_ids,\"label\":predictions}) #将id列和label列创建成一个DataFrame\nprint(test.head) # 输出test的前几行\ntest.to_csv(\"submission.csv\",index = False) # 生成没有索引的submission.csv，以便提交","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a6d65cb7-8cc5-4768-ac07-42b24c946f45","_cell_guid":"23664964-36b6-4e7b-a391-4c258b5bb084","trusted":true},"cell_type":"markdown","source":"# 9. 视觉上进行一下验证，看下预测效果\n这里为什么选择验证集进行视觉上的验证？\n\n我们选取验证集进行验证，因为模型是根据训练集训练的，而验证集和测试集都和训练集毫不相关，但是验证集有实际标签，方便我们进行验证"},{"metadata":{"_uuid":"5c5f1e90-84aa-4a85-a291-ec654ac72395","_cell_guid":"db8828aa-90b3-45e3-a5d6-e75b2ea363a4","trusted":true},"cell_type":"code","source":"dataset = get_validation_dataset()  # 获取验证集\ndataset = dataset.unbatch().batch(20)  #将验证集分成大小为20的小批量\nbatch = iter(dataset) # 将数据集转化为Iterator对象","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"af16367b-0981-4704-9420-6a0abb756373","_cell_guid":"059af2f5-65c8-4806-83ac-c2ed57d07ec7","trusted":true},"cell_type":"code","source":"# 再次运行该单元格以获取下一组图像\nimages, labels = next(batch) # 获取验证集的下一个批量\nprobabilities = model.predict(images) # 图片在104个类别上的概率\npredictions = np.argmax(probabilities, axis=-1) # 其中最大的概率表示这个图片的预测类别\ndisplay_batch_of_images((images, labels), predictions) # 展示一个批量的图片，图片标题为预测标签+预测标签是否正确（OK或NO）\n# 举个例子：标题为wild rose（NO->watercress），这个图片实际是豆瓣花，但是预测为野玫瑰，所以它是错的。所以它的标签为 野玫瑰（NO->豆瓣花）","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}