{"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":"# EfficientNetB7 迁移学习\n这是可能会令你非常自豪的一个程序！这个程序过后，或许你可以确信做出类似花伴侣这样酷的应用！<br/>\n<a href=\"http://www.aiplants.net/\">花伴侣</a><br/>\n花草树木，一拍呈名。只需要拍摄植物的花、果、叶等特征部位，即可快速识别植物。花伴侣能识别中国野生及栽培植物3000属，近5000种，几乎涵盖身边所有常见花草树木。","metadata":{}},{"cell_type":"code","source":"# 导入库\nimport math, re, os\n# 设置log等级，只输出Error和Fatal级别的信息\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets   # 用于访问Google云服务器上的数据集\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-10-17T04:33:30.705499Z","iopub.execute_input":"2021-10-17T04:33:30.706330Z","iopub.status.idle":"2021-10-17T04:33:30.715179Z","shell.execute_reply.started":"2021-10-17T04:33:30.706281Z","shell.execute_reply":"2021-10-17T04:33:30.714198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1 使用TPU训练模型\n为了使用TPU，需要首先检测和链接TPU，并根据可用的TPU加速单元数量，决定批处理大小。学习率动态调度策略也考虑了这一点。","metadata":{}},{"cell_type":"code","source":"# 检测并链接 TPU \ntpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()\nstrategy = tf.distribute.TPUStrategy(tpu)\nAUTO = tf.data.experimental.AUTOTUNE   # 并行化训练模式\nprint(\"Number of accelerators: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:33:34.902424Z","iopub.execute_input":"2021-10-17T04:33:34.902867Z","iopub.status.idle":"2021-10-17T04:33:40.390568Z","shell.execute_reply.started":"2021-10-17T04:33:34.902835Z","shell.execute_reply":"2021-10-17T04:33:40.390013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512]   # 输入图像的尺寸\nEPOCHS = 13  # 训练代数\nBATCH_SIZE = 32 * strategy.num_replicas_in_sync  # 根据TPU加速器数量设定批处理大小","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:33:40.391843Z","iopub.execute_input":"2021-10-17T04:33:40.392205Z","iopub.status.idle":"2021-10-17T04:33:40.396289Z","shell.execute_reply.started":"2021-10-17T04:33:40.392176Z","shell.execute_reply":"2021-10-17T04:33:40.395365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2 数据集目录观察\n花朵数据集包含四种尺寸规格的图片，可以根据需要任意选择。这里选定512x512的数据集。","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # 获取数据集在Google Cloud Storage上的地址 \nGCS_DS_PATH","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:33:42.374695Z","iopub.execute_input":"2021-10-17T04:33:42.375327Z","iopub.status.idle":"2021-10-17T04:33:44.169689Z","shell.execute_reply.started":"2021-10-17T04:33:42.375283Z","shell.execute_reply":"2021-10-17T04:33:44.169075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_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]]  # 返回512x512数据集的路径\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') # 返回测试集测试集文件列表","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:33:44.171011Z","iopub.execute_input":"2021-10-17T04:33:44.171612Z","iopub.status.idle":"2021-10-17T04:33:44.394393Z","shell.execute_reply.started":"2021-10-17T04:33:44.171577Z","shell.execute_reply":"2021-10-17T04:33:44.393760Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 训练集目录列表\nTRAINING_FILENAMES","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:33:45.217635Z","iopub.execute_input":"2021-10-17T04:33:45.218227Z","iopub.status.idle":"2021-10-17T04:33:45.224858Z","shell.execute_reply.started":"2021-10-17T04:33:45.218174Z","shell.execute_reply":"2021-10-17T04:33:45.224245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 验证集目录列表\nVALIDATION_FILENAMES","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:33:46.217659Z","iopub.execute_input":"2021-10-17T04:33:46.218540Z","iopub.status.idle":"2021-10-17T04:33:46.225182Z","shell.execute_reply.started":"2021-10-17T04:33:46.218485Z","shell.execute_reply":"2021-10-17T04:33:46.224323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 测试集目录列表\nTEST_FILENAMES","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:33:46.661789Z","iopub.execute_input":"2021-10-17T04:33:46.662308Z","iopub.status.idle":"2021-10-17T04:33:46.668227Z","shell.execute_reply.started":"2021-10-17T04:33:46.662260Z","shell.execute_reply":"2021-10-17T04:33:46.667339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 104种花朵名称（标签）\nCLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     \n           'wild geranium',     'tiger lily',           'moon orchid',          'bird of paradise', \n           'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', \n           'yellow iris',       'globe-flower',         'purple coneflower',    'peruvian lily', \n           'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',   \n           'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian',\n           'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        \n           'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',          'great masterwort', \n           'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    \n           'bolero deep blue',  'wallflower',           'marigold',             'buttercup',    \n           'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',   \n           'lilac hibiscus',    'bishop of llandaff',   'gaura',                'geranium',   \n           'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',\n           'californian poppy', 'osteospermum',         'spring crocus',        'iris',      \n           'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',      \n           'thorn apple',       'morning glory',        'passion flower',       'lotus',    \n           'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',   \n           'desert-rose',       'tree mallow',          'magnolia',             'cyclamen ',  \n           'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',   \n           'bougainvillea',     'camellia',             'mallow',               'mexican petunia', \n           'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose'] # 100 - 103","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:35:06.565500Z","iopub.execute_input":"2021-10-17T04:35:06.565834Z","iopub.status.idle":"2021-10-17T04:35:06.577255Z","shell.execute_reply.started":"2021-10-17T04:35:06.565799Z","shell.execute_reply":"2021-10-17T04:35:06.576236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"##  3 学习率调度函数\n学习率对模型训练异常重要。为此，指定学习率动态调度策略非常必要！","metadata":{}},{"cell_type":"code","source":"LR_START = 0.00001  # 学习率初值\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync  # 学习率最大值\nLR_MIN = 0.00001   # 学习率最小值\nLR_RAMPUP_EPOCHS = 4   # 学习率增长代数\nLR_SUSTAIN_EPOCHS = 0  # 学习率保持不变的代数\nLR_EXP_DECAY = .8  # 学习率衰减因子\n\n# 学习率调度函数\ndef lrfn(epoch):\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\n# 学习率回调函数   \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\n# 绘制学习率变化曲线，观察模型训练期间学习率变化规律\nrng = range(EPOCHS)\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)\nprint(f\"学习率调度策略，从最小值 {y[0]} 到最大值： {max(y)} 再衰减到： {y[-1]}\")","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:35:14.707954Z","iopub.execute_input":"2021-10-17T04:35:14.708241Z","iopub.status.idle":"2021-10-17T04:35:15.202722Z","shell.execute_reply.started":"2021-10-17T04:35:14.708213Z","shell.execute_reply":"2021-10-17T04:35:15.201845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 4 可视化函数\n定义显示图像函数、显示模型训练曲线函数、显示混淆矩阵的函数，分别用于观察数据集、观察模型训练效果和预测结果。","metadata":{}},{"cell_type":"code","source":"# 控制输出的显示方式\nnp.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data): # 数据集转换为 Numpy类型\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, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # 对于测试集，numpy_labels返回值为 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', \"?\" 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), \n                  color='red' if red else 'black', \n                  fontdict={'verticalalignment':'center'}, \n                  pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None):  # 批量显示\n    \"\"\"\n    用法:\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    # 显示尺寸和间距\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    # 显示\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 \n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    # 布局\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\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', \n                                               'verticalalignment':'top', 'color':'#804040'})\n    plt.show()\n    \n# 显示模型训练曲线    \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.'])","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:35:30.814806Z","iopub.execute_input":"2021-10-17T04:35:30.815544Z","iopub.status.idle":"2021-10-17T04:35:30.844116Z","shell.execute_reply.started":"2021-10-17T04:35:30.815502Z","shell.execute_reply":"2021-10-17T04:35:30.843196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 5 定义数据集\n兵马未动，粮草先行，数据集预处理始终是建模第一步！细心对待训练集、验证集和测试集！","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3) # image format uint8 [0,255]\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for 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 # returns a dataset of (image, label) pairs\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    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    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    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\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\nNUM_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\nVALIDATION_STEPS = -(-NUM_VALIDATION_IMAGES // BATCH_SIZE)\nTEST_STEPS = -(-NUM_TEST_IMAGES // BATCH_SIZE) \nprint(f'训练集图像数量: {NUM_TRAINING_IMAGES} ，\\\n      验证集图像数量： {NUM_VALIDATION_IMAGES}，\\\n      测试集图像数量：{NUM_TEST_IMAGES}')","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2021-10-17T05:45:05.994059Z","iopub.execute_input":"2021-10-17T05:45:05.994442Z","iopub.status.idle":"2021-10-17T05:45:06.017530Z","shell.execute_reply.started":"2021-10-17T05:45:05.994399Z","shell.execute_reply":"2021-10-17T05:45:06.016598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 数据集观察\n抽样显示数据集图片，建立感性认识","metadata":{}},{"cell_type":"code","source":"# data dump\nprint(\"Training data shapes:\")\nfor image, label in get_training_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())\nprint(\"Validation data shapes:\")\nfor image, label in get_validation_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Validation data label examples:\", label.numpy())\nprint(\"Test data shapes:\")\nfor image, idnum in get_test_dataset().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":"2021-10-17T04:41:48.229503Z","iopub.execute_input":"2021-10-17T04:41:48.230042Z","iopub.status.idle":"2021-10-17T04:41:56.010522Z","shell.execute_reply.started":"2021-10-17T04:41:48.230003Z","shell.execute_reply":"2021-10-17T04:41:56.009694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 观察训练集\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\ntrain_batch = iter(training_dataset)","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:42:54.573702Z","iopub.execute_input":"2021-10-17T04:42:54.574466Z","iopub.status.idle":"2021-10-17T04:42:54.632771Z","shell.execute_reply.started":"2021-10-17T04:42:54.574420Z","shell.execute_reply":"2021-10-17T04:42:54.631964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 随机抽样\ndisplay_batch_of_images(next(train_batch))","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:43:17.429516Z","iopub.execute_input":"2021-10-17T04:43:17.430065Z","iopub.status.idle":"2021-10-17T04:43:20.302854Z","shell.execute_reply.started":"2021-10-17T04:43:17.430024Z","shell.execute_reply":"2021-10-17T04:43:20.301679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 观察测试集\ntest_dataset = get_test_dataset()\ntest_dataset = test_dataset.unbatch().batch(20)\ntest_batch = iter(test_dataset)","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:43:29.365985Z","iopub.execute_input":"2021-10-17T04:43:29.367018Z","iopub.status.idle":"2021-10-17T04:43:29.404858Z","shell.execute_reply.started":"2021-10-17T04:43:29.366977Z","shell.execute_reply":"2021-10-17T04:43:29.403971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 随机抽样\ndisplay_batch_of_images(next(test_batch))","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:43:36.671130Z","iopub.execute_input":"2021-10-17T04:43:36.671850Z","iopub.status.idle":"2021-10-17T04:43:39.608697Z","shell.execute_reply.started":"2021-10-17T04:43:36.671805Z","shell.execute_reply":"2021-10-17T04:43:39.608073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"##  6 定义模型 EfficientNetB7\n用TPU模式定义","metadata":{}},{"cell_type":"code","source":"with strategy.scope():\n    load_locally = tf.saved_model.LoadOptions(experimental_io_device='/job:localhost')\n    pretrained_model = hub.KerasLayer('https://tfhub.dev/tensorflow/efficientnet/b7/feature-vector/1', \n                                      trainable=True,\n                                      input_shape=[*IMAGE_SIZE, 3], \n                                      load_options=load_locally)\n    model = tf.keras.Sequential([\n        # the expected image format for all TFHub image models is float32 in [0,1) range\n        tf.keras.layers.Lambda(lambda data: tf.image.convert_image_dtype(data, tf.float32), input_shape=[*IMAGE_SIZE, 3]),\n        pretrained_model,\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n    steps_per_execution=16\n)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:53:01.507152Z","iopub.execute_input":"2021-10-17T04:53:01.507433Z","iopub.status.idle":"2021-10-17T04:53:57.057875Z","shell.execute_reply.started":"2021-10-17T04:53:01.507405Z","shell.execute_reply":"2021-10-17T04:53:57.056988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 7 模型训练","metadata":{}},{"cell_type":"code","source":"history = model.fit(get_training_dataset(), \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=EPOCHS,\n                    validation_data=get_validation_dataset(), \n                    validation_steps=VALIDATION_STEPS,\n                    callbacks=[lr_callback])","metadata":{"execution":{"iopub.status.busy":"2021-10-17T04:55:06.418277Z","iopub.execute_input":"2021-10-17T04:55:06.418617Z","iopub.status.idle":"2021-10-17T05:19:07.212426Z","shell.execute_reply.started":"2021-10-17T04:55:06.418581Z","shell.execute_reply":"2021-10-17T05:19:07.211545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 8 显示准确率和损失函数曲线","metadata":{}},{"cell_type":"code","source":"display_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 211)\ndisplay_training_curves(history.history['sparse_categorical_accuracy'], \n                        history.history['val_sparse_categorical_accuracy'], 'accuracy', 212)","metadata":{"execution":{"iopub.status.busy":"2021-10-17T05:19:07.214879Z","iopub.execute_input":"2021-10-17T05:19:07.215149Z","iopub.status.idle":"2021-10-17T05:19:07.749751Z","shell.execute_reply.started":"2021-10-17T05:19:07.215120Z","shell.execute_reply":"2021-10-17T05:19:07.748706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 9 保存模型","metadata":{}},{"cell_type":"code","source":"save_locally = tf.saved_model.SaveOptions(experimental_io_device='/job:localhost')\nmodel.save('./EfficientNetB7', options=save_locally) # saving in Tensorflow's \"SavedModel\" format","metadata":{"execution":{"iopub.status.busy":"2021-10-17T05:19:07.751401Z","iopub.execute_input":"2021-10-17T05:19:07.751748Z","iopub.status.idle":"2021-10-17T05:20:45.256516Z","shell.execute_reply.started":"2021-10-17T05:19:07.751705Z","shell.execute_reply":"2021-10-17T05:20:45.252255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 10 模型评估--混淆矩阵、F1-Score","metadata":{}},{"cell_type":"code","source":"load_locally = tf.saved_model.LoadOptions(experimental_io_device='/job:localhost')\nmodel = tf.keras.models.load_model('./EfficientNetB7', options=load_locally)","metadata":{"execution":{"iopub.status.busy":"2021-10-17T05:20:45.275279Z","iopub.execute_input":"2021-10-17T05:20:45.275605Z","iopub.status.idle":"2021-10-17T05:21:58.335548Z","shell.execute_reply.started":"2021-10-17T05:20:45.275570Z","shell.execute_reply":"2021-10-17T05:21:58.334770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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()\n# 预测标签\ncm_probabilities = model.predict(images_ds, steps=VALIDATION_STEPS)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\nprint(\"验证集真实标签: \", cm_correct_labels.shape, cm_correct_labels)\nprint(\"验证集预测标签: \", cm_predictions.shape, cm_predictions)","metadata":{"execution":{"iopub.status.busy":"2021-10-17T05:45:50.891849Z","iopub.execute_input":"2021-10-17T05:45:50.892360Z","iopub.status.idle":"2021-10-17T05:54:05.329547Z","shell.execute_reply.started":"2021-10-17T05:45:50.892324Z","shell.execute_reply":"2021-10-17T05:54:05.328620Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))\nscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\nrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)), average='macro')\ncmat = (cmat.T / cmat.sum(axis=1)).T # normalized\ndisplay_confusion_matrix(cmat, score, precision, recall)\nprint('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))","metadata":{"execution":{"iopub.status.busy":"2021-10-17T05:54:05.331184Z","iopub.execute_input":"2021-10-17T05:54:05.331501Z","iopub.status.idle":"2021-10-17T05:54:10.264536Z","shell.execute_reply.started":"2021-10-17T05:54:05.331468Z","shell.execute_reply":"2021-10-17T05:54:10.263649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"##  11 模型预测\n在测试集上预测，保存预测结果到 submission.csv 文件中...","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint('在测试集上做预测...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds, steps=TEST_STEPS)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('生成预测结果文件 submission.csv...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), \n           fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2021-10-17T05:54:10.265798Z","iopub.execute_input":"2021-10-17T05:54:10.266045Z","iopub.status.idle":"2021-10-17T06:10:48.679602Z","shell.execute_reply.started":"2021-10-17T05:54:10.266017Z","shell.execute_reply":"2021-10-17T06:10:48.678522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###  对验证集预测结果的可视化观察","metadata":{}},{"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","metadata":{"execution":{"iopub.status.busy":"2021-10-17T06:10:48.682858Z","iopub.execute_input":"2021-10-17T06:10:48.683132Z","iopub.status.idle":"2021-10-17T06:10:48.750002Z","shell.execute_reply.started":"2021-10-17T06:10:48.683101Z","shell.execute_reply":"2021-10-17T06:10:48.749238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 在验证集上随机抽样观察\nimages, 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":"2021-10-17T06:11:18.940248Z","iopub.execute_input":"2021-10-17T06:11:18.940990Z","iopub.status.idle":"2021-10-17T06:11:23.733707Z","shell.execute_reply.started":"2021-10-17T06:11:18.940955Z","shell.execute_reply":"2021-10-17T06:11:23.733028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 对测试集预测结果的可视化观察","metadata":{}},{"cell_type":"code","source":"dataset = get_test_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","metadata":{"execution":{"iopub.status.busy":"2021-10-17T06:11:31.047304Z","iopub.execute_input":"2021-10-17T06:11:31.047924Z","iopub.status.idle":"2021-10-17T06:11:31.082721Z","shell.execute_reply.started":"2021-10-17T06:11:31.047880Z","shell.execute_reply":"2021-10-17T06:11:31.081996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 在测试集上随机抽样观察\nimages, 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":"2021-10-17T06:11:34.357855Z","iopub.execute_input":"2021-10-17T06:11:34.358670Z","iopub.status.idle":"2021-10-17T06:11:39.483593Z","shell.execute_reply.started":"2021-10-17T06:11:34.358633Z","shell.execute_reply":"2021-10-17T06:11:39.482659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"至此，颇有成就感！我们得到了一个性能非常好的花朵识别模型。虽然只有104种花朵。只要您有新的数据集，您完全可以在此基础上，继续运用迁移学习迭代下去，识别更多类型的花朵！！","metadata":{}}]}