{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"tpu1vmV38","dataSources":[{"sourceId":39272,"databundleVersionId":4629629,"sourceType":"competition"},{"sourceId":7389910,"sourceType":"datasetVersion","datasetId":2803290},{"sourceId":8158186,"sourceType":"datasetVersion","datasetId":4826256},{"sourceId":8158722,"sourceType":"datasetVersion","datasetId":4826662}],"dockerImageVersionId":30685,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"from kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\nuser_credential = user_secrets.get_gcloud_credential()\nuser_secrets.set_tensorflow_credential(user_credential)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-04-21T22:44:40.12489Z","iopub.execute_input":"2024-04-21T22:44:40.125282Z","iopub.status.idle":"2024-04-21T22:44:40.341712Z","shell.execute_reply.started":"2024-04-21T22:44:40.125247Z","shell.execute_reply":"2024-04-21T22:44:40.34084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Install ConvNextV2 Models From Keras CV Attention Models Pip Package\n!pip install -qq /kaggle/input/keras-cv-attention-models/keras_cv_attention_models-1.3.9-py3-none-any.whl","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:44:40.343151Z","iopub.execute_input":"2024-04-21T22:44:40.343425Z","iopub.status.idle":"2024-04-21T22:44:48.609965Z","shell.execute_reply.started":"2024-04-21T22:44:40.343384Z","shell.execute_reply":"2024-04-21T22:44:48.608937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\n# Ignore all warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Ignore specific warnings based on message or category\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\nwarnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n\n# Example to ignore specific warnings based on message content\nwarnings.filterwarnings(\"ignore\", message=\"SetPriority unimplemented for this stream\")","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:44:48.611347Z","iopub.execute_input":"2024-04-21T22:44:48.611629Z","iopub.status.idle":"2024-04-21T22:44:48.616803Z","shell.execute_reply.started":"2024-04-21T22:44:48.611597Z","shell.execute_reply":"2024-04-21T22:44:48.616164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nfrom tqdm import tqdm\nfrom multiprocessing import cpu_count\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.model_selection import train_test_split\nfrom keras_cv_attention_models import convnext\n\nimport os\nimport time\nimport pickle\nimport math\nimport random\nimport sys\nimport cv2\nimport gc\nimport datetime\ntf.compat.v1.enable_eager_execution()\n\nprint(f'Tensorflow Version: {tf.__version__}')\nprint(f'Python Version: {sys.version}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:44:48.618493Z","iopub.execute_input":"2024-04-21T22:44:48.618747Z","iopub.status.idle":"2024-04-21T22:45:08.471385Z","shell.execute_reply.started":"2024-04-21T22:44:48.618721Z","shell.execute_reply":"2024-04-21T22:45:08.470513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"now = datetime.datetime.now().strftime(\"%d-%b-%Y %H-%M-%S\")\nnp.save(now, np.array([now]))","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:08.472472Z","iopub.execute_input":"2024-04-21T22:45:08.473024Z","iopub.status.idle":"2024-04-21T22:45:08.477892Z","shell.execute_reply.started":"2024-04-21T22:45:08.472979Z","shell.execute_reply":"2024-04-21T22:45:08.477144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\ntf.compat.v1.enable_eager_execution()\n# float32 or mixed_float16 (mixed precision: compute float16, variable float32)\n# TPU is fast enough and has enough memory to use float32\npolicy = tf.keras.mixed_precision.Policy('float32')\ntf.keras.mixed_precision.set_global_policy(policy)\n\nprint(f'Compute dtype: {tf.keras.mixed_precision.global_policy().compute_dtype}')\nprint(f'Variable dtype: {tf.keras.mixed_precision.global_policy().variable_dtype}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:08.478766Z","iopub.execute_input":"2024-04-21T22:45:08.479015Z","iopub.status.idle":"2024-04-21T22:45:08.492329Z","shell.execute_reply.started":"2024-04-21T22:45:08.47899Z","shell.execute_reply":"2024-04-21T22:45:08.491569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# MatplotLib Global Settings\nmpl.rcParams.update(mpl.rcParamsDefault)\nmpl.rcParams['xtick.labelsize'] = 16\nmpl.rcParams['ytick.labelsize'] = 16\nmpl.rcParams['axes.labelsize'] = 18\nmpl.rcParams['axes.titlesize'] = 24","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:08.493232Z","iopub.execute_input":"2024-04-21T22:45:08.493467Z","iopub.status.idle":"2024-04-21T22:45:08.503708Z","shell.execute_reply.started":"2024-04-21T22:45:08.493442Z","shell.execute_reply":"2024-04-21T22:45:08.503017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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    print('Running on GPU')\n    TPU = None\n\nif TPU:\n    IS_TPU = True\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    IS_TPU = False\n    STRATEGY = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nN_REPLICAS = STRATEGY.num_replicas_in_sync\nprint(f'N_REPLICAS: {N_REPLICAS}, IS_TPU: {IS_TPU}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:08.504641Z","iopub.execute_input":"2024-04-21T22:45:08.504902Z","iopub.status.idle":"2024-04-21T22:45:18.365534Z","shell.execute_reply.started":"2024-04-21T22:45:08.504876Z","shell.execute_reply":"2024-04-21T22:45:18.364825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SEED = 59\nDEBUG = False\n\n# Image dimensions\nIMG_HEIGHT = 1344\nIMG_WIDTH = 768\nN_CHANNELS = 1\nINPUT_SHAPE = (IMG_HEIGHT, IMG_WIDTH, 1)\nN_SAMPLES_TFRECORDS = 548\n\n# Peak Learning Rate\nLR_MAX = 5e-6 * N_REPLICAS\nWD_RATIO = 0.01\n\nN_WARMUP_EPOCHS = 0\nN_EPOCHS = 10\n\n# Batch size\nBATCH_SIZE = 8 * N_REPLICAS\n\n# Is Interactive Flag and COrresponding Verbosity Method\nIS_INTERACTIVE = os.environ['KAGGLE_KERNEL_RUN_TYPE'] == 'Interactive'\nVERBOSE = 1 if IS_INTERACTIVE else 2\n\n# Tensorflow AUTO flag\nAUTO = tf.data.experimental.AUTOTUNE\n\nprint(f'BATCH_SIZE: {BATCH_SIZE}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.366547Z","iopub.execute_input":"2024-04-21T22:45:18.366833Z","iopub.status.idle":"2024-04-21T22:45:18.372697Z","shell.execute_reply.started":"2024-04-21T22:45:18.366803Z","shell.execute_reply":"2024-04-21T22:45:18.371928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Seed all random number generators\ndef seed_everything(seed=SEED):\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    random.seed(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n\nseed_everything()","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.375523Z","iopub.execute_input":"2024-04-21T22:45:18.375797Z","iopub.status.idle":"2024-04-21T22:45:18.383947Z","shell.execute_reply.started":"2024-04-21T22:45:18.375753Z","shell.execute_reply":"2024-04-21T22:45:18.383148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train DataFrame\ntrain = pd.read_csv('/kaggle/input/rsna-breast-cancer-detection/train.csv')\n\ndisplay(train.head())\ndisplay(train.info())","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.384962Z","iopub.execute_input":"2024-04-21T22:45:18.385212Z","iopub.status.idle":"2024-04-21T22:45:18.532049Z","shell.execute_reply.started":"2024-04-21T22:45:18.385187Z","shell.execute_reply":"2024-04-21T22:45:18.531152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# short Tensorflow randin integer function\ndef tf_rand_int(minval, maxval, dtype=tf.int64):\n    minval = tf.cast(minval, dtype)\n    maxval = tf.cast(maxval, dtype)\n    return tf.random.uniform(shape=(), minval=minval, maxval=maxval, dtype=dtype)\n\n# chance of 1 in k\ndef one_in(k):\n    return 0 == tf_rand_int(0, k)","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.533097Z","iopub.execute_input":"2024-04-21T22:45:18.5334Z","iopub.status.idle":"2024-04-21T22:45:18.538193Z","shell.execute_reply.started":"2024-04-21T22:45:18.533369Z","shell.execute_reply":"2024-04-21T22:45:18.537483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to benchmark the dataset\ndef benchmark_dataset(dataset, num_epochs=3, n_steps_per_epoch=10, bs=BATCH_SIZE):\n    start_time = time.perf_counter()\n    for epoch_num in range(num_epochs):\n        for idx, (inputs, labels) in enumerate(dataset.take(n_steps_per_epoch + 1)):\n            if idx == 0:\n                epoch_start = time.perf_counter()\n            elif idx == 1 and epoch_num == 0:\n                image = inputs['image']\n                print(f'image shape: {image.shape}, labels shape: {labels.shape}, image dtype: {image.dtype}, labels dtype: {labels.dtype}')\n            else:\n                pass\n        \n        epoch_t = time.perf_counter() - epoch_start\n        mean_step_t = round(epoch_t / n_steps_per_epoch * 1000, 1)\n        n_imgs_per_s = int(1 / (mean_step_t / 1000) * bs)\n        print(f'epoch {epoch_num} took: {round(epoch_t, 2)} sec, mean step duration: {mean_step_t}ms, images/s: {n_imgs_per_s}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.539022Z","iopub.execute_input":"2024-04-21T22:45:18.539272Z","iopub.status.idle":"2024-04-21T22:45:18.55232Z","shell.execute_reply.started":"2024-04-21T22:45:18.539246Z","shell.execute_reply":"2024-04-21T22:45:18.551569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plots a batch of images\ndef show_batch(dataset, n_rows=16, n_cols=4):\n    inputs, targets = next(iter(dataset))\n    images = inputs['image'].numpy().squeeze()\n    fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols, figsize=(n_cols*4, n_rows*7))\n    for r in range(n_rows):\n        for c in range(n_cols):\n            idx = r * n_cols + c\n            # Image\n            img = images[idx]\n            axes[r, c].imshow(img)\n            # Target\n            target = targets[idx]\n            axes[r, c].set_title(f'target: {target}', fontsize=16, pad=5)\n        \n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.553208Z","iopub.execute_input":"2024-04-21T22:45:18.553485Z","iopub.status.idle":"2024-04-21T22:45:18.562417Z","shell.execute_reply.started":"2024-04-21T22:45:18.553453Z","shell.execute_reply":"2024-04-21T22:45:18.56171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Decodes the TFRecords\ndef decode_image(record_bytes):\n    features = tf.io.parse_single_example(record_bytes, {\n        'image': tf.io.FixedLenFeature([], tf.string),\n        'target': tf.io.FixedLenFeature([], tf.int64),\n        'patient_id': tf.io.FixedLenFeature([], tf.int64),\n    })\n    \n    # Decode PNG Image\n    image = tf.io.decode_png(features['image'], channels=N_CHANNELS)\n    # Explicit reshape needed for TPU\n    image = tf.reshape(image, [IMG_HEIGHT, IMG_WIDTH, N_CHANNELS])\n\n    target = features['target']\n    \n    return { 'image': image }, target","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.563245Z","iopub.execute_input":"2024-04-21T22:45:18.563525Z","iopub.status.idle":"2024-04-21T22:45:18.572921Z","shell.execute_reply.started":"2024-04-21T22:45:18.56349Z","shell.execute_reply":"2024-04-21T22:45:18.572196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"@tf.function\ndef augment_image(X, y):\n    image = X['image']\n    \n    # Random Brightness\n    image = tf.image.random_brightness(image, 0.10)\n    \n    # Random Contrast\n    image = tf.image.random_contrast(image, 0.90, 1.10)\n    \n    # Random crop image with maximum of 10%\n    ratio = tf.random.uniform([], 0.75, 1.00)\n    img_height_crop = tf.cast(ratio * IMG_HEIGHT, tf.int32)\n    img_width_crop = tf.cast(ratio * IMG_WIDTH, tf.int32)\n    \n    # Random offset for crop\n    img_height_offset = tf_rand_int(0, tf.maximum(1, IMG_HEIGHT - img_height_crop))\n    img_width_offset = 0\n    \n    # Crop And Resize\n    image = tf.slice(image, [img_height_offset, img_width_offset, 0], [img_height_crop, img_width_crop, N_CHANNELS])\n    image = tf.image.resize(image, [IMG_HEIGHT, IMG_WIDTH], method=tf.image.ResizeMethod.BILINEAR)\n    \n    # Clip pixel values in range [0,255] to prevent underflow/overflow\n    image = tf.clip_by_value(image, 0, 255)\n    image = tf.cast(image, tf.uint8)\n        \n    return { 'image': image }, y","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.573736Z","iopub.execute_input":"2024-04-21T22:45:18.573981Z","iopub.status.idle":"2024-04-21T22:45:18.587197Z","shell.execute_reply.started":"2024-04-21T22:45:18.573955Z","shell.execute_reply":"2024-04-21T22:45:18.586574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Undersample majority class (0/negative) by randomly dropping them\ndef undersample_majority(X, y):\n    # Filter 2/3 of negative samples to upsample positive samples by a factor 3\n    return y == 1 or tf.random.uniform([]) > 0.66","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.588002Z","iopub.execute_input":"2024-04-21T22:45:18.588233Z","iopub.status.idle":"2024-04-21T22:45:18.598011Z","shell.execute_reply.started":"2024-04-21T22:45:18.588209Z","shell.execute_reply":"2024-04-21T22:45:18.59738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset1 = tf.io.gfile.glob('/kaggle/input/yolo-cropped-batches/*.tfrecords')\ndataset2 = tf.io.gfile.glob('/kaggle/input/yolo-cropped-batches-2/*.tfrecords')\n\n# Filter out batch_74.tfrecords and select files from 0 to 73 from the first dataset\nselected_dataset1_files = sorted([file_path for file_path in dataset1 if 'batch_74.tfrecords' not in file_path])\n\n# Combine the selected files from dataset 1 with dataset 2\nFNAMES_TRAIN_TFRECORDS = selected_dataset1_files + dataset2\n\n# Define a function to extract the batch number from the file path\ndef extract_batch_number(file_path):\n    start_idx = file_path.find('batch_') + len('batch_')\n    end_idx = file_path.find('.tfrecords')\n    # Convert the substring to an integer and return it\n    return int(file_path[start_idx:end_idx])\n\n# Sort the list using the custom key function\nFNAMES_TRAIN_TFRECORDS = sorted(FNAMES_TRAIN_TFRECORDS, key=extract_batch_number)\nprint(f'Found {len(FNAMES_TRAIN_TFRECORDS)} TFRecords')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.598874Z","iopub.execute_input":"2024-04-21T22:45:18.599107Z","iopub.status.idle":"2024-04-21T22:45:18.651941Z","shell.execute_reply.started":"2024-04-21T22:45:18.599084Z","shell.execute_reply":"2024-04-21T22:45:18.651111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train Test Split\nTFRECORDS_TRAIN, TFRECORDS_VAL = train_test_split(FNAMES_TRAIN_TFRECORDS, train_size=0.80, random_state=SEED, shuffle=True)\nprint(f'# TFRECORDS_TRAIN: {len(TFRECORDS_TRAIN)}, # TFRECORDS_VAL: {len(TFRECORDS_VAL)}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.652812Z","iopub.execute_input":"2024-04-21T22:45:18.653067Z","iopub.status.idle":"2024-04-21T22:45:18.658724Z","shell.execute_reply.started":"2024-04-21T22:45:18.65304Z","shell.execute_reply":"2024-04-21T22:45:18.657956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_dataset(tfrecords, bs=BATCH_SIZE, val=False, debug=True):\n    ignore_order = tf.data.Options()\n    ignore_order.experimental_deterministic = False\n    \n    # Initialize dataset with TFRecords\n    dataset = tf.data.TFRecordDataset(tfrecords, num_parallel_reads=AUTO, compression_type='GZIP')\n    \n    # Decode mapping\n    dataset = dataset.map(decode_image, num_parallel_calls=AUTO)\n\n    if not val:\n        dataset = dataset.filter(undersample_majority)\n        dataset = dataset.map(augment_image, num_parallel_calls=AUTO)\n        dataset = dataset.with_options(ignore_order)\n        if not debug:\n            dataset = dataset.shuffle(1024)\n        dataset = dataset.repeat()        \n\n    dataset = dataset.batch(bs, drop_remainder=not val)\n    dataset = dataset.prefetch(AUTO)\n    \n    return dataset","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.659754Z","iopub.execute_input":"2024-04-21T22:45:18.660228Z","iopub.status.idle":"2024-04-21T22:45:18.673763Z","shell.execute_reply.started":"2024-04-21T22:45:18.660198Z","shell.execute_reply":"2024-04-21T22:45:18.673018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get Train/Validation datasets\ntrain_dataset = get_dataset(TFRECORDS_TRAIN, val=False, debug=False)\nval_dataset = get_dataset(TFRECORDS_VAL, val=True, debug=False)\n\nTRAIN_STEPS_PER_EPOCH = len(TFRECORDS_TRAIN) * N_SAMPLES_TFRECORDS // BATCH_SIZE\nVAL_STEPS_PER_EPOCH = len(TFRECORDS_VAL) * N_SAMPLES_TFRECORDS // BATCH_SIZE\nprint(f'TRAIN_STEPS_PER_EPOCH: {TRAIN_STEPS_PER_EPOCH}, VAL_STEPS_PER_EPOCH: {VAL_STEPS_PER_EPOCH}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:18.674462Z","iopub.execute_input":"2024-04-21T22:45:18.674797Z","iopub.status.idle":"2024-04-21T22:45:19.030738Z","shell.execute_reply.started":"2024-04-21T22:45:18.674767Z","shell.execute_reply":"2024-04-21T22:45:19.029988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Sanity check, image and label statistics\nX_batch, y_batch = next(iter(get_dataset(TFRECORDS_TRAIN, val=False)))\nimage = X_batch['image'].numpy()\nprint(f'image shape: {image.shape}, y_batch shape: {y_batch.shape}')\nprint(f'image dtype: {image.dtype}, y_batch dtype: {y_batch.dtype}')\nprint(f'image min: {image.min():.2f}, max: {image.max():.2f}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:19.031641Z","iopub.execute_input":"2024-04-21T22:45:19.031902Z","iopub.status.idle":"2024-04-21T22:45:19.558805Z","shell.execute_reply.started":"2024-04-21T22:45:19.031876Z","shell.execute_reply":"2024-04-21T22:45:19.557978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Benchmark Dataset\nbenchmark_dataset(get_dataset(TFRECORDS_TRAIN, val=False))","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:19.559798Z","iopub.execute_input":"2024-04-21T22:45:19.560062Z","iopub.status.idle":"2024-04-21T22:45:23.769395Z","shell.execute_reply.started":"2024-04-21T22:45:19.560035Z","shell.execute_reply":"2024-04-21T22:45:23.768532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Show what we will be training on\nshow_batch(get_dataset(TFRECORDS_TRAIN, bs=64, val=False))","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:23.771135Z","iopub.execute_input":"2024-04-21T22:45:23.771405Z","iopub.status.idle":"2024-04-21T22:45:38.991782Z","shell.execute_reply.started":"2024-04-21T22:45:23.771379Z","shell.execute_reply":"2024-04-21T22:45:38.990908Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Label Distribution Train With Undersampled Majority Class\nN = 128\ntrain_labels = []\nfor _, labels in tqdm(get_dataset(TFRECORDS_TRAIN, val=False).take(N), total=N):\n    train_labels += labels.numpy().tolist()\n    \ndisplay(pd.concat((\n        pd.Series(train_labels).value_counts(normalize=True).to_frame('Train Label Ratio'),\n        pd.Series(train_labels).value_counts().to_frame('Train Label Count'),\n    ), axis=1)\n)","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:38.993288Z","iopub.execute_input":"2024-04-21T22:45:38.993572Z","iopub.status.idle":"2024-04-21T22:45:51.745215Z","shell.execute_reply.started":"2024-04-21T22:45:38.993544Z","shell.execute_reply":"2024-04-21T22:45:51.744147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Label Distribution Validation (Unchanged)\nval_labels = []\nfor _, labels in tqdm(get_dataset(TFRECORDS_VAL, val=True), total=VAL_STEPS_PER_EPOCH):\n    val_labels += labels.numpy().tolist()\n    \ndisplay(pd.concat((\n        pd.Series(val_labels).value_counts(normalize=True).to_frame('Val Label Ratio'),\n        pd.Series(val_labels).value_counts().to_frame('Val Label Count'),\n    ), axis=1)\n)","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:51.746555Z","iopub.execute_input":"2024-04-21T22:45:51.746908Z","iopub.status.idle":"2024-04-21T22:45:57.534522Z","shell.execute_reply.started":"2024-04-21T22:45:51.746874Z","shell.execute_reply":"2024-04-21T22:45:57.533714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Tensorflow custom metric is just a conventional class object\nclass pF1(tf.keras.metrics.Metric):\n    # Initialize properties\n    def __init__(self, name='pF1', **kwargs):\n        super(pF1, self).__init__(name=name, **kwargs)\n        self.tc = self.add_weight(name='tc', initializer='zeros')\n        self.tp = self.add_weight(name='tp', initializer='zeros')\n        self.fp = self.add_weight(name='fp', initializer='zeros')\n\n    # Update state called on each batch with true and predicted labels\n    def update_state(self, y_true, y_pred, sample_weight=None):\n        self.tc.assign_add(tf.cast(tf.reduce_sum(y_true), tf.float32))\n        self.tp.assign_add(tf.cast(tf.reduce_sum((y_pred[y_true == 1])), tf.float32))\n        self.fp.assign_add(tf.cast(tf.reduce_sum((y_pred[y_true == 0])), tf.float32))\n\n    # Result function is called to obtain result which is printed in progress bar\n    def result(self):\n        if self.tc == 0 or (self.tp + self.fp) == 0:\n            return 0.0\n        else:\n            precision = self.tp / (self.tp + self.fp)\n            recall = self.tp / (self.tc)\n            return 2 * (precision * recall) / (precision + recall)\n\n    # Reset state is called after each epoch to start fresh each epoch\n    def reset_state(self):\n        self.tc.assign(0)\n        self.tp.assign(0)\n        self.fp.assign(0)","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:57.535586Z","iopub.execute_input":"2024-04-21T22:45:57.535926Z","iopub.status.idle":"2024-04-21T22:45:57.544568Z","shell.execute_reply.started":"2024-04-21T22:45:57.535891Z","shell.execute_reply":"2024-04-21T22:45:57.543923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def normalize(image):\n    # Repeat channels to create 3 channel images required by pretrained ConvNextV2 models\n    image = tf.repeat(image, repeats=3, axis=3)\n    # Cast to float 32\n    image = tf.cast(image, tf.float32)\n    # Normalize with respect to ImageNet mean/std\n    image = tf.keras.applications.imagenet_utils.preprocess_input(image, mode='torch')\n\n    return image","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:57.548843Z","iopub.execute_input":"2024-04-21T22:45:57.549079Z","iopub.status.idle":"2024-04-21T22:45:57.560519Z","shell.execute_reply.started":"2024-04-21T22:45:57.549055Z","shell.execute_reply":"2024-04-21T22:45:57.559927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_model():\n    # Verify Mixed Policy Settings\n    print(f'Compute dtype: {tf.keras.mixed_precision.global_policy().compute_dtype}')\n    print(f'Variable dtype: {tf.keras.mixed_precision.global_policy().variable_dtype}')\n    \n    with STRATEGY.scope():\n        # Set seed for deterministic weights initialization\n        seed_everything()\n        \n        # Inputs, note the names are equal to the dictionary keys in the dataset\n        image = tf.keras.layers.Input(INPUT_SHAPE, name='image', dtype=tf.uint8)\n        \n        # Normalize Input\n        image_norm = normalize(image)\n\n        # CNN Prediction in range [0,1]\n        x = convnext.ConvNeXtV2Tiny(\n            input_shape=(IMG_HEIGHT, IMG_WIDTH, 3),\n            pretrained='imagenet21k-ft1k',\n            num_classes=0,\n        )(image_norm)\n        \n        # Average Pooling BxHxWxC -> BxC\n        x = tf.keras.layers.GlobalAveragePooling2D()(x)\n        # Dropout to prevent Overfitting\n        x = tf.keras.layers.Dropout(0.30)(x)\n        # Output value between [0, 1] using Sigmoid function\n        outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n\n        # We will use the famous AdamW optimizer for fast learning with weight decay\n        optimizer = tfa.optimizers.AdamW(learning_rate=LR_MAX, weight_decay=LR_MAX*WD_RATIO, epsilon=1e-6)\n\n        # Loss\n        loss = tf.keras.losses.BinaryCrossentropy(from_logits=False)\n        \n        # Metrics\n        metrics = [\n            pF1(),\n            tfa.metrics.F1Score(num_classes=1, threshold=0.50),\n            tf.keras.metrics.Precision(),\n            tf.keras.metrics.Recall(),\n            tf.keras.metrics.AUC(),\n            tf.keras.metrics.BinaryAccuracy(),\n        ]\n\n        model = tf.keras.models.Model(inputs=image, outputs=outputs)\n        \n        model.compile(optimizer=optimizer, loss=loss, metrics=metrics)\n\n        return model","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:57.561285Z","iopub.execute_input":"2024-04-21T22:45:57.561516Z","iopub.status.idle":"2024-04-21T22:45:57.571216Z","shell.execute_reply.started":"2024-04-21T22:45:57.561492Z","shell.execute_reply":"2024-04-21T22:45:57.570664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Pretrained File Path: '/kaggle/input/sartorius-training-dataset/model.h5'\ntf.keras.backend.clear_session()\n# enable XLA optmizations\ntf.get_logger().setLevel('ERROR')\ntf.config.optimizer.set_jit(True)\n\nmodel = get_model()","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:45:57.572032Z","iopub.execute_input":"2024-04-21T22:45:57.572272Z","iopub.status.idle":"2024-04-21T22:46:16.363637Z","shell.execute_reply.started":"2024-04-21T22:45:57.572236Z","shell.execute_reply":"2024-04-21T22:46:16.362457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot model summary\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:46:16.364818Z","iopub.execute_input":"2024-04-21T22:46:16.365077Z","iopub.status.idle":"2024-04-21T22:46:16.402917Z","shell.execute_reply.started":"2024-04-21T22:46:16.365051Z","shell.execute_reply":"2024-04-21T22:46:16.401983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Validation metric on initialized model\n_ = model.evaluate(\n        get_dataset(TFRECORDS_VAL, val=True),\n        verbose=VERBOSE,\n        steps=VAL_STEPS_PER_EPOCH,\n    )","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:46:16.403948Z","iopub.execute_input":"2024-04-21T22:46:16.40421Z","iopub.status.idle":"2024-04-21T22:47:23.564103Z","shell.execute_reply.started":"2024-04-21T22:46:16.404185Z","shell.execute_reply":"2024-04-21T22:47:23.562754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train Output Baseline\ntrain_preds = model.predict(\n        get_dataset(TFRECORDS_TRAIN, val=True),\n        verbose=VERBOSE,\n        steps=128,\n    ).squeeze()","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:47:23.567106Z","iopub.execute_input":"2024-04-21T22:47:23.567409Z","iopub.status.idle":"2024-04-21T22:48:16.832827Z","shell.execute_reply.started":"2024-04-21T22:47:23.567378Z","shell.execute_reply":"2024-04-21T22:48:16.831418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Initialized model train predictions: should not be saturated (all 0/1)\ndisplay(pd.Series(train_preds).describe().to_frame('Value').round(2))","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:48:16.835962Z","iopub.execute_input":"2024-04-21T22:48:16.836279Z","iopub.status.idle":"2024-04-21T22:48:16.850816Z","shell.execute_reply.started":"2024-04-21T22:48:16.836248Z","shell.execute_reply":"2024-04-21T22:48:16.849623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Predictions on initialized model, shoudl be random and not saturated (all 0 or  all 1)\nplt.figure(figsize=(15,8))\nplt.title(f'Training Predictions Initialized Model')\npd.Series(train_preds).plot(kind='hist', bins=32)\nplt.xticks(np.arange(0, 1.1, 0.1))\nplt.xlim(0, 1)\nplt.grid()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:48:16.852366Z","iopub.execute_input":"2024-04-21T22:48:16.85294Z","iopub.status.idle":"2024-04-21T22:48:17.118968Z","shell.execute_reply.started":"2024-04-21T22:48:16.852891Z","shell.execute_reply":"2024-04-21T22:48:17.117979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Learning rate scheduler with logaritmic warmup and cosine decay\ndef lrfn(current_step, num_warmup_steps, lr_max, num_cycles=0.50, num_training_steps=N_EPOCHS):\n    \n    if current_step < num_warmup_steps:\n        return lr_max * 0.10 ** (num_warmup_steps - current_step)\n    else:\n        progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps))\n\n        return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))) * lr_max","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:48:17.120203Z","iopub.execute_input":"2024-04-21T22:48:17.120502Z","iopub.status.idle":"2024-04-21T22:48:17.125706Z","shell.execute_reply.started":"2024-04-21T22:48:17.120472Z","shell.execute_reply":"2024-04-21T22:48:17.124921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot the learning rate scheduler\ndef plot_lr_schedule(lr_schedule, epochs):\n    fig = plt.figure(figsize=(20, 10))\n    plt.plot([None] + lr_schedule + [None])\n    # X Labels\n    x = np.arange(1, epochs + 1)\n    x_axis_labels = [i if epochs <= 40 or i % 5 == 0 or i == 1 else None for i in range(1, epochs + 1)]\n    plt.xlim([1, epochs])\n    plt.xticks(x, x_axis_labels) # set tick step to 1 and let x axis start at 1\n    \n    # Increase y-limit for better readability\n    plt.ylim([0, max(lr_schedule) * 1.1])\n    \n    # Title\n    schedule_info = f'start: {lr_schedule[0]:.1E}, max: {max(lr_schedule):.1E}, final: {lr_schedule[-1]:.1E}'\n    plt.title(f'Step Learning Rate Schedule, {schedule_info}', size=18, pad=12)\n    \n    # Plot Learning Rates\n    for x, val in enumerate(lr_schedule):\n        if epochs <= 40 or x % 5 == 0 or x is epochs - 1:\n            if x < len(lr_schedule) - 1:\n                if lr_schedule[x - 1] < val:\n                    ha = 'right'\n                else:\n                    ha = 'left'\n            elif x == 0:\n                ha = 'right'\n            else:\n                ha = 'left'\n            plt.plot(x + 1, val, 'o', color='black');\n            offset_y = (max(lr_schedule) - min(lr_schedule)) * 0.02\n            plt.annotate(f'{val:.1E}', xy=(x + 1, val + offset_y), size=12, ha=ha)\n    \n    plt.xlabel('Epoch', size=16, labelpad=5)\n    plt.ylabel('Learning Rate', size=16, labelpad=5)\n    plt.grid()\n    plt.show()\n\n# Learning rate for encoder\nLR_SCHEDULE = [lrfn(step, num_warmup_steps=N_WARMUP_EPOCHS, lr_max=LR_MAX, num_cycles=0.50) for step in range(N_EPOCHS)]\nplot_lr_schedule(LR_SCHEDULE, epochs=N_EPOCHS)","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:48:17.126605Z","iopub.execute_input":"2024-04-21T22:48:17.126855Z","iopub.status.idle":"2024-04-21T22:48:17.420589Z","shell.execute_reply.started":"2024-04-21T22:48:17.126831Z","shell.execute_reply":"2024-04-21T22:48:17.419437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Learning Rate Callback\nlr_callback = tf.keras.callbacks.LearningRateScheduler(lambda step: LR_SCHEDULE[step], verbose=0)","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:48:17.421809Z","iopub.execute_input":"2024-04-21T22:48:17.422119Z","iopub.status.idle":"2024-04-21T22:48:17.426437Z","shell.execute_reply.started":"2024-04-21T22:48:17.422076Z","shell.execute_reply":"2024-04-21T22:48:17.425586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Tensorflow Learning Rate Scheduler does not update weight decay, need to do it manually in a custom callback\nclass WeightDecayCallback(tf.keras.callbacks.Callback):\n    def __init__(self, wd_ratio=WD_RATIO):\n        self.step_counter = 0\n        self.wd_ratio = wd_ratio\n    \n    def on_epoch_begin(self, epoch, logs=None):\n        model.optimizer.weight_decay = model.optimizer.learning_rate * self.wd_ratio\n        print(f'learning rate: {model.optimizer.learning_rate.numpy():.2e}, weight decay: {model.optimizer.weight_decay.numpy():.2e}')","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:48:17.427362Z","iopub.execute_input":"2024-04-21T22:48:17.427597Z","iopub.status.idle":"2024-04-21T22:48:17.437357Z","shell.execute_reply.started":"2024-04-21T22:48:17.427572Z","shell.execute_reply":"2024-04-21T22:48:17.436539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train model on TPU!\nhistory = model.fit(\n        train_dataset,\n        steps_per_epoch = TRAIN_STEPS_PER_EPOCH,\n        validation_data = val_dataset,\n        epochs = N_EPOCHS,\n        verbose = VERBOSE,\n        callbacks = [\n            lr_callback,\n            WeightDecayCallback(),\n        ],\n        class_weight = {\n            0: 1.0,\n            1: 5.0,\n        },\n    )","metadata":{"execution":{"iopub.status.busy":"2024-04-21T22:48:17.438263Z","iopub.execute_input":"2024-04-21T22:48:17.438501Z","iopub.status.idle":"2024-04-22T00:04:03.248454Z","shell.execute_reply.started":"2024-04-21T22:48:17.438477Z","shell.execute_reply":"2024-04-22T00:04:03.247159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save model weights for inference\nmodel.save_weights('model.h5')","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:04:03.251533Z","iopub.execute_input":"2024-04-22T00:04:03.251981Z","iopub.status.idle":"2024-04-22T00:04:03.73101Z","shell.execute_reply.started":"2024-04-22T00:04:03.251946Z","shell.execute_reply":"2024-04-22T00:04:03.729895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get true labels and predictions for validation set\ny_true_val = []\ny_pred_val = []\nfor X_batch, y_batch in tqdm(get_dataset(TFRECORDS_VAL, val=True), total=VAL_STEPS_PER_EPOCH):\n    y_true_val += y_batch.numpy().tolist()\n    y_pred_val += model.predict_on_batch(X_batch).squeeze().tolist()","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:04:03.73213Z","iopub.execute_input":"2024-04-22T00:04:03.732388Z","iopub.status.idle":"2024-04-22T00:07:03.103027Z","shell.execute_reply.started":"2024-04-22T00:04:03.732363Z","shell.execute_reply":"2024-04-22T00:07:03.101959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# source: https://www.kaggle.com/code/sohier/probabilistic-f-score\n# Competition Leaderboard Metric\ndef pfbeta(labels, predictions, beta=1):\n    y_true_count = 0\n    ctp = 0\n    cfp = 0\n\n    for idx in range(len(labels)):\n        prediction = min(max(predictions[idx], 0), 1)\n        if (labels[idx]):\n            y_true_count += 1\n            ctp += prediction\n        else:\n            cfp += prediction\n\n    beta_squared = beta * beta\n    c_precision = ctp / (ctp + cfp)\n    c_recall = ctp / y_true_count\n    if (c_precision > 0 and c_recall > 0):\n        result = (1 + beta_squared) * (c_precision * c_recall) / (beta_squared * c_precision + c_recall)\n        return result\n    else:\n        return 0","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:03.104935Z","iopub.execute_input":"2024-04-22T00:07:03.105245Z","iopub.status.idle":"2024-04-22T00:07:03.111934Z","shell.execute_reply.started":"2024-04-22T00:07:03.105214Z","shell.execute_reply":"2024-04-22T00:07:03.111072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot pF1 by threshold plot to find best threshold\npf1_by_threshold = []\nthresholds = np.arange(0, 1.01, 0.01)\nfor t in tqdm(thresholds):\n    # Compute pF1 for each threshold\n    pf1_by_threshold.append(\n        pfbeta(y_true_val, y_pred_val > t)\n    )\n    \nplt.figure(figsize=(15,8))\nplt.title('F1 By Threshold', size=24)\nplt.plot(pf1_by_threshold, label='F1 Score')\n\n# Best threshold and pF1 score\narg_max = np.argmax(pf1_by_threshold)\nval_max = np.max(pf1_by_threshold)\nthreshold_best = thresholds[arg_max]\nplt.scatter(arg_max, val_max, color='red', label=f'Best Threshold {threshold_best:.2f}, pF1 Score: {val_max:.2f}')\n\n# Plot pF1 by Threshold\nplt.xticks(np.arange(0, 110, 10), [f'{t:.2f}' for t in np.arange(0, 1.1, 0.1)])\nplt.yticks(np.arange(0, 1.1, 0.1))\nplt.xlim(0, 100)\nplt.ylim(0, 1)\nplt.xlabel('Threshold')\nplt.ylabel('pF1 Score')\nplt.legend(fontsize=12)\nplt.grid()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:03.112784Z","iopub.execute_input":"2024-04-22T00:07:03.113037Z","iopub.status.idle":"2024-04-22T00:07:07.264156Z","shell.execute_reply.started":"2024-04-22T00:07:03.113009Z","shell.execute_reply":"2024-04-22T00:07:07.263117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_history_metric(metric, f_best=np.argmax, ylim=None, yscale=None, yticks=None):\n    plt.figure(figsize=(20, 10))\n    \n    values = history.history[metric]\n    N_EPOCHS = len(values)\n    val = 'val' in ''.join(history.history.keys())\n    # Epoch Ticks\n    if N_EPOCHS <= 20:\n        x = np.arange(1, N_EPOCHS + 1)\n    else:\n        x = [1, 5] + [10 + 5 * idx for idx in range((N_EPOCHS - 10) // 5 + 1)]\n\n    x_ticks = np.arange(1, N_EPOCHS+1)\n\n    # Validation\n    if val:\n        val_values = history.history[f'val_{metric}']\n        val_argmin = f_best(val_values)\n        plt.plot(x_ticks, val_values, label=f'val')\n\n    # summarize history for accuracy\n    plt.plot(x_ticks, values, label=f'train')\n    argmin = f_best(values)\n    plt.scatter(argmin + 1, values[argmin], color='red', s=75, marker='o', label=f'train_best')\n    if val:\n        plt.scatter(val_argmin + 1, val_values[val_argmin], color='purple', s=75, marker='o', label=f'val_best')\n\n    plt.title(f'Model {metric}', fontsize=24, pad=10)\n    plt.ylabel(metric, fontsize=20, labelpad=10)\n\n    if ylim:\n        plt.ylim(ylim)\n\n    if yscale is not None:\n        plt.yscale(yscale)\n        \n    if yticks is not None:\n        plt.yticks(yticks, fontsize=16)\n\n    plt.xlabel('epoch', fontsize=20, labelpad=10)        \n    plt.tick_params(axis='x', labelsize=8)\n    plt.xticks(x, fontsize=16) # set tick step to 1 and let x axis start at 1\n    plt.yticks(fontsize=16)\n    \n    plt.legend(prop={'size': 10})\n    plt.grid()\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:07.265338Z","iopub.execute_input":"2024-04-22T00:07:07.265644Z","iopub.status.idle":"2024-04-22T00:07:07.276877Z","shell.execute_reply.started":"2024-04-22T00:07:07.265614Z","shell.execute_reply":"2024-04-22T00:07:07.276049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_history_metric('loss', f_best=np.argmin)","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:07.277779Z","iopub.execute_input":"2024-04-22T00:07:07.278037Z","iopub.status.idle":"2024-04-22T00:07:07.586413Z","shell.execute_reply.started":"2024-04-22T00:07:07.27801Z","shell.execute_reply":"2024-04-22T00:07:07.585263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_history_metric('pF1', ylim=[0,1], yticks=np.arange(0.0, 1.1, 0.1))","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:07.587546Z","iopub.execute_input":"2024-04-22T00:07:07.588292Z","iopub.status.idle":"2024-04-22T00:07:07.889427Z","shell.execute_reply.started":"2024-04-22T00:07:07.588249Z","shell.execute_reply":"2024-04-22T00:07:07.888443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_history_metric('f1_score', ylim=[0,1], yticks=np.arange(0.0, 1.1, 0.1))","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:07.890472Z","iopub.execute_input":"2024-04-22T00:07:07.890758Z","iopub.status.idle":"2024-04-22T00:07:08.198209Z","shell.execute_reply.started":"2024-04-22T00:07:07.890731Z","shell.execute_reply":"2024-04-22T00:07:08.197225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_history_metric('precision', ylim=[0,1], yticks=np.arange(0.0, 1.1, 0.1))","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:08.199316Z","iopub.execute_input":"2024-04-22T00:07:08.199604Z","iopub.status.idle":"2024-04-22T00:07:08.487845Z","shell.execute_reply.started":"2024-04-22T00:07:08.199574Z","shell.execute_reply":"2024-04-22T00:07:08.486889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_history_metric('recall', ylim=[0,1], yticks=np.arange(0.0, 1.1, 0.1))","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:08.488996Z","iopub.execute_input":"2024-04-22T00:07:08.48931Z","iopub.status.idle":"2024-04-22T00:07:08.77285Z","shell.execute_reply.started":"2024-04-22T00:07:08.489272Z","shell.execute_reply":"2024-04-22T00:07:08.771886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_history_metric('auc', ylim=[0,1], yticks=np.arange(0.0, 1.1, 0.1))","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:08.773839Z","iopub.execute_input":"2024-04-22T00:07:08.774097Z","iopub.status.idle":"2024-04-22T00:07:09.040818Z","shell.execute_reply.started":"2024-04-22T00:07:08.774071Z","shell.execute_reply":"2024-04-22T00:07:09.039873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_history_metric('binary_accuracy', ylim=[0,1], yticks=np.arange(0.0, 1.1, 0.1))","metadata":{"execution":{"iopub.status.busy":"2024-04-22T00:07:09.041905Z","iopub.execute_input":"2024-04-22T00:07:09.042179Z","iopub.status.idle":"2024-04-22T00:07:09.332918Z","shell.execute_reply.started":"2024-04-22T00:07:09.04215Z","shell.execute_reply":"2024-04-22T00:07:09.331974Z"},"trusted":true},"execution_count":null,"outputs":[]}]}