{"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":"#### reference : https://www.kaggle.com/code/dmitrynokhrin/start-with-ensemble-v2","metadata":{}},{"cell_type":"markdown","source":"# Imports and Defines","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport random,os,re\n\nimport matplotlib.pyplot as plt\n\nfrom kaggle_datasets import KaggleDatasets\n\nimport tensorflow as tf\nfrom tensorflow.keras.applications.densenet import DenseNet201\nfrom tensorflow.keras.applications import Xception \nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense\n\nSAMPLE_SUBMISSION_PATH = \"../input/tpu-getting-started/sample_submission.csv\"\nSUBMISSION_PATH = \"submission.csv\"\n\nID = \"id\"\nTARGET = \"label\"\n\nAUTO = tf.data.experimental.AUTOTUNE\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() \nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(\"tpu-getting-started\")\n\nIMAGE_SIZE = [512, 512] # при таком размере графическому процессору не хватит памяти. Используйте TPU\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\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}\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\n\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')\n\nSEED = 2022\ndef seed_everything(seed=SEED):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    \nseed_everything()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-05-08T03:03:14.869350Z","iopub.execute_input":"2022-05-08T03:03:14.869768Z","iopub.status.idle":"2022-05-08T03:03:16.644257Z","shell.execute_reply.started":"2022-05-08T03:03:14.869729Z","shell.execute_reply":"2022-05-08T03:03:16.643467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Model","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3) \n    image = tf.cast(image, tf.float32) / 255.0  \n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) \n    \n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), \n        \"class\": tf.io.FixedLenFeature([], tf.int64),  \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 \n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"id\": tf.io.FixedLenFeature([], tf.string), \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 \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    \n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True)\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_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint('Dataset: {} validation images, {} unlabeled test images'.format(NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\n\ndef get_model(use_model):\n    base_model = use_model(weights='imagenet', \n                      include_top=False, pooling='avg',\n                      input_shape=(*IMAGE_SIZE, 3))\n#     base_model.trainable = False\n    x = base_model.output\n    predictions = Dense(104, activation='softmax')(x)\n    model = Model(inputs=base_model.input, outputs=predictions)\n    model.compile(\n                    optimizer='nadam',\n                    loss = 'sparse_categorical_crossentropy',\n                    metrics=['sparse_categorical_accuracy']\n                 )\n    return model\nwith strategy.scope():    \n    model1 = get_model(DenseNet201)\nmodel1.load_weights(\"/kaggle/input/densenet201-aug-additional-data/my_denceNet_201.h5\")\n\nwith strategy.scope():    \n    model2 = get_model(Xception) \nmodel2.load_weights(\"/kaggle/input/xception-aug-additional-data/my_Xception.h5\") ","metadata":{"execution":{"iopub.status.busy":"2022-05-08T02:58:19.664434Z","iopub.execute_input":"2022-05-08T02:58:19.664865Z","iopub.status.idle":"2022-05-08T02:58:19.685876Z","shell.execute_reply.started":"2022-05-08T02:58:19.664821Z","shell.execute_reply":"2022-05-08T02:58:19.684914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predict Data","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) \nbest_alpha = 0.45\ntest_images_ds = test_ds.map(lambda image, idnum: image)\n\nprobabilities1 = model1.predict(test_images_ds)\nprobabilities2 = model2.predict(test_images_ds)\nprobabilities = best_alpha * probabilities1 + (1 - best_alpha) * probabilities2\npredictions = np.argmax(probabilities, axis=-1)\n\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') \nnp.savetxt(SUBMISSION_PATH, np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n\nsub = pd.read_csv(SUBMISSION_PATH)\nsub.head()","metadata":{"execution":{"iopub.status.busy":"2022-05-08T02:58:39.542883Z","iopub.execute_input":"2022-05-08T02:58:39.543151Z","iopub.status.idle":"2022-05-08T03:02:37.385508Z","shell.execute_reply.started":"2022-05-08T02:58:39.543114Z","shell.execute_reply":"2022-05-08T03:02:37.384699Z"},"trusted":true},"execution_count":null,"outputs":[]}]}