{"cells":[{"metadata":{"_uuid":"f309d71f-d039-4735-b7e9-b830686889dc","_cell_guid":"f289fbee-43fa-477c-926f-03e5dc648131","trusted":true},"cell_type":"code","source":"# 以狗分类为例子，可以自由使用所有方法以及其组合，可以自由更改数据集\n# baseline：EfficientNetB0，可以自由更改网络\n\n# 可以选择启用哪些方法\n\nbool_random_flip_left_right=0\nbool_random_flip_up_down=0\nbool_random_brightness=0\nbool_random_contrast=0\nbool_random_hue=0\nbool_random_saturation=0\n\nbool_rotation_transform=0\ncutmix_rate=0.\nmixup_rate= 0.\ngridmask_rate = 0.\n\npre_trained='imagenet' # None,'imagenet','noisy-student'\ndense_activation='softmax' #'softmax','sigmoid'\nbool_lr_scheduler=0\n\n# 交叉验证和tta目前最多只允许使用一个\ntta_times=0 #当tta_times=i>0时，使用i+1倍测试集\ncross_validation_folds=0 #当tta_times=i>1时，使用i折交叉验证\n\n\n#focal_loss和label_smoothing最多同时使用一个\nbool_focal_loss = 0\nlabel_smoothing_rate=0.\n\n# 划分了训练集和验证集时才有效,该功能暂时作废\n# special_monitor='auc'#None,'auc'\n\n\n# 暂未引入，后续引入\n# adversarial validation","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ad95383b-62db-4d53-8fbe-7a2b125c6e76","_cell_guid":"56d106de-3991-4fdb-a8f5-e4a028f22eb6","trusted":true},"cell_type":"code","source":"#针对前面opts的一些中间处理\n\n#tta只有在使用了data_aug时才允许启用\nbool_tta =  tta_times and max(  bool_random_flip_left_right,\n                                bool_random_flip_up_down,\n                                bool_random_brightness,\n                                bool_random_contrast,\n                                bool_random_hue,\n                                bool_random_saturation)\n\nprint(bool_tta)\n\nassert (bool_focal_loss and label_smoothing_rate) == 0 , 'focal_loss和label_smoothing最多同时使用一个'\nassert (tta_times and cross_validation_folds) == 0 , 'focal_loss和label_smoothing最多同时使用一个'    ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"24546652-247e-415c-86eb-f2dd9170b48a","_cell_guid":"0c7f1698-8c79-4944-bf42-1b2e6598548e","trusted":true},"cell_type":"code","source":"#安装包\n!pip install -U efficientnet\n!pip install tensorflow_addons","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ad2784c5-9a2a-4702-a2d0-cfa6d0310ab1","_cell_guid":"05d934c2-62e2-4b3e-8602-603b20ce4e9f","trusted":true},"cell_type":"code","source":"#导入包\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt \nimport os\nimport tensorflow as tf\nimport random, re, math\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras import optimizers\nimport tensorflow_addons as tfa\n\nfrom kaggle_datasets import KaggleDatasets\nimport efficientnet.tfkeras as efn\nfrom sklearn.model_selection import KFold\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n\nprint(tf.__version__)\nprint(tf.keras.__version__)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e45297b9-179d-48e4-8eac-9dc7156b9291","_cell_guid":"44ba2954-3773-40be-82a3-e738399348f9","trusted":true},"cell_type":"code","source":"#针对不同硬件产生不同配置\nAUTO = tf.data.experimental.AUTOTUNE\n# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\n    GCS_DS_PATH = KaggleDatasets().get_gcs_path()\n    print(GCS_DS_PATH)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9df674cb-0e75-4917-96cb-9b16c199896f","_cell_guid":"61296a55-85e3-45ba-9fee-920a14aaec22","trusted":true},"cell_type":"code","source":"#更换数据集时更换整个这大段\n\n#超参数，根据数据和策略调参\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nimg_size = 512\nIMAGE_SIZE=(img_size, img_size)\n\n#应感觉该是，用的数据增强方法增多，那么需要的EPOCHS也需要增多\nEPOCHS = 12 #12,改为1快速测试\nlr_if_without_scheduler = 0.0003\nnb_classes = 104\nprint('BATCH_SIZE是：',BATCH_SIZE)\n\n#如果使用了special_monitor，会在后续自动append，无需在此添加\nmy_metrics = ['accuracy']\n\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}\n\n\nGCS_PATH = GCS_PATH_SELECT[img_size]\n\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\n\nprint(GCS_PATH)\n#应该是这个才对  gs://kds-b2e6cdbc4af76dcf0363776c09c12fe46872cab211d1de9f60ec7aec/tfrecords-jpeg-512x512\n\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\ntest_paths = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') # predictions on this dataset should be submitted for the competition\ntrain_paths=TRAINING_FILENAMES+VALIDATION_FILENAMES\n\nprint(TRAINING_FILENAMES)\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\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  # convert image to floats in [0, 1] range\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    label=tf.one_hot(label,nb_classes)\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        # 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\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#lr_scheduler\n#数值按实际情况设置\n\nLR_START = 0.00003\nLR_MAX = 0.0003 * strategy.num_replicas_in_sync\nLR_MIN = 0.00003\nLR_RAMPUP_EPOCHS = 3\nLR_SUSTAIN_EPOCHS = 1\nLR_EXP_DECAY = .8\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\nrng = [i for i in range(EPOCHS)]\ny = [lrfn(x) for x in rng]\nif bool_lr_scheduler:\n    plt.plot(rng, y)\n    print(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7aedd923-9e6c-401d-9619-65fa195ec0ac","_cell_guid":"cc2fde42-2a63-4f5b-824e-37bafaf3ea41","trusted":true},"cell_type":"code","source":"'''\n# 这里比较特殊，需要重写decode_image\ndef decode_image(filename, label=None, image_size=(img_size, img_size)):\n    bits = tf.io.read_file(filename)\n    image = tf.image.decode_jpeg(bits, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.image.resize(image, image_size)\n    if label is None:\n        return image\n    else:\n        return image, label\n'''\n\n\n\n\n# 只能写入test data 也能用的 aug   \ndef data_aug(image, label=None):\n    if bool_random_flip_left_right:\n        image = tf.image.random_flip_left_right(image)\n    if bool_random_flip_up_down:    \n        image = tf.image.random_flip_up_down(image)\n    if bool_random_brightness:\n        image = tf.image.random_brightness(image,0.2)\n    if bool_random_contrast:\n        image = tf.image.random_contrast(image,0.6,1.4)\n    if bool_random_hue:\n        image = tf.image.random_hue(image,0.07)\n    if bool_random_saturation:\n        image = tf.image.random_saturation(image,0.5,1.5)\n    \n    if label is None:\n        return image\n    else:\n        return image, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf, tensorflow.keras.backend as K\ndef get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n    # returns 3x3 transformmatrix which transforms indicies\n        \n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation / 180.\n    shear = math.pi * shear / 180.\n    \n    # ROTATION MATRIX\n    c1 = tf.math.cos(rotation)\n    s1 = tf.math.sin(rotation)\n    one = tf.constant([1],dtype='float32')\n    zero = tf.constant([0],dtype='float32')\n    rotation_matrix = tf.reshape( tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3] )\n        \n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape( tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3] )    \n    \n    # ZOOM MATRIX\n    zoom_matrix = tf.reshape( tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3] )\n    \n    # SHIFT MATRIX\n    shift_matrix = tf.reshape( tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3] )\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))\n\n\ndef rotation_transform(image,label):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly rotated, sheared, zoomed, and shifted\n    DIM = IMAGE_SIZE[0]\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = 15. * tf.random.normal([1],dtype='float32')\n    shr = 5. * tf.random.normal([1],dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    h_shift = 16. * tf.random.normal([1],dtype='float32') \n    w_shift = 16. * tf.random.normal([1],dtype='float32') \n  \n    # GET TRANSFORMATION MATRIX\n    m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift) \n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat( tf.range(DIM//2,-DIM//2,-1), DIM )\n    y = tf.tile( tf.range(-DIM//2,DIM//2),[DIM] )\n    z = tf.ones([DIM*DIM],dtype='int32')\n    idx = tf.stack( [x,y,z] )\n    \n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(m,tf.cast(idx,dtype='float32'))\n    idx2 = K.cast(idx2,dtype='int32')\n    idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)\n    \n    # FIND ORIGIN PIXEL VALUES           \n    idx3 = tf.stack( [DIM//2-idx2[0,], DIM//2-1+idx2[1,]] )\n    d = tf.gather_nd(image,tf.transpose(idx3))\n        \n    return tf.reshape(d,[DIM,DIM,3]),label","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f14868a5-58fa-4c94-928d-ff1fbb675c7d","_cell_guid":"8f64b93c-a5bb-4fa2-867c-592ba64b74ad","trusted":true},"cell_type":"code","source":"# 在batch内部互相随机取图\ndef cutmix(image, label, PROBABILITY = cutmix_rate):\n    # input image - is a batch of images of size [n,dim,dim,3] not a single image of [dim,dim,3]\n    # output - a batch of images with cutmix applied\n    label=tf.cast(label,tf.float32)\n    \n    DIM = img_size    \n    imgs = []; labs = []\n    \n    for j in range(BATCH_SIZE):\n        \n        #random_uniform( shape, minval=0, maxval=None)        \n        # DO CUTMIX WITH PROBABILITY DEFINED ABOVE\n        P = tf.cast(tf.random.uniform([], 0, 1) <= PROBABILITY, tf.int32)\n        \n        # CHOOSE RANDOM IMAGE TO CUTMIX WITH\n        k = tf.cast(tf.random.uniform([], 0, BATCH_SIZE), tf.int32)\n        \n        # CHOOSE RANDOM LOCATION\n        #选一个随机的中心点\n        x = tf.cast(tf.random.uniform([], 0, DIM), tf.int32)\n        y = tf.cast(tf.random.uniform([], 0, DIM), tf.int32)\n        \n        # Beta(1, 1)等于均匀分布\n        b = tf.random.uniform([], 0, 1) # this is beta dist with alpha=1.0\n        \n        #P只随机出0或1，就是裁剪或是不裁剪\n        WIDTH = tf.cast(DIM * tf.math.sqrt(1-b),tf.int32) * P\n        ya = tf.math.maximum(0,y-WIDTH//2)\n        yb = tf.math.minimum(DIM,y+WIDTH//2)\n        xa = tf.math.maximum(0,x-WIDTH//2)\n        xb = tf.math.minimum(DIM,x+WIDTH//2)\n        \n        # MAKE CUTMIX IMAGE\n        one = image[j,ya:yb,0:xa,:]\n        two = image[k,ya:yb,xa:xb,:]\n        three = image[j,ya:yb,xb:DIM,:]        \n        #得出了ya:yb区间内的输出图像\n        middle = tf.concat([one,two,three],axis=1)\n        #得到了完整输出图像\n        img = tf.concat([image[j,0:ya,:,:],middle,image[j,yb:DIM,:,:]],axis=0)\n        imgs.append(img)\n        \n        # MAKE CUTMIX LABEL\n        #按面积来加权的\n        a = tf.cast(WIDTH*WIDTH/DIM/DIM,tf.float32)\n        lab1 = label[j,]\n        lab2 = label[k,]\n        labs.append((1-a)*lab1 + a*lab2)\n\n    image2 = tf.reshape(tf.stack(imgs),(BATCH_SIZE,DIM,DIM,3))\n    label2 = tf.reshape(tf.stack(labs),(BATCH_SIZE, nb_classes))\n    return image2,label2","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d226c59c-f232-4bc6-a4d5-392ddad00b3b","_cell_guid":"fabb0fda-9b89-40d9-bbb2-f8fece5cb7fc","trusted":true},"cell_type":"code","source":"def mixup(image, label, PROBABILITY = mixup_rate):\n    # input image - is a batch of images of size [n,dim,dim,3] not a single image of [dim,dim,3]\n    # output - a batch of images with mixup applied\n    DIM = img_size\n    \n    imgs = []; labs = []\n    for j in range(BATCH_SIZE):\n        \n        # CHOOSE RANDOM\n        k = tf.cast( tf.random.uniform([],0,BATCH_SIZE),tf.int32)\n        a = tf.random.uniform([],0,1) # this is beta dist with alpha=1.0\n\n        #根据概率抽取执不执行mixup\n        P = tf.cast(tf.random.uniform([], 0, 1) <= PROBABILITY, tf.int32)\n        if P==1:\n            a=0.\n        \n        # MAKE MIXUP IMAGE\n        img1 = image[j,]\n        img2 = image[k,]\n        imgs.append((1-a)*img1 + a*img2)\n        \n        # MAKE CUTMIX LABEL\n        lab1 = label[j,]\n        lab2 = label[k,]\n        labs.append((1-a)*lab1 + a*lab2)\n            \n    # RESHAPE HACK SO TPU COMPILER KNOWS SHAPE OF OUTPUT TENSOR (maybe use Python typing instead?)\n    image2 = tf.reshape(tf.stack(imgs),(BATCH_SIZE,DIM,DIM,3))\n    label2 = tf.reshape(tf.stack(labs),(BATCH_SIZE,nb_classes))\n    return image2,label2","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b89f7ad0-e2c1-4ed4-a975-97de4481ed34","_cell_guid":"83d95ba5-7ee0-4f37-bdb8-b89f85d0c5b5","trusted":true},"cell_type":"code","source":"# gridmask\ndef transform(image, inv_mat, image_shape):\n    h, w, c = image_shape\n    cx, cy = w//2, h//2\n    new_xs = tf.repeat( tf.range(-cx, cx, 1), h)\n    new_ys = tf.tile( tf.range(-cy, cy, 1), [w])\n    new_zs = tf.ones([h*w], dtype=tf.int32)\n    old_coords = tf.matmul(inv_mat, tf.cast(tf.stack([new_xs, new_ys, new_zs]), tf.float32))\n    old_coords_x, old_coords_y = tf.round(old_coords[0, :] + w//2), tf.round(old_coords[1, :] + h//2)\n    clip_mask_x = tf.logical_or(old_coords_x<0, old_coords_x>w-1)\n    clip_mask_y = tf.logical_or(old_coords_y<0, old_coords_y>h-1)\n    clip_mask = tf.logical_or(clip_mask_x, clip_mask_y)\n    old_coords_x = tf.boolean_mask(old_coords_x, tf.logical_not(clip_mask))\n    old_coords_y = tf.boolean_mask(old_coords_y, tf.logical_not(clip_mask))\n    new_coords_x = tf.boolean_mask(new_xs+cx, tf.logical_not(clip_mask))\n    new_coords_y = tf.boolean_mask(new_ys+cy, tf.logical_not(clip_mask))\n    old_coords = tf.cast(tf.stack([old_coords_y, old_coords_x]), tf.int32)\n    new_coords = tf.cast(tf.stack([new_coords_y, new_coords_x]), tf.int64)\n    rotated_image_values = tf.gather_nd(image, tf.transpose(old_coords))\n    rotated_image_channel = list()\n    for i in range(c):\n        vals = rotated_image_values[:,i]\n        sparse_channel = tf.SparseTensor(tf.transpose(new_coords), vals, [h, w])\n        rotated_image_channel.append(tf.sparse.to_dense(sparse_channel, default_value=0, validate_indices=False))\n    return tf.transpose(tf.stack(rotated_image_channel), [1,2,0])\n\ndef random_rotate(image, angle, image_shape):\n    def get_rotation_mat_inv(angle):\n        # transform to radian\n        angle = math.pi * angle / 180\n        cos_val = tf.math.cos(angle)\n        sin_val = tf.math.sin(angle)\n        one = tf.constant([1], tf.float32)\n        zero = tf.constant([0], tf.float32)\n        rot_mat_inv = tf.concat([cos_val, sin_val, zero, -sin_val, cos_val, zero, zero, zero, one], axis=0)\n        rot_mat_inv = tf.reshape(rot_mat_inv, [3,3])\n        return rot_mat_inv\n    angle = float(angle) * tf.random.normal([1],dtype='float32')\n    rot_mat_inv = get_rotation_mat_inv(angle)\n    return transform(image, rot_mat_inv, image_shape)\n\n\ndef GridMask(image_height, image_width, d1, d2, rotate_angle=1, ratio=0.5):\n    h, w = image_height, image_width\n    hh = int(np.ceil(np.sqrt(h*h+w*w)))\n    hh = hh+1 if hh%2==1 else hh\n    d = tf.random.uniform(shape=[], minval=d1, maxval=d2, dtype=tf.int32)\n    l = tf.cast(tf.cast(d,tf.float32)*ratio+0.5, tf.int32)\n\n    st_h = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)\n    st_w = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)\n\n    y_ranges = tf.range(-1 * d + st_h, -1 * d + st_h + l)\n    x_ranges = tf.range(-1 * d + st_w, -1 * d + st_w + l)\n\n    for i in range(0, hh//d+1):\n        s1 = i * d + st_h\n        s2 = i * d + st_w\n        y_ranges = tf.concat([y_ranges, tf.range(s1,s1+l)], axis=0)\n        x_ranges = tf.concat([x_ranges, tf.range(s2,s2+l)], axis=0)\n\n    x_clip_mask = tf.logical_or(x_ranges < 0 , x_ranges > hh-1)\n    y_clip_mask = tf.logical_or(y_ranges < 0 , y_ranges > hh-1)\n    clip_mask = tf.logical_or(x_clip_mask, y_clip_mask)\n\n    x_ranges = tf.boolean_mask(x_ranges, tf.logical_not(clip_mask))\n    y_ranges = tf.boolean_mask(y_ranges, tf.logical_not(clip_mask))\n\n    hh_ranges = tf.tile(tf.range(0,hh), [tf.cast(tf.reduce_sum(tf.ones_like(x_ranges)), tf.int32)])\n    x_ranges = tf.repeat(x_ranges, hh)\n    y_ranges = tf.repeat(y_ranges, hh)\n\n    y_hh_indices = tf.transpose(tf.stack([y_ranges, hh_ranges]))\n    x_hh_indices = tf.transpose(tf.stack([hh_ranges, x_ranges]))\n\n    y_mask_sparse = tf.SparseTensor(tf.cast(y_hh_indices, tf.int64),  tf.zeros_like(y_ranges), [hh, hh])\n    y_mask = tf.sparse.to_dense(y_mask_sparse, 1, False)\n\n    x_mask_sparse = tf.SparseTensor(tf.cast(x_hh_indices, tf.int64), tf.zeros_like(x_ranges), [hh, hh])\n    x_mask = tf.sparse.to_dense(x_mask_sparse, 1, False)\n\n    mask = tf.expand_dims( tf.clip_by_value(x_mask + y_mask, 0, 1), axis=-1)\n\n    mask = random_rotate(mask, rotate_angle, [hh, hh, 1])\n    mask = tf.image.crop_to_bounding_box(mask, (hh-h)//2, (hh-w)//2, image_height, image_width)\n\n    return mask\n\ndef apply_grid_mask(image, image_shape, PROBABILITY = gridmask_rate):\n    AugParams = {\n        'd1' : 100,\n        'd2': 160,\n        'rotate' : 45,\n        'ratio' : 0.3\n    }\n    \n        \n    mask = GridMask(image_shape[0], image_shape[1], AugParams['d1'], AugParams['d2'], AugParams['rotate'], AugParams['ratio'])\n    if image_shape[-1] == 3:\n        mask = tf.concat([mask, mask, mask], axis=-1)\n        mask = tf.cast(mask,tf.float32)\n        #print(mask.shape) # (299,299,3)\n\n# 会报错，放弃\n#     imgs = []\n#     BATCH_SIZE=len(image)\n#     for j in range(BATCH_SIZE):\n#         P = tf.cast(tf.random.uniform([], 0, 1) <= PROBABILITY, tf.int32)\n#         if P==1:\n#             imgs.append(image[j,]*mask)\n#         else:\n#             imgs.append(image[j,])\n#     return tf.cast(imgs,tf.float32)\n\n        \n    # 整个batch启用或者不启用\n    P = tf.cast(tf.random.uniform([], 0, 1) <= PROBABILITY, tf.int32)\n    if P==1:\n        return image*mask\n    else:\n        return image\n\ndef gridmask(img_batch, label_batch):\n    return apply_grid_mask(img_batch, (img_size,img_size, 3)), label_batch","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a0ddeb58-7f42-4a71-92db-10fdd961bfc6","_cell_guid":"75fe26e5-a002-4e81-be54-1fc82e7cc3ec","trusted":true},"cell_type":"code","source":"def get_train_dataset(train_paths,train_labels=None):\n\n    # num_parallel_calls并发处理数据的并发数\n    #train_dataset = tf.data.Dataset.from_tensor_slices((train_paths, train_labels.astype(np.float32))).map(decode_image, num_parallel_calls=AUTO)\n\n    #特殊情况，这样更改下\n    train_dataset = load_dataset(train_paths, labeled=True)    \n    train_dataset = train_dataset.cache().map(data_aug, num_parallel_calls=AUTO).repeat()\n    \n    if bool_rotation_transform:\n        train_dataset =train_dataset.map(rotation_transform)\n                     \n    train_dataset = train_dataset.shuffle(512).batch(BATCH_SIZE,drop_remainder=True)\n\n\n    if cutmix_rate:  \n        print('启用cutmix')\n        train_dataset =train_dataset.map(cutmix, num_parallel_calls=AUTO)\n    if mixup_rate:  \n        print('启用mixup')\n        train_dataset =train_dataset.map(mixup, num_parallel_calls=AUTO)\n    if gridmask_rate:\n        print('启用gridmask')\n        train_dataset =train_dataset.map(gridmask, num_parallel_calls=AUTO)\n    if (cutmix_rate or mixup_rate):\n        train_dataset =train_dataset.unbatch().shuffle(512).batch(BATCH_SIZE)\n\n\n    # repeat()代表无限制复制原始数据，这里可以用count指明复制份数，但要注意要比fit中的epochs大才可\n    # 直接调用repeat()的话，生成的序列就会无限重复下去\n    # prefetch: prefetch next batch while training (autotune prefetch buffer size)\n    train_dataset = train_dataset.prefetch(AUTO)\n\n    return train_dataset","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"bc17efd3-ffb6-49cb-8cb2-00f581b8ea98","_cell_guid":"4db64ffe-46e1-452f-8839-d52ddd1367c9","trusted":true},"cell_type":"code","source":"try:\n    view_train_dataset=get_train_dataset(train_paths,train_labels)\nexcept:\n    view_train_dataset=get_train_dataset(train_paths)\n    \nit = view_train_dataset.__iter__()\n\n#看看train_dataset 是否正常显示\nshow_x, show_y = it.next()\nprint(show_x.shape,'\\n\\n',show_y[0])\n\nplt.figure(figsize=(12, 6))\nfor i in range(8):\n    plt.subplot(2, 4, i+1)\n    plt.imshow(show_x[i])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3eeb82d1-a3f2-44aa-9d7d-759e9db4e3a2","_cell_guid":"ab45a47e-8313-418a-80bf-c05758cc4117","trusted":true},"cell_type":"code","source":"def get_validation_dataset(valid_paths,valid_labels=None):\n    #dataset = tf.data.Dataset.from_tensor_slices((valid_paths, valid_labels))\n    #dataset = dataset.map(decode_image, num_parallel_calls=AUTO)\n    \n    #特殊情况，这样更改下\n    dataset = load_dataset(valid_paths, labeled=True, ordered=True)\n    \n    \n\n    dataset = dataset.cache()\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"18d4223e-fbf5-4c54-923e-d71b3b13b200","_cell_guid":"14239533-3146-4b08-b54a-0df89a1dc1cb","trusted":true},"cell_type":"code","source":"#生成测试集\ndef re_produce_test_dataset(test_paths):\n    #test_dataset = tf.data.Dataset.from_tensor_slices(test_paths)\n    #test_dataset = test_dataset.map(decode_image, num_parallel_calls=AUTO)\n    \n    #特殊情况，这样更改下\n    test_dataset = load_dataset(test_paths, labeled=False, ordered=True)\n    \n\n    if bool_tta:\n        test_dataset = test_dataset.cache().map(data_aug, num_parallel_calls=AUTO)\n\n    test_dataset = test_dataset.batch(BATCH_SIZE)\n    return test_dataset","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"63ed3af5-ef07-4bd6-8e91-46eb39da94ea","_cell_guid":"bbd9e3db-6950-492d-90e9-39aae9632dcc","trusted":true},"cell_type":"code","source":"#tta时可重复运行这块观察是否多次运行时生成了不同的测试数据\nview_dataset = re_produce_test_dataset(test_paths[:8])\nit = view_dataset.__iter__()\nshow_x= it.next()\ntry:\n    print(show_x.shape)\nexcept:\n    print(show_x[0].shape)\n    show_x=show_x[0]\n    \nplt.figure(figsize=(12, 6))\nfor i in range(8):\n    plt.subplot(2, 4, i+1)\n    plt.imshow(show_x[i])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"45093a15-6f97-4451-9446-fa471ffbec7f","_cell_guid":"98481fec-f2e0-42f4-a544-bfbbdecec7c4","trusted":true},"cell_type":"code","source":"# if special_monitor=='auc':\n#     my_metrics.append(tf.keras.metrics.AUC(name='auc'))\n\n\n#创建模型\ndef get_model():\n    with strategy.scope():\n        base_model =  efn.EfficientNetB0(weights=pre_trained, include_top=False, pooling='avg', input_shape=(img_size, img_size, 3))\n        x = base_model.output\n        predictions = Dense(nb_classes, activation=dense_activation)(x)\n        model = Model(inputs=base_model.input, outputs=predictions)\n\n    if label_smoothing_rate:\n        print('启用label_smoothing')\n        my_loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=label_smoothing_rate)\n    elif bool_focal_loss:\n\n        my_loss = tfa.losses.SigmoidFocalCrossEntropy(reduction=tf.keras.losses.Reduction.AUTO)\n\n    else:\n        my_loss='categorical_crossentropy'\n\n    model.compile(optimizer=tf.keras.optimizers.Adam(lr_if_without_scheduler), \n                  loss=my_loss,\n                  metrics=my_metrics\n                 )\n\n    return model","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"911dda5d-a1cf-4f19-aa63-bcfee6912277","_cell_guid":"90fa49e6-a3be-4b1f-9a8b-3665f34cb1d3","trusted":true},"cell_type":"code","source":"callbacks=[]\nif bool_lr_scheduler:\n    callbacks.append(lr_callback)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ef0ebc6c-45c9-43ef-8348-33138a68ce8f","_cell_guid":"cf8de1c4-3f58-4abd-90e6-c6a67089af43","trusted":true},"cell_type":"code","source":"if cross_validation_folds:\n    probabilities =[]\n    histories = []\n\n    # early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 3)\n    kfold = KFold(cross_validation_folds , shuffle = True)\n    \n    i=1\n    \n    #特殊处理\n    for trn_ind, val_ind in kfold.split(train_paths):\n        # print(trn_ind)\n        # print(val_ind)\n    \n    #for trn_ind, val_ind in kfold.split(train_paths,train_labels):\n        print(); print('#'*25)\n        print('### FOLD',i)\n        print('#'*25)\n        \n        #每轮都应该重置 ModelCheckpoint\n        ch_p1 = ModelCheckpoint(filepath=\"temp_best.h5\", monitor='val_loss', save_weights_only=True,verbose=1,save_best_only=True)\n\n#该功能暂时作废\n#         if special_monitor=='auc': \n#             ch_p1 = ModelCheckpoint(filepath=\"temp_best.h5\", monitor='val_auc', mode='max',save_weights_only=True,verbose=1,save_best_only=True)\n\n        temp_callbacks=callbacks.copy()\n        temp_callbacks.append(ch_p1)\n        \n        trn_paths = np.array(train_paths)[trn_ind]\n        val_paths=np.array(train_paths)[val_ind]\n\n        #特殊处理\n#         trn_labels = train_labels[trn_ind]\n#         val_labels=train_labels[val_ind]\n        trn_labels=None\n        val_labels=None\n        \n        model = get_model()\n        history = model.fit(\n            get_train_dataset(trn_paths,trn_labels), \n            #steps_per_epoch = trn_labels.shape[0]//BATCH_SIZE,\n            \n            #特殊处理下\n            steps_per_epoch = 16465//BATCH_SIZE,\n            \n            epochs = EPOCHS,\n            callbacks = temp_callbacks,\n            validation_data = (get_validation_dataset(val_paths,val_labels)),\n        )\n        \n        i+=1\n        histories.append(history)\n        \n        #用val_loss最小的权重来预测\n        model.load_weights(\"temp_best.h5\")\n        #prob = model.predict(re_produce_test_dataset(test_paths), verbose=1)\n        \n        #特殊处理\n        prob = model.predict(re_produce_test_dataset(test_paths).map(lambda image, idnum: image), verbose=1)\n        \n        probabilities.append(prob)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#画history咯\ndef display_training_curves(training, title, subplot, validation=None):\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    if validation is not None:\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    if validation is not None:\n        ax.legend(['train', 'valid.'])\n    else:\n        ax.legend(['train'])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"913c240c-ff6f-47f2-a477-e98afaa4d612","_cell_guid":"edea1af7-ecb2-4ecf-a1f1-d4d94d78b9f5","trusted":true},"cell_type":"code","source":"# 写开，防止交叉验证时out of memory导致什么都没保存\nif cross_validation_folds:\n    y_pred = np.mean(probabilities,axis =0)\n    \n    \n#然后画画- -\n    for h in range(len(histories)):\n        display_training_curves(histories[h].history['loss'], 'loss', 211, histories[h].history['val_loss'])\n        display_training_curves(histories[h].history['accuracy'], 'accuracy', 212, histories[h].history['val_accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9e397ce4-f9f0-4f4b-ac2f-d227371a94cb","_cell_guid":"bd03afe7-029a-4dca-9571-be71541ad27e","trusted":true},"cell_type":"code","source":"if not cross_validation_folds:\n    \n    model = get_model()\n    \n    #特殊处理\n    train_labels=None\n    \n    history = model.fit(\n        get_train_dataset(train_paths,train_labels), \n        #steps_per_epoch=train_labels.shape[0] // BATCH_SIZE,\n        \n        #特殊处理下\n        steps_per_epoch = 16465//BATCH_SIZE,\n        \n        \n        callbacks=callbacks,\n        epochs=EPOCHS\n    )\n\n\n    if bool_tta:\n        probabilities = []\n        for i in range(tta_times+1):\n            print('TTA Number: ',i,'\\n')\n            test_dataset = re_produce_test_dataset(test_paths)\n            #probabilities.append(model.predict(test_dataset))\n            \n            #特殊处理\n            probabilities.append(model.predict(re_produce_test_dataset(test_paths).map(lambda image, idnum: image), verbose=1))\n        y_pred = np.mean(probabilities,axis =0)\n\n    else:\n        #test_dataset = re_produce_test_dataset(test_paths)\n        #y_pred = model.predict(test_dataset)\n        \n        #特殊处理\n        y_pred = model.predict(re_produce_test_dataset(test_paths).map(lambda image, idnum: image), verbose=1)\n        \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if not cross_validation_folds:\n    display_training_curves(history.history['loss'], 'loss', 211)\n    display_training_curves(history.history['accuracy'], 'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c2553d1e-781e-40ec-bb5a-37098f63ba7f","_cell_guid":"5e6cf9ff-bb63-4e10-857a-00a0b7191434","trusted":true},"cell_type":"code","source":"#针对不同数据不同后处理\npredictions = np.argmax(y_pred, axis=-1)\nprint(predictions)\n\nprint('Generating submission.csv file...')\ntest_ids_ds = re_produce_test_dataset(test_paths).map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(7382))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n!head submission.csv","execution_count":null,"outputs":[]}],"metadata":{"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"}},"nbformat":4,"nbformat_minor":4}