{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.execute_input":"2021-02-23T21:08:04.688068Z","iopub.status.busy":"2021-02-23T21:08:04.687391Z","iopub.status.idle":"2021-02-23T21:08:13.305473Z","shell.execute_reply":"2021-02-23T21:08:13.304746Z"},"papermill":{"duration":8.632056,"end_time":"2021-02-23T21:08:13.305697","exception":false,"start_time":"2021-02-23T21:08:04.673641","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"import numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport tensorflow as tf\nimport re\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nAUTO = tf.data.experimental.AUTOTUNE\nfolds = 5\n\nimage_size = 128  # We'll resize input images to this size\ninput_shape = (image_size, image_size,3)\n\nTEST_FILENAMES = tf.io.gfile.glob('../input/ranzcr-clip-catheter-line-classification/test_tfrecords/*.tfrec') # predictions on this dataset should be submitted for the competition\nprint(TEST_FILENAMES)\n\nbatch_size = 4","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-02-23T21:08:13.324578Z","iopub.status.busy":"2021-02-23T21:08:13.323852Z","iopub.status.idle":"2021-02-23T21:08:43.203991Z","shell.execute_reply":"2021-02-23T21:08:43.202870Z"},"papermill":{"duration":29.891427,"end_time":"2021-02-23T21:08:43.204147","exception":false,"start_time":"2021-02-23T21:08:13.312720","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"import sys\n!pip install ../input/validators\npackage_path = '../input/vitkeras/'\nsys.path.append(package_path)\n\n#test\n#!pip install vit-keras\nfrom vit_keras import vit, utils\n","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-02-23T21:08:43.233947Z","iopub.status.busy":"2021-02-23T21:08:43.233226Z","iopub.status.idle":"2021-02-23T21:08:43.559652Z","shell.execute_reply":"2021-02-23T21:08:43.559105Z"},"papermill":{"duration":0.347676,"end_time":"2021-02-23T21:08:43.559793","exception":false,"start_time":"2021-02-23T21:08:43.212117","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"\nUNLABELED_TFREC_FORMAT = {\n    'image': tf.io.FixedLenFeature([], tf.string),\n    'StudyInstanceUID': tf.io.FixedLenFeature([], tf.string)\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.image.resize(image, [image_size, image_size])\n    image = tf.reshape(image, [image_size, image_size, 3])\n    return image\n\n\ndef read_unlabeled_tfrecord(example):\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['StudyInstanceUID']\n    return image, idnum  # returns a dataset of image(s)\n\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  # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames,\n                                      num_parallel_reads=AUTO)  # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order)  # use data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_unlabeled_tfrecord,\n                          num_parallel_calls=AUTO)  # returns a dataset of (image, label) pairs if labeled = True or (image, id) pair if labeld = False\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    dataset = dataset.prefetch(AUTO)  # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\n","execution_count":null,"outputs":[]},{"metadata":{"execution":{"iopub.execute_input":"2021-02-23T21:08:43.593533Z","iopub.status.busy":"2021-02-23T21:08:43.583198Z","iopub.status.idle":"2021-02-23T21:10:10.135064Z","shell.execute_reply":"2021-02-23T21:10:10.135748Z"},"papermill":{"duration":86.568187,"end_time":"2021-02-23T21:10:10.135995","exception":false,"start_time":"2021-02-23T21:08:43.567808","status":"completed"},"tags":[],"trusted":true},"cell_type":"code","source":"def test():\n    transformer = vit.vit_l32(\n        image_size=image_size,\n        pretrained=False,\n        include_top=False,\n        pretrained_top = False,\n        weights=f'../input/vitweight/fold0vit.h5',\n    )\n\n    model = tf.keras.Sequential([\n        transformer,\n        tf.keras.layers.Dense(11, activation='sigmoid')\n    ])\n\n    print(model)\n    models1=[]\n    models1.append(model)\n    test_ds = get_test_dataset(ordered=True)\n    test_images_ds = test_ds.map(lambda image, idnum: image)\n\n    labels = ['ETT - Abnormal', 'ETT - Borderline',\n              'ETT - Normal', 'NGT - Abnormal', 'NGT - Borderline',\n              'NGT - Incompletely Imaged', 'NGT - Normal', 'CVC - Abnormal',\n              'CVC - Borderline', 'CVC - Normal', 'Swan Ganz Catheter Present']\n    mean = np.average([models1[i].predict(test_images_ds) for i in range(len(models1))], axis=0)\n\n    test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n    submission = pd.DataFrame(mean, columns=labels)\n\n    submission.insert(0, \"StudyInstanceUID\", test_ids, False)\n    submission['StudyInstanceUID'] = submission['StudyInstanceUID'].apply(lambda x: x.rstrip(\".jpg\"))\n    submission.to_csv('submission.csv', index=False)\n\ntest()\n\n","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}