{"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":"# Transfer Learning with TPU","metadata":{}},{"cell_type":"code","source":"# Import libraries\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.data.experimental import AUTOTUNE\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.applications import ResNet152V2, InceptionResNetV2\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Input, Dense, GlobalAveragePooling2D, MaxPooling2D\nfrom tensorflow.keras.layers import BatchNormalization, Dropout\nfrom tensorflow.keras.optimizers import Adam, SGD\nfrom tensorflow import keras\n\nfrom kaggle_datasets import KaggleDatasets","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:44.192013Z","iopub.execute_input":"2023-04-13T08:20:44.192634Z","iopub.status.idle":"2023-04-13T08:20:54.362584Z","shell.execute_reply.started":"2023-04-13T08:20:44.192596Z","shell.execute_reply":"2023-04-13T08:20:54.361311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Detect TPU, return appropriate distribution strategy\n\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  \n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:54.364294Z","iopub.execute_input":"2023-04-13T08:20:54.364890Z","iopub.status.idle":"2023-04-13T08:20:58.876816Z","shell.execute_reply.started":"2023-04-13T08:20:54.364858Z","shell.execute_reply":"2023-04-13T08:20:58.875304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get GCS path and select the file with 224x224 images\n\ngcs_ds_path = KaggleDatasets().get_gcs_path('tpu-getting-started')\ngcs_path = gcs_ds_path + '/tfrecords-jpeg-224x224'","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:58.878183Z","iopub.execute_input":"2023-04-13T08:20:58.878552Z","iopub.status.idle":"2023-04-13T08:20:59.182401Z","shell.execute_reply.started":"2023-04-13T08:20:58.878511Z","shell.execute_reply":"2023-04-13T08:20:59.181542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set parameters\n\nBUFFER_SIZE = 60000\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n# BATCH_SIZE = 4\nIMAGE_SIZE = [224, 224]\nHEIGHT = 224\nWIDTH = 224\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\n# EPOCHS = 4\nEPOCHS = 20\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:59.184871Z","iopub.execute_input":"2023-04-13T08:20:59.185499Z","iopub.status.idle":"2023-04-13T08:20:59.192304Z","shell.execute_reply.started":"2023-04-13T08:20:59.185456Z","shell.execute_reply":"2023-04-13T08:20:59.190798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the path to all the files within the tfrecords-jpeg-224x224 folder\n\ntraining_filepath = tf.io.gfile.glob(gcs_path + '/train/*.tfrec')\nvalidation_filepath = tf.io.gfile.glob(gcs_path + '/val/*.tfrec')\ntest_filepath = tf.io.gfile.glob(gcs_path + '/test/*.tfrec') ","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:59.194018Z","iopub.execute_input":"2023-04-13T08:20:59.194403Z","iopub.status.idle":"2023-04-13T08:20:59.326538Z","shell.execute_reply.started":"2023-04-13T08:20:59.194364Z","shell.execute_reply":"2023-04-13T08:20:59.325362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load TFRecord file from the folder as bytes\n\nraw_training_dataset = tf.data.TFRecordDataset(training_filepath)\nraw_validation_dataset = tf.data.TFRecordDataset(validation_filepath)\nraw_test_dataset = tf.data.TFRecordDataset(test_filepath)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:59.328216Z","iopub.execute_input":"2023-04-13T08:20:59.328879Z","iopub.status.idle":"2023-04-13T08:20:59.372161Z","shell.execute_reply.started":"2023-04-13T08:20:59.328829Z","shell.execute_reply":"2023-04-13T08:20:59.370300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a dictionary describing the features\n\nlabeled_feature_description = {\n    'class': tf.io.FixedLenFeature([], tf.int64),\n    'image': tf.io.FixedLenFeature([], tf.string)\n}\n\nunlabeled_feature_description = {\n    'id': tf.io.FixedLenFeature([], tf.string),\n    'image': tf.io.FixedLenFeature([], tf.string)\n}","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:59.374580Z","iopub.execute_input":"2023-04-13T08:20:59.375522Z","iopub.status.idle":"2023-04-13T08:20:59.382270Z","shell.execute_reply.started":"2023-04-13T08:20:59.375474Z","shell.execute_reply":"2023-04-13T08:20:59.381140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Class name of flowers\n\nCLASSES = [\n    'pink primrose',        'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',      'wild geranium',         # 00-04\n    'tiger lily',           'moon orchid',               'bird of paradise', 'monkshood',      'globe thistle',         # 05-09\n    'snapdragon',           \"colt's foot\",               'king protea',      'spear thistle',  'yellow iris',           # 10-14\n    'globe-flower',         'purple coneflower',         'peruvian lily',    'balloon flower', 'giant white arum lily', # 15-19\n    'fire lily',            'pincushion flower',         'fritillary',       'red ginger',     'grape hyacinth',        # 20-24\n    'corn poppy',           'prince of wales feathers',  'stemless gentian', 'artichoke',      'sweet william',         # 25-29\n    'carnation',            'garden phlox',              'love in the mist', 'cosmos',         'alpine sea holly',      # 30-34\n    'ruby-lipped cattleya', 'cape flower',               'great masterwort', 'siam tulip',     'lenten rose',           # 35-39\n    'barberton daisy',      'daffodil',                  'sword lily',       'poinsettia',     'bolero deep blue',      # 40-44\n    'wallflower',           'marigold',                  'buttercup',        'daisy',          'common dandelion',      # 45-49\n    'petunia',              'wild pansy',                'primula',          'sunflower',      'lilac hibiscus',        # 50-54\n    'bishop of llandaff',   'gaura',                     'geranium',         'orange dahlia',  'pink-yellow dahlia',    # 55-59\n    'cautleya spicata',     'japanese anemone',          'black-eyed susan', 'silverbush',     'californian poppy',     # 60-64\n    'osteospermum',         'spring crocus',             'iris',             'windflower',     'tree poppy',            # 65-69\n    'gazania',              'azalea',                    'water lily',       'rose',           'thorn apple',           # 70-74\n    'morning glory',        'passion flower',            'lotus',            'toad lily',      'anthurium',             # 75-79\n    'frangipani',           'clematis',                  'hibiscus',         'columbine',      'desert-rose',           # 80-84\n    'tree mallow',          'magnolia',                  'cyclamen ',        'watercress',     'canna lily',            # 85-89\n    'hippeastrum ',         'bee balm',                  'pink quill',       'foxglove',       'bougainvillea',         # 90-94\n    'camellia',             'mallow',                    'mexican petunia',  'bromelia',       'blanket flower',        # 95-99\n    'trumpet creeper',      'blackberry lily',           'common tulip',     'wild rose'                                #100-103\n]","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:59.384617Z","iopub.execute_input":"2023-04-13T08:20:59.385139Z","iopub.status.idle":"2023-04-13T08:20:59.396977Z","shell.execute_reply.started":"2023-04-13T08:20:59.385100Z","shell.execute_reply":"2023-04-13T08:20:59.395367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a function to read and extract images from dataset\n\ndef _parse_labeled_image_function(example_proto):\n    example = tf.io.parse_single_example(example_proto, labeled_feature_description)\n    image = tf.io.decode_jpeg(example['image'])\n    image = tf.cast(image, tf.float32) / 255.\n    image = tf.image.resize(image, IMAGE_SIZE)\n    label = tf.cast(example['class'], tf.int32)\n    return image, label\n\ndef _parse_unlabeled_image_function(example_proto):\n    example = tf.io.parse_single_example(example_proto, unlabeled_feature_description)\n    image = tf.io.decode_jpeg(example['image'])\n    image = tf.cast(image, tf.float32) / 255.\n    image = tf.image.resize(image, IMAGE_SIZE)\n    idnum = example['id']\n    return image, idnum","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:59.398599Z","iopub.execute_input":"2023-04-13T08:20:59.398983Z","iopub.status.idle":"2023-04-13T08:20:59.415022Z","shell.execute_reply.started":"2023-04-13T08:20:59.398944Z","shell.execute_reply":"2023-04-13T08:20:59.413139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Parse and extract images\n\n# Parse labeled images, shuffle and batch\ntraining_dataset = (\n    raw_training_dataset\n    .map(_parse_labeled_image_function)\n    .repeat()\n    .shuffle(BUFFER_SIZE)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTOTUNE)\n)\n\n# Parse unlabeled images and batch\nvalidation_dataset = (\n    raw_validation_dataset\n    .map(_parse_labeled_image_function)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTOTUNE)\n)\n\n# Parse unlabeled images and batch\ntest_dataset = (\n    raw_test_dataset\n    .map(_parse_unlabeled_image_function)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTOTUNE)\n)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:59.418666Z","iopub.execute_input":"2023-04-13T08:20:59.418983Z","iopub.status.idle":"2023-04-13T08:20:59.612432Z","shell.execute_reply.started":"2023-04-13T08:20:59.418954Z","shell.execute_reply":"2023-04-13T08:20:59.610567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display images in a 5x5 grid\n\nimage_batch, label_batch = next(iter(training_dataset))\n\ndef display_images(image_batch, label_batch):\n    plt.figure(figsize = [20,12])\n    for i in range(25):\n        plt.subplot(5,5,i+1)\n        plt.imshow(image_batch[i])\n        plt.title(CLASSES[label_batch[i].numpy()])\n        plt.axis('off')\n    plt.show()\n\ndisplay_images(image_batch, label_batch)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:20:59.613983Z","iopub.execute_input":"2023-04-13T08:20:59.614398Z","iopub.status.idle":"2023-04-13T08:21:22.191587Z","shell.execute_reply.started":"2023-04-13T08:20:59.614359Z","shell.execute_reply":"2023-04-13T08:21:22.189843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a function to augment brightness, contrast, flip and crop images\n\ndef augment_image(image, label):\n    \n    # Add 10px padding and random crop\n    image = tf.image.resize_with_crop_or_pad(image, HEIGHT+10, WIDTH+10)\n    image = tf.image.random_crop(image, size=[*IMAGE_SIZE, 3])\n    \n    # Random flip\n    image = tf.image.random_flip_left_right(image)\n    \n    # Random brightness\n    image = tf.image.random_brightness(image, 0.2)\n    \n    # Random contrast \n    image = tf.image.random_contrast(image, lower=0.8, upper=1.2)\n    \n    # Random saturation\n    image = tf.image.random_saturation(image, lower=0.8, upper=1.2)\n    \n    # add\n    image = tf.image.random_hue(image, max_delta=0.2)\n    \n    return image, label","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:42:35.612069Z","iopub.execute_input":"2023-04-13T08:42:35.612544Z","iopub.status.idle":"2023-04-13T08:42:35.622056Z","shell.execute_reply.started":"2023-04-13T08:42:35.612501Z","shell.execute_reply":"2023-04-13T08:42:35.620867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Parse unlabeled images, augment, shuffle and batch\n\ntraining_dataset_augmented = (\n    raw_training_dataset\n    .map(_parse_labeled_image_function)\n    .map(augment_image)\n    .repeat()\n    .shuffle(BUFFER_SIZE)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTOTUNE)\n)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:21:22.203562Z","iopub.execute_input":"2023-04-13T08:21:22.204582Z","iopub.status.idle":"2023-04-13T08:21:22.443295Z","shell.execute_reply.started":"2023-04-13T08:21:22.204543Z","shell.execute_reply":"2023-04-13T08:21:22.441511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display images in a 5x5 grid\n\nimage_batch_augmented, label_batch_augmented = next(iter(training_dataset_augmented))\n\ndisplay_images(image_batch_augmented, label_batch_augmented)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:21:22.445330Z","iopub.execute_input":"2023-04-13T08:21:22.445759Z","iopub.status.idle":"2023-04-13T08:22:42.466781Z","shell.execute_reply.started":"2023-04-13T08:21:22.445720Z","shell.execute_reply":"2023-04-13T08:22:42.465250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a function to build the model\n\ndef build_model():\n    inputs = Input(shape=(HEIGHT, WIDTH, 3))\n    \n    model = ResNet152V2(include_top=False, input_tensor=inputs, weights=\"imagenet\")\n#     model = InceptionResNetV2(include_top=False, input_tensor=inputs, weights=\"imagenet\")\n\n    # Freeze the pretrained weights\n    model.trainable = False\n\n    # Rebuild top\n    x = GlobalAveragePooling2D()(model.output)\n    x = BatchNormalization()(x)\n#     x = Dropout(0.2)(x)\n    x = Dropout(0.3)(x)\n    outputs = Dense(104, activation=\"softmax\")(x)\n\n    # Compile\n    model = Model(inputs, outputs)\n    model.compile(optimizer=Adam(learning_rate=1e-2), \n                  loss=\"sparse_categorical_crossentropy\", \n                  metrics=[\"sparse_categorical_accuracy\"])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:22:42.468435Z","iopub.execute_input":"2023-04-13T08:22:42.468783Z","iopub.status.idle":"2023-04-13T08:22:42.477188Z","shell.execute_reply.started":"2023-04-13T08:22:42.468749Z","shell.execute_reply":"2023-04-13T08:22:42.475498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\n\nwith strategy.scope():\n    model = build_model()\n    \ncallbacks = [\n    keras.callbacks.ModelCheckpoint(filepath=\"feature_extraction.keras\",\n                                    save_best_only=True,\n                                    monitor=\"val_loss\"),\n    keras.callbacks.EarlyStopping(monitor=\"val_sparse_categorical_accuracy\",\n                                 patience=2)\n]\n\nhist = model.fit(training_dataset_augmented, \n                 epochs=EPOCHS*2, \n                 validation_data=validation_dataset, \n                 callbacks=callbacks,\n                 steps_per_epoch=STEPS_PER_EPOCH)\n# hist = model.fit(training_dataset_augmented, \n#                  epochs=EPOCHS*2, \n#                  validation_data=validation_dataset, \n#                  callbacks=callbacks\n#                 )","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:22:42.478559Z","iopub.execute_input":"2023-04-13T08:22:42.478883Z","iopub.status.idle":"2023-04-13T08:31:35.486359Z","shell.execute_reply.started":"2023-04-13T08:22:42.478848Z","shell.execute_reply":"2023-04-13T08:31:35.483995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist.history","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:31:35.490279Z","iopub.execute_input":"2023-04-13T08:31:35.490634Z","iopub.status.idle":"2023-04-13T08:31:35.504368Z","shell.execute_reply.started":"2023-04-13T08:31:35.490598Z","shell.execute_reply":"2023-04-13T08:31:35.502166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = hist.history[\"sparse_categorical_accuracy\"]\nval_acc = hist.history[\"val_sparse_categorical_accuracy\"]\nloss = hist.history[\"loss\"]\nval_loss = hist.history[\"val_loss\"]\nepochs = range(1, len(acc) + 1)\nplt.plot(epochs, acc, \"bo\", label=\"Training accuracy\")\nplt.plot(epochs, val_acc, \"b\", label=\"Validation accuracy\")\nplt.title(\"Training and Validation accuracy\")\nplt.legend()\nplt.figure()\nplt.plot(epochs, loss, \"bo\", label=\"Training loss\")\nplt.plot(epochs, val_loss, \"b\", label=\"Validation loss\")\nplt.title(\"Training and Validation loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:31:35.507242Z","iopub.execute_input":"2023-04-13T08:31:35.507820Z","iopub.status.idle":"2023-04-13T08:31:35.892802Z","shell.execute_reply.started":"2023-04-13T08:31:35.507767Z","shell.execute_reply":"2023-04-13T08:31:35.890935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a function to unfreeze the model the top 20 layers\n# But, we'll keep BatchNormalization layers frozen\n\ndef unfreeze_model(model):\n    for layer in model.layers[-20:]:\n        if not isinstance(layer, BatchNormalization):\n            layer.trainable = True\n\n    model.compile(optimizer=Adam(learning_rate=1e-4), \n                  loss=\"sparse_categorical_crossentropy\", \n                  metrics=[\"sparse_categorical_accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:31:35.895022Z","iopub.execute_input":"2023-04-13T08:31:35.895603Z","iopub.status.idle":"2023-04-13T08:31:35.902716Z","shell.execute_reply.started":"2023-04-13T08:31:35.895564Z","shell.execute_reply":"2023-04-13T08:31:35.901209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Unfreeze and train the model\n\nunfreeze_model(model)\n\nhist = model.fit(training_dataset_augmented, \n                 epochs=EPOCHS, \n                 validation_data=validation_dataset, \n                 callbacks=callbacks,\n                 steps_per_epoch=STEPS_PER_EPOCH)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:31:35.904527Z","iopub.execute_input":"2023-04-13T08:31:35.904889Z","iopub.status.idle":"2023-04-13T08:36:28.965846Z","shell.execute_reply.started":"2023-04-13T08:31:35.904855Z","shell.execute_reply":"2023-04-13T08:36:28.964441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = hist.history[\"sparse_categorical_accuracy\"]\nval_acc = hist.history[\"val_sparse_categorical_accuracy\"]\nloss = hist.history[\"loss\"]\nval_loss = hist.history[\"val_loss\"]\nepochs = range(1, len(acc) + 1)\nplt.plot(epochs, acc, \"bo\", label=\"Training accuracy\")\nplt.plot(epochs, val_acc, \"b\", label=\"Validation accuracy\")\nplt.title(\"Training and Validation accuracy\")\nplt.legend()\nplt.figure()\nplt.plot(epochs, loss, \"bo\", label=\"Training loss\")\nplt.plot(epochs, val_loss, \"b\", label=\"Validation loss\")\nplt.title(\"Training and Validation loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:36:28.969756Z","iopub.execute_input":"2023-04-13T08:36:28.970280Z","iopub.status.idle":"2023-04-13T08:36:29.308311Z","shell.execute_reply.started":"2023-04-13T08:36:28.970231Z","shell.execute_reply":"2023-04-13T08:36:29.307155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Predict images from test set\n\ntest_images = test_dataset.map(lambda image, idnum: image)\nprob = model.predict(test_images)\npred = np.argmax(prob, axis=-1)\nprint(pred)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:36:29.309424Z","iopub.execute_input":"2023-04-13T08:36:29.309911Z","iopub.status.idle":"2023-04-13T08:36:58.468388Z","shell.execute_reply.started":"2023-04-13T08:36:29.309884Z","shell.execute_reply":"2023-04-13T08:36:58.466598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Prepare file for submission\n\ntest_ids_ds = test_dataset.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n# np.savetxt(\n#     '/kaggle/working/submission.csv',\n#     np.rec.fromarrays([test_ids, pred]),\n#     fmt=['%s', '%d'],\n#     delimiter=',',\n#     header='id,label',\n#     comments='',\n# )","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:36:58.470873Z","iopub.execute_input":"2023-04-13T08:36:58.471396Z","iopub.status.idle":"2023-04-13T08:37:00.162850Z","shell.execute_reply.started":"2023-04-13T08:36:58.471348Z","shell.execute_reply":"2023-04-13T08:37:00.161110Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dim2list = [[test_ids[i], pred[i]] for i in range(len(test_ids))]\ndf = pd.DataFrame(dim2list, columns=['id', 'label'])\ndf.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-04-13T08:37:00.165443Z","iopub.execute_input":"2023-04-13T08:37:00.165923Z","iopub.status.idle":"2023-04-13T08:37:00.207858Z","shell.execute_reply.started":"2023-04-13T08:37:00.165882Z","shell.execute_reply":"2023-04-13T08:37:00.206597Z"},"trusted":true},"execution_count":null,"outputs":[]}]}