{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "7d5f265e-407a-40bd-92fb-a652091fd7ea", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "importing modules\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Detected kernel version 4.18.0, which is below the recommended minimum of 5.5.0; this can cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "LOCAL RANK 0\n", "PID of this process = 1915809\n", "device: cuda\n", "Distributed environment: DistributedType.NO\n", "Num processes: 1\n", "Process index: 0\n", "Local process index: 0\n", "Device: cuda\n", "\n", "Mixed precision type: fp16\n", "\n", "distributed = False num_devices = 1 local rank = 0 world size = 1\n" ] } ], "source": [ "print('importing modules')\n", "import os\n", "import sys\n", "import json\n", "import argparse\n", "import numpy as np\n", "import math\n", "from einops import rearrange\n", "import time\n", "import random\n", "import string\n", "import h5py\n", "from tqdm import tqdm\n", "import webdataset as wds\n", "\n", "import matplotlib.pyplot as plt\n", "import torch\n", "import torch.nn as nn\n", "from torchvision import transforms\n", "from accelerate import Accelerator, DeepSpeedPlugin\n", "\n", "from generative_models.sgm.modules.encoders.modules import FrozenOpenCLIPImageEmbedder\n", "from models import GNet8_Encoder\n", "\n", "# tf32 data type is faster than standard float32\n", "torch.backends.cuda.matmul.allow_tf32 = True\n", "\n", "# custom functions #\n", "import utils\n", "\n", "### Multi-GPU config ###\n", "local_rank = os.getenv('RANK')\n", "if local_rank is None: \n", " local_rank = 0\n", "else:\n", " local_rank = int(local_rank)\n", "print(\"LOCAL RANK \", local_rank) \n", "\n", "accelerator = Accelerator(split_batches=False, mixed_precision=\"fp16\") # ['no', 'fp8', 'fp16', 'bf16']\n", "\n", "print(\"PID of this process =\",os.getpid())\n", "device = accelerator.device\n", "print(\"device:\",device)\n", "world_size = accelerator.state.num_processes\n", "distributed = not accelerator.state.distributed_type == 'NO'\n", "num_devices = torch.cuda.device_count()\n", "if num_devices==0 or not distributed: num_devices = 1\n", "num_workers = num_devices\n", "print(accelerator.state)\n", "\n", "print(\"distributed =\",distributed, \"num_devices =\", num_devices, \"local rank =\", local_rank, \"world size =\", world_size)\n", "print = accelerator.print # only print if local_rank=0" ] }, { "cell_type": "code", "execution_count": 2, "id": "1b8e8d9e-2931-4546-a2ce-a7417bbe21f4", "metadata": { "tags": [] }, "outputs": [], "source": [ "# Load embedding model (last hidden layer)\n", "try:\n", " print(clip_img_embedder)\n", "except:\n", " clip_img_embedder = FrozenOpenCLIPImageEmbedder(\n", " arch=\"ViT-bigG-14\",\n", " version=\"laion2b_s39b_b160k\",\n", " output_tokens=True,\n", " only_tokens=True,\n", " )\n", " clip_img_embedder.to(device)\n", "clip_seq_dim = 256\n", "clip_emb_dim = 1664\n", "\n", "## Load embedding model (last layer)\n", "# clip_img_embedder = FrozenOpenCLIPImageEmbedder(\n", "# arch=\"ViT-bigG-14\",\n", "# version=\"laion2b_s39b_b160k\",\n", "# output_tokens=False,\n", "# only_tokens=False,\n", "# )\n", "# clip_img_embedder.to(device)\n", "# clip_seq_dim = 1\n", "# clip_emb_dim = 1280" ] }, { "cell_type": "code", "execution_count": 3, "id": "1ffb659a-8154-4536-ab27-2d976da1bf4e", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "model_name: sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0\n", "--model_name=sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0 --data_path=/scratch/gpfs/ri4541/MindEyeV2/src/mindeyev2 --all_recons_path=evals/sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0/sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0_all_recons.pt --eval_dir=/scratch/gpfs/ri4541/MindEyeV2/src/mindeyev2/evals/sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0\n" ] } ], "source": [ "plot_all = False\n", "compute_circular = False # for the circular tests looking at image similarity in clip space (without any brain data involved)\n", "saving = True\n", "\n", "# if running this interactively, can specify jupyter_args here for argparser to use\n", "if utils.is_interactive():\n", " model_name = f\"sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0\"\n", " eval_dir = f\"/scratch/gpfs/ri4541/MindEyeV2/src/mindeyev2/evals/{model_name}\"\n", " if (\"remove\" in model_name and \"random\" in model_name) or \"ses-04\" in model_name:\n", " all_recons_path = f\"{eval_dir}/all_recons.pt\"\n", " elif \"paul\" in model_name:\n", " all_recons_path = f\"evals/{model_name}/{model_name}_all_recons.pt\"\n", " else:\n", " all_recons_path = f\"{eval_dir}/{model_name}_all_recons.pt\" \n", "\n", " data_path = \"/scratch/gpfs/ri4541/MindEyeV2/src/mindeyev2\"\n", " print(\"model_name:\", model_name)\n", "\n", " jupyter_args = f\"--model_name={model_name} --data_path={data_path} --all_recons_path={all_recons_path} --eval_dir={eval_dir}\"\n", " print(jupyter_args)\n", " jupyter_args = jupyter_args.split()\n", " \n", " from IPython.display import clear_output # function to clear print outputs in cell\n", " %load_ext autoreload \n", " # this allows you to change functions in models.py or utils.py and have this notebook automatically update with your revisions\n", " %autoreload 2 " ] }, { "cell_type": "code", "execution_count": 4, "id": "fb8120cd-f226-4e2c-a6c5-3cd8ef6e9bc8", "metadata": { "tags": [] }, "outputs": [], "source": [ "parser = argparse.ArgumentParser(description=\"Model Training Configuration\")\n", "parser.add_argument(\n", " \"--model_name\", type=str, default=\"testing\",\n", " help=\"name of model, used for ckpt saving and wandb logging (if enabled)\",\n", ")\n", "parser.add_argument(\n", " \"--data_path\", type=str, default=\"/weka/proj-fmri/shared/mindeyev2_dataset\",\n", " help=\"Path to where NSD data is stored / where to download it to\",\n", ")\n", "parser.add_argument(\n", " \"--all_recons_path\", type=str,\n", " help=\"Path to where all_recons.pt is stored\",\n", ")\n", "\n", "parser.add_argument(\n", " \"--eval_dir\", type=str,\n", " help=\"Path to where evaluations should be stored\",\n", ")\n", "\n", "parser.add_argument(\n", " \"--seed\",type=int,default=42,\n", ")\n", "if utils.is_interactive():\n", " args = parser.parse_args(jupyter_args)\n", "else:\n", " args = parser.parse_args()\n", "\n", "# create global variables without the args prefix\n", "for attribute_name in vars(args).keys():\n", " globals()[attribute_name] = getattr(args, attribute_name)\n", " \n", "# seed all random functions\n", "utils.seed_everything(seed)" ] }, { "cell_type": "markdown", "id": "95d66b33-b327-4895-a861-ecc6ccc51296", "metadata": { "tags": [] }, "source": [ "# Evals" ] }, { "cell_type": "code", "execution_count": 5, "id": "be66f9c9-f25a-48d9-9e9a-272ab33d20ed", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "torch.Size([100, 3, 256, 256])\n", "all_recons_path: evals/sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0/sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0_all_recons.pt\n" ] } ], "source": [ "if (\"remove\" in model_name and \"random\" in model_name) or \"ses-04\" in model_name:\n", " all_images = torch.load(f\"{eval_dir}/all_images.pt\")\n", " all_clipvoxels = torch.load(f\"{eval_dir}/all_clipvoxels.pt\")\n", " all_predcaptions = torch.load(f\"{eval_dir}/all_predcaptions.pt\")\n", " all_unrefinedrecons = torch.load(f\"{eval_dir}/all_recons.pt\")\n", "elif \"ses-01\" in model_name and \"paul\" in model_name:\n", " all_images = torch.load(f\"evals/{model_name}/{model_name}_all_images.pt\")\n", " all_clipvoxels = torch.load(f\"evals/{model_name}/{model_name}_all_clipvoxels.pt\")\n", " all_predcaptions = torch.load(f\"evals/{model_name}/{model_name}_all_predcaptions.pt\")\n", " all_unrefinedrecons = torch.load(f\"evals/{model_name}/{model_name}_all_recons.pt\")\n", "else:\n", " all_images = torch.load(f\"{eval_dir}/{model_name}_all_images.pt\") \n", " all_clipvoxels = torch.load(f\"{eval_dir}/{model_name}_all_clipvoxels.pt\") \n", " all_predcaptions = torch.load(f\"{eval_dir}/{model_name}_all_predcaptions.pt\") \n", " all_unrefinedrecons = torch.load(f\"{eval_dir}/{model_name}_all_recons.pt\") \n", "\n", "print(all_images.shape)\n", "print(\"all_recons_path:\", all_recons_path)\n", "all_recons = torch.load(all_recons_path)\n", "\n", "# all_blurryrecons = torch.load(f\"{eval_dir}/all_blurryrecons.pt\")" ] }, { "cell_type": "code", "execution_count": 6, "id": "4b6c44f9-95ac-4bac-9fbf-d0b31f4f127f", "metadata": {}, "outputs": [], "source": [ "# if \"ses-01\" in model_name:\n", "# paul_all_images = torch.load(f\"evals/sub-001_ses-01_bs24_MST_paul_MSTsplit/sub-001_ses-01_bs24_MST_paul_MSTsplit_all_images.pt\").to('cpu')\n", "# paul_all_clipvoxels = torch.load(f\"evals/sub-001_ses-01_bs24_MST_paul_MSTsplit/sub-001_ses-01_bs24_MST_paul_MSTsplit_all_clipvoxels.pt\").to('cpu')\n", "# paul_all_recons = torch.load(f\"evals/sub-001_ses-01_bs24_MST_paul_MSTsplit/sub-001_ses-01_bs24_MST_paul_MSTsplit_all_recons.pt\").to('cpu')\n", "# # paul_all_prior_out = torch.load(f\"evals/sub-001_ses-01_bs24_MST_paul_MSTsplit/sub-001_ses-01_bs24_MST_paul_MSTsplit_all_prior_out.pt\").to('cpu')\n", "# # all_images = torch.load(f\"{eval_dir}/all_images.pt\") \n", "# print(paul_all_images.shape, all_images.shape)\n", "# print(paul_all_clipvoxels.shape, all_clipvoxels.shape)\n", "# print(torch.eq(paul_all_clipvoxels, all_clipvoxels))\n", "# # assert torch.allclose(paul_all_images, all_images)" ] }, { "cell_type": "code", "execution_count": 7, "id": "e8f29ac6-6561-4770-8837-8877488dce05", "metadata": { "tags": [] }, "outputs": [], "source": [ "# for i in range(100):\n", "# # print(torch.allclose(paul_all_images[i], all_images[i]))\n", "# pass" ] }, { "cell_type": "code", "execution_count": 8, "id": "a1382548-4b43-4101-a15b-e67b1225059c", "metadata": {}, "outputs": [], "source": [ "# num_images = paul_all_images.size(0)\n", "# rows = 10 # Number of rows for the grid\n", "# cols = 10 # Number of columns for the grid\n", "\n", "# fig, axes = plt.subplots(rows, cols * 2, figsize=(80, 40))\n", "\n", "# for i in range(num_images):\n", "# row = i // cols\n", "# col = (i % cols) * 2 # Adjust for side-by-side\n", " \n", "# # Plot correct image\n", "# ax_correct = axes[row, col]\n", "# ax_correct.imshow(paul_all_recons[i].permute(1, 2, 0).cpu().numpy())\n", "# ax_correct.axis('off')\n", "# ax_correct.set_title(f\"Correct {i}\")\n", " \n", "# # Plot modified image\n", "# ax_modified = axes[row, col + 1]\n", "# ax_modified.imshow(all_recons[i].permute(1, 2, 0).cpu().numpy())\n", "# ax_modified.axis('off')\n", "# ax_modified.set_title(f\"Modified {i}\")\n", "\n", "# plt.tight_layout()\n", "# plt.show()" ] }, { "cell_type": "code", "execution_count": 9, "id": "4cc551db-85c3-4696-a6fd-52b0092669eb", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0_all_recons.pt\n", "torch.Size([100, 3, 256, 256]) torch.Size([100, 3, 256, 256])\n" ] } ], "source": [ "model_name_plus_suffix = all_recons_path.split('/')[-1]\n", "print(model_name_plus_suffix)\n", "print(all_images.shape, all_recons.shape)" ] }, { "cell_type": "code", "execution_count": 10, "id": "22e933c4-1eed-48a7-a22f-84a4606ac253", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0 (50, 2) torch.Size([100, 3, 256, 256]) torch.Size([100, 256, 1664])\n" ] } ], "source": [ "if \"MST\" in model_name:\n", " if (\"remove\" in model_name and \"random\" in model_name) or \"ses-04\" in model_name or \"rishab\" in model_name:\n", " MST_ID = np.load(f\"{eval_dir}/MST_ID.npy\")\n", " MST_pairmate_indices = np.load(f\"{eval_dir}/MST_pairmate_indices.npy\")\n", " elif \"paul\" in model_name:\n", " MST_ID = np.load(f\"evals/{model_name}/{model_name}_MST_ID.npy\")\n", " MST_pairmate_indices = np.array(utils.find_paired_indices(torch.Tensor(MST_ID)))\n", " # print(MST_pairmate_indices)\n", " else:\n", " MST_ID = np.load(f\"{eval_dir}/{model_name}_MST_ID.npy\") \n", " MST_pairmate_indices = np.load(f\"{eval_dir}/{model_name}_MST_pairmate_indices.npy\") \n", "\n", " # pairs = utils.find_paired_indices(torch.Tensor(MST_ID))\n", " # if \"close_to_MST\" in model_name or (\"remove\" in model_name and \"random\" in model_name) or \"ses-0\" in model_name:\n", " # pairs = np.array(pairs[:-1]) # index out the placeholder\n", " # pairs = np.array(pairs)\n", " # if \"ses-0\" in model_name:\n", " # if \"ses-01\" in model_name or \"ses-04\" in model_name:\n", " # print(pairs.shape)\n", " # assert pairs.shape == (49,2)\n", " # else:\n", " # assert pairs.shape == (50,3)\n", " # else:\n", " # assert pairs.shape == (100,3)\n", " # print(pairs)\n", " # repeats_in_test = torch.load(f\"{eval_dir}/repeats_in_test.pt\")\n", " # test_image_indices = torch.load(f\"{eval_dir}/test_image_indices.pt\")\n", " all_unique_images = all_images[MST_pairmate_indices.flatten()]\n", " all_unique_clipvoxels = all_clipvoxels[MST_pairmate_indices.flatten()]\n", "\n", " print(model_name, MST_pairmate_indices.shape, all_unique_images.shape, all_unique_clipvoxels.shape)" ] }, { "cell_type": "code", "execution_count": 11, "id": "880081e4-7567-4b1e-acb0-4af863018228", "metadata": { "tags": [] }, "outputs": [], "source": [ "# visualize all unique images\n", "if plot_all:\n", " # Plot all the MST images and pairmates\n", " import textwrap\n", " def wrap_title(title, wrap_width):\n", " return \"\\n\".join(textwrap.wrap(title, wrap_width))\n", "\n", " size = int(np.ceil(MST_pairmate_indices.shape[0]/2)) # helps determine size of plot\n", " fig, axes = plt.subplots(size, 4, figsize=(15, size*4))\n", " jj=-1; kk=0;\n", " for i, j in enumerate(all_unique_images):\n", " jj+=1\n", " axes[kk][jj].imshow(utils.torch_to_Image(j))\n", " axes[kk][jj].axis('off')\n", " if jj==3: \n", " kk+=1; jj=-1\n", "\n", " fig.tight_layout()\n", " # plt.savefig('figures/MST_2_pairmates_10-01')\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": 12, "id": "48c8772b-871a-4031-b013-d7159bf8b74a", "metadata": { "tags": [] }, "outputs": [], "source": [ "# if plot_all:\n", "# # create full grid of recon comparisons\n", "# from PIL import Image\n", "\n", "# imsize = 150\n", "# if all_images.shape[-1] != imsize:\n", "# all_images = transforms.Resize((imsize,imsize))(all_images).float()\n", "# if all_recons.shape[-1] != imsize:\n", "# all_recons = transforms.Resize((imsize,imsize))(all_recons).float()\n", "\n", "# num_images = all_recons.shape[0]\n", "# num_rows = (2 * num_images + 9) // 10\n", "\n", "# # Interleave tensors\n", "# merged = torch.stack([val for pair in zip(all_images, all_recons) for val in pair], dim=0)\n", "\n", "# # Calculate grid size\n", "# grid = torch.zeros((num_rows * 10, 3, all_recons.shape[-1], all_recons.shape[-1]))\n", "\n", "# # Populate the grid\n", "# grid[:2*num_images] = merged\n", "# grid_images = [transforms.functional.to_pil_image(grid[i]) for i in range(num_rows * 10)]\n", "\n", "# # Create the grid image\n", "# grid_image = Image.new('RGB', (all_recons.shape[-1]*10, all_recons.shape[-1] * num_rows)) # 10 images wide\n", "\n", "# # Paste images into the grid\n", "# for i, img in enumerate(grid_images):\n", "# grid_image.paste(img, (all_recons.shape[-1] * (i % 10), all_recons.shape[-1] * (i // 10)))\n", "# grid_image\n", "# # grid_image.save(f\"{model_name_plus_suffix[:-3]}_1000recons.png\")" ] }, { "cell_type": "code", "execution_count": 13, "id": "f42009e9-f910-4f02-8db6-d46778aa6595", "metadata": { "tags": [] }, "outputs": [], "source": [ "imsize = 256\n", "if all_images.shape[-1] != imsize:\n", " all_images = transforms.Resize((imsize,imsize))(all_images).float()\n", "if all_recons.shape[-1] != imsize:\n", " all_recons = transforms.Resize((imsize,imsize))(all_recons).float()\n", "try:\n", " if all_blurryrecons.shape[-1] != imsize:\n", " all_blurryrecons = transforms.Resize((imsize,imsize))(all_blurryrecons).float()\n", "except:\n", " pass\n", "\n", "if \"enhanced\" in model_name_plus_suffix:\n", " try:\n", " all_recons = all_recons*.75 + all_blurryrecons*.25\n", " print(\"weighted averaging to improve low-level evals\")\n", " except:\n", " pass" ] }, { "cell_type": "code", "execution_count": 14, "id": "06e23174-a777-4dd1-8b73-6783587d8f9c", "metadata": { "tags": [] }, "outputs": [], "source": [ "# visualize some images with recons and captions\n", "if plot_all:\n", " assert np.all(all_images.shape == all_recons.shape)\n", " import textwrap\n", " def wrap_title(title, wrap_width):\n", " return \"\\n\".join(textwrap.wrap(title, wrap_width))\n", "\n", " fig, axes = plt.subplots(3, 4, figsize=(10, 8))\n", " jj=-1; kk=0;\n", " for j in np.array([0,1,2,3,4,5]):\n", " jj+=1\n", " # print(kk,jj)\n", " axes[kk][jj].imshow(utils.torch_to_Image(all_images[j]))\n", " axes[kk][jj].axis('off')\n", " jj+=1\n", " axes[kk][jj].imshow(utils.torch_to_Image(all_recons[j]))\n", " axes[kk][jj].axis('off')\n", " axes[kk][jj].set_title(wrap_title(str(all_predcaptions[[j]]),wrap_width=30), fontsize=8)\n", " if jj==3: \n", " kk+=1; jj=-1\n", "\n", " fig.tight_layout()\n", " # plt.savefig('figures/recon_09-26')\n", " plt.show()" ] }, { "cell_type": "markdown", "id": "5b4deb53-4d85-4292-92c5-bb59077523cf", "metadata": {}, "source": [ "# Retrieval eval (chance = 1/100)" ] }, { "cell_type": "code", "execution_count": 15, "id": "2e49d57a-9b65-490c-a1e0-61bd05682171", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "overall fwd percent_correct: 0.7100\n", "overall bwd percent_correct: 0.7000\n" ] } ], "source": [ "from scipy import stats\n", "\n", "all_fwd_acc = []\n", "all_bwd_acc = []\n", "\n", "assert len(all_unique_images) == len(all_unique_clipvoxels) \n", "\n", "all_percent_correct_fwds, all_percent_correct_bwds = [], []\n", "\n", "with torch.cuda.amp.autocast(dtype=torch.float16):\n", " all_emb = clip_img_embedder(all_unique_images.to(device)).float() # CLIP-Image\n", " all_emb_ = all_unique_clipvoxels # CLIP-Brain\n", "\n", " # flatten if necessary\n", " all_emb = all_emb.reshape(len(all_emb),-1).to(device)\n", " all_emb_ = all_emb_.reshape(len(all_emb_),-1).to(device)\n", "\n", " # l2norm \n", " all_emb = nn.functional.normalize(all_emb,dim=-1)\n", " all_emb_ = nn.functional.normalize(all_emb_,dim=-1)\n", "\n", " all_labels = torch.arange(len(all_emb)).to(device)\n", " all_bwd_sim = utils.batchwise_cosine_similarity(all_emb,all_emb_) # clip, brain\n", " all_fwd_sim = utils.batchwise_cosine_similarity(all_emb_,all_emb) # brain, clip\n", "\n", " if \"ses-0\" not in model_name or \"ses-01\" in model_name or \"ses-04\" in model_name:\n", " assert len(all_fwd_sim) == 100\n", " assert len(all_bwd_sim) == 100\n", " else:\n", " assert len(all_fwd_sim) == 50\n", " assert len(all_bwd_sim) == 50\n", " \n", " all_percent_correct_fwds = utils.topk(all_fwd_sim, all_labels, k=1).item()\n", " all_percent_correct_bwds = utils.topk(all_bwd_sim, all_labels, k=1).item()\n", "\n", "all_fwd_acc.append(all_percent_correct_fwds)\n", "all_bwd_acc.append(all_percent_correct_bwds)\n", "\n", "all_fwd_sim = np.array(all_fwd_sim.cpu())\n", "all_bwd_sim = np.array(all_bwd_sim.cpu())\n", "\n", "print(f\"overall fwd percent_correct: {all_fwd_acc[0]:.4f}\")\n", "print(f\"overall bwd percent_correct: {all_bwd_acc[0]:.4f}\")" ] }, { "cell_type": "code", "execution_count": 16, "id": "1a4cda50-ef4a-43d0-9c2e-53ee8509482d", "metadata": { "tags": [] }, "outputs": [], "source": [ "if \"ses-0\" not in model_name:\n", " from scipy import stats\n", "\n", " fwd_acc = []\n", " bwd_acc = []\n", " fwd_sim_halves = []\n", " bwd_sim_halves = []\n", "\n", " assert len(all_unique_images) == len(all_unique_clipvoxels) \n", "\n", " for i in range(2): # since this is a 2-session model, we evaluate on the test set corresponding to each session and report both separately for better comparison to single-session models\n", " percent_correct_fwds, percent_correct_bwds = [], []\n", " # percent_correct_fwd, percent_correct_bwd = None, None\n", "\n", " if i==0: \n", " all_unique_images_half = all_unique_images[:int(len(all_unique_images)/2)]\n", " all_unique_clipvoxels_half = all_unique_clipvoxels[:int(len(all_unique_clipvoxels)/2)]\n", " elif i==1:\n", " all_unique_images_half = all_unique_images[int(len(all_unique_images)/2):]\n", " all_unique_clipvoxels_half = all_unique_clipvoxels[int(len(all_unique_clipvoxels)/2):]\n", "\n", "\n", " with torch.cuda.amp.autocast(dtype=torch.float16):\n", " emb = clip_img_embedder(all_unique_images_half.to(device)).float() # CLIP-Image\n", " emb_ = all_unique_clipvoxels_half # CLIP-Brain\n", "\n", " # flatten if necessary\n", " emb = emb.reshape(len(emb),-1).to(device)\n", " emb_ = emb_.reshape(len(emb_),-1).to(device)\n", "\n", " # l2norm \n", " emb = nn.functional.normalize(emb,dim=-1)\n", " emb_ = nn.functional.normalize(emb_,dim=-1)\n", "\n", " labels = torch.arange(len(emb)).to(device)\n", " bwd_sim = utils.batchwise_cosine_similarity(emb,emb_) # clip, brain\n", " fwd_sim = utils.batchwise_cosine_similarity(emb_,emb) # brain, clip\n", "\n", " assert len(fwd_sim) == 50\n", " assert len(bwd_sim) == 50\n", "\n", " # percent_correct_fwds = np.append(percent_correct_fwds, utils.topk(fwd_sim, labels, k=1).item())\n", " # percent_correct_bwds = np.append(percent_correct_bwds, utils.topk(bwd_sim, labels, k=1).item())\n", " percent_correct_fwds = utils.topk(fwd_sim, labels, k=1).item()\n", " percent_correct_bwds = utils.topk(bwd_sim, labels, k=1).item()\n", "\n", " # percent_correct_fwd = np.mean(percent_correct_fwds)\n", " # fwd_sd = np.std(percent_correct_fwds) / np.sqrt(len(percent_correct_fwds))\n", " # fwd_ci = stats.norm.interval(0.95, loc=percent_correct_fwd, scale=fwd_sd)\n", "\n", " # percent_correct_bwd = np.mean(percent_correct_bwds)\n", " # bwd_sd = np.std(percent_correct_bwds) / np.sqrt(len(percent_correct_bwds))\n", " # bwd_ci = stats.norm.interval(0.95, loc=percent_correct_bwd, scale=bwd_sd)\n", "\n", " fwd_acc.append(percent_correct_fwds)\n", " bwd_acc.append(percent_correct_bwds)\n", "\n", " fwd_sim = np.array(fwd_sim.cpu())\n", " bwd_sim = np.array(bwd_sim.cpu())\n", " fwd_sim_halves.append(fwd_sim)\n", " bwd_sim_halves.append(bwd_sim)\n", "\n", " print(f\"ses-02 fwd percent_correct: {fwd_acc[0]:.4f}; ses-03 fwd percent_correct: {fwd_acc[1]:.4f}\")\n", " print(f\"ses-02 bwd percent_correct: {bwd_acc[0]:.4f}; ses-03 bwd percent_correct: {bwd_acc[1]:.4f} \")" ] }, { "cell_type": "code", "execution_count": 17, "id": "40d43a70-e1db-43e5-ae84-40eb1577cf01", "metadata": { "tags": [] }, "outputs": [], "source": [ "if compute_circular:\n", " if \"ses-0\" not in model_name: # we're in a multisession model, assumed ses-02 and ses-03 for now\n", " fwd_acc_circular = []\n", " fwd_sim_halves_circular = []\n", "\n", " assert len(all_unique_images) == len(all_unique_clipvoxels) \n", "\n", " for i in range(2): # since this is a 2-session model, we evaluate on the test set corresponding to each session and report both separately for better comparison to single-session models\n", " percent_correct_fwds_circular = []\n", " # percent_correct_fwd_circular = None\n", "\n", " if i==0: \n", " all_unique_images_half_circular = all_unique_images[:int(len(all_unique_images)/2)]\n", " all_unique_clipvoxels_half_circular = all_unique_clipvoxels[:int(len(all_unique_clipvoxels)/2)]\n", " elif i==1:\n", " all_unique_images_half_circular = all_unique_images[int(len(all_unique_images)/2):]\n", " all_unique_clipvoxels_half_circular = all_unique_clipvoxels[int(len(all_unique_clipvoxels)/2):]\n", "\n", " with torch.cuda.amp.autocast(dtype=torch.float16):\n", " emb_circular = clip_img_embedder(all_unique_images_half_circular.to(device)).float() # CLIP-Image\n", "\n", " # flatten if necessary\n", " emb_circular = emb_circular.reshape(len(emb_circular),-1).to(device)\n", "\n", " # l2norm \n", " emb_circular = nn.functional.normalize(emb_circular,dim=-1)\n", "\n", " labels_circular = torch.arange(len(emb_circular)).to(device)\n", " fwd_sim_circular = utils.batchwise_cosine_similarity(emb_circular,emb_circular) # clip, clip\n", "\n", "\n", " if \"ses-0\" in model_name:\n", " assert len(fwd_sim_circular) == 25\n", " else:\n", " assert len(fwd_sim_circular) == 50\n", "\n", " # percent_correct_fwds_circular = np.append(percent_correct_fwds_circular, utils.topk(fwd_sim_circular, labels_circular, k=1).item())\n", " percent_correct_fwds_circular = utils.topk(fwd_sim_circular, labels_circular, k=1).item()\n", "\n", "\n", " # percent_correct_fwd_circular = np.mean(percent_correct_fwds_circular)\n", " # fwd_sd_circular = np.std(percent_correct_fwds_circular) / np.sqrt(len(percent_correct_fwds_circular))\n", " # fwd_ci_circular = stats.norm.interval(0.95, loc=percent_correct_fwd_circular, scale=fwd_sd_circular)\n", "\n", " fwd_acc_circular.append(percent_correct_fwds_circular)\n", "\n", " fwd_sim_circular = np.array(fwd_sim_circular.cpu())\n", " fwd_sim_halves_circular.append(fwd_sim_circular)\n", "\n", " print(f\"ses-02 fwd percent_correct: {fwd_acc_circular[0]:.4f}; ses-03 fwd percent_correct: {fwd_acc_circular[1]:.4f}\")\n", " \n", " else: # single session model\n", " fwd_acc_circular = []\n", "\n", " assert len(all_unique_images) == len(all_unique_clipvoxels) \n", "\n", " percent_correct_fwds_circular = []\n", " # percent_correct_fwd_circular = None\n", "\n", " with torch.cuda.amp.autocast(dtype=torch.float16):\n", " emb_circular = clip_img_embedder(all_unique_images.to(device)).float() # CLIP-Image\n", "\n", " # flatten if necessary\n", " emb_circular = emb_circular.reshape(len(emb_circular),-1).to(device)\n", "\n", " # l2norm \n", " emb_circular = nn.functional.normalize(emb_circular,dim=-1)\n", "\n", " labels_circular = torch.arange(len(emb_circular)).to(device)\n", " fwd_sim_circular = utils.batchwise_cosine_similarity(emb_circular,emb_circular) # clip, clip\n", "\n", "\n", " if \"ses-01\" in model_name:\n", " assert len(fwd_sim_circular) == 100\n", " else:\n", " assert len(fwd_sim_circular) == 50\n", "\n", " # percent_correct_fwds_circular = np.append(percent_correct_fwds_circular, utils.topk(fwd_sim_circular, labels_circular, k=1).item())\n", " percent_correct_fwds_circular = utils.topk(fwd_sim_circular, labels_circular, k=1).item()\n", "\n", "\n", " # percent_correct_fwd_circular = np.mean(percent_correct_fwds_circular)\n", " # fwd_sd_circular = np.std(percent_correct_fwds_circular) / np.sqrt(len(percent_correct_fwds_circular))\n", " # fwd_ci_circular = stats.norm.interval(0.95, loc=percent_correct_fwd_circular, scale=fwd_sd_circular)\n", "\n", " fwd_acc_circular.append(percent_correct_fwds_circular)\n", "\n", " fwd_sim_circular = np.array(fwd_sim_circular.cpu())\n", "\n", " print(f\"session fwd percent_correct (circular): {fwd_acc_circular[0]:.4f}\")" ] }, { "cell_type": "code", "execution_count": 18, "id": "d086c99a-c712-4ac7-b625-a0656c9ee886", "metadata": { "tags": [] }, "outputs": [], "source": [ "if compute_circular:\n", " # print(utils.topk(torch.Tensor(fwd_sim_halves[1]).to(device), labels, k=1).item())\n", " # ses02_top1 = torch.argsort(torch.Tensor(fwd_sim_halves[0]).to(device),axis=1)[:,-1] == labels # from utils.topk()\n", " # ses03_top1 = torch.argsort(torch.Tensor(fwd_sim_halves[1]).to(device),axis=1)[:,-1] == labels\n", " # top1_results = torch.cat((ses02_top1, ses03_top1))\n", " # incorrect_idx = torch.argwhere(top1_results == False)[:,0]\n", " # print(incorrect_idx)\n", "\n", " # confirm that the lure is behind the target 80% of the time in CLIP last hidden layer embeddings\n", "\n", " use_fwd_sim = False\n", " use_first_half = False\n", "\n", " all_top_sims = [] # len(fwd_sim_halves[0]); for each image, contains the similarity to the top-n choices until it gets the correct answer. If len 1, top-1 is correct\n", " all_pairmate_sims = [] # len(fwd_sim_halves[0]); the similarity of each image to its pairmate \n", " all_chose_lures = [] # len(fwd_sim_halves[0]); True for each top-n choice if the lure was predicted to be more similar to the target \n", " if \"ses-0\" not in model_name:\n", " sim_halves = fwd_sim_halves if use_fwd_sim else bwd_sim_halves\n", " sim_halves = sim_halves[0] if use_first_half else sim_halves[1]\n", " else:\n", " sim_halves = all_fwd_sim if use_fwd_sim else all_bwd_sim\n", " for i, img in enumerate(sim_halves):\n", " if i%2==0:\n", " idx_to_pairmate = 1\n", " elif i%2==1:\n", " idx_to_pairmate = -1\n", "\n", " order = img.argsort()[::-1]\n", " # print(order)\n", " top_sim = []\n", " chose_lure = []\n", " for idx in order:\n", " sim = img[idx]\n", " pairmate_sim = img[i+idx_to_pairmate]\n", " top_sim.append(sim) \n", " chose_lure.append((idx, sim <= pairmate_sim))\n", " # print(i, idx, img[idx], img[i+idx_to_pairmate])\n", " if idx == i:\n", " break\n", "\n", " all_top_sims.append(top_sim)\n", " all_pairmate_sims.append(pairmate_sim)\n", " all_chose_lures.append(chose_lure)\n", "\n", " # print(all_top_sims)\n", " # print()\n", " # print(all_pairmate_sims)\n", " # print()\n", " # print(all_chose_lures)\n", "\n", " where_chose_pairmate = []\n", " for idx, i in enumerate(all_chose_lures):\n", " for value in i:\n", " # print(value[1])\n", " if value[1] == True:\n", " # print(idx, i, end='\\n')\n", " where_chose_pairmate.append(idx)\n", " break\n", "\n", " # where_chose_pairmate # trials where the pairmate was chosen ahead of the target" ] }, { "cell_type": "code", "execution_count": 19, "id": "a5c4405c-b3b7-42fe-b622-f4cb81500464", "metadata": { "tags": [] }, "outputs": [], "source": [ "# top-n predictions using CLIP brain embeddings\n", "\n", "if plot_all:\n", " use_fwd_sim = True\n", " top_n = 10 # how many of the top n images to display\n", " print(\"Given Brain embedding, find correct Image embedding\")\n", " fig, ax = plt.subplots(nrows=len(all_unique_images), ncols=top_n+1, figsize=(top_n*2,len(all_unique_images)*2))\n", " for trial in range(len(all_unique_images)):\n", " ax[trial, 0].imshow(utils.torch_to_Image(all_unique_images[trial]))\n", " ax[trial, 0].set_title(\"original\\nimage\")\n", " ax[trial, 0].axis(\"off\")\n", " for attempt in range(top_n):\n", " if trial < 50:\n", " if \"ses-0\" not in model_name:\n", " sim_half = fwd_sim_halves[0] if use_fwd_sim else bwd_sim_halves[0]\n", " unique_imgs_to_plot = all_unique_images[:int(len(all_unique_images)/2)]\n", " # unique_clipvoxels_to_plot = all_unique_clipvoxels[:int(len(all_unique_clipvoxels)/2)]\n", " else:\n", " sim_half = all_fwd_sim if use_fwd_sim else all_bwd_sim\n", " unique_imgs_to_plot = all_unique_images\n", " # unique_clipvoxels_to_plot = all_unique_clipvoxels\n", " which = np.flip(np.argsort(sim_half[trial]))[attempt]\n", "\n", " elif trial >= 50:\n", " if \"ses-0\" not in model_name:\n", " sim_halves = fwd_sim_halves[1] if use_fwd_sim else bwd_sim_halves[1]\n", " unique_imgs_to_plot = all_unique_images[int(len(all_unique_images)/2):]\n", " # unique_clipvoxels_to_plot = all_unique_clipvoxels[int(len(all_unique_clipvoxels)/2):]\n", " else:\n", " sim_halves = all_fwd_sim if use_fwd_sim else all_bwd_sim\n", " unique_imgs_to_plot = all_unique_images\n", " # unique_clipvoxels_to_plot = all_unique_clipvoxels\n", " which = np.flip(np.argsort(sim_half[trial-50]))[attempt]\n", "\n", " ax[trial, attempt+1].imshow(utils.torch_to_Image(unique_imgs_to_plot[which]))\n", " ax[trial, attempt+1].set_title(f\"Top {attempt+1}\")\n", " ax[trial, attempt+1].axis(\"off\")\n", " fig.tight_layout()\n", " # plt.savefig('figures/retrieval_top10')\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": 20, "id": "05df72ce-3cdb-4ad2-a790-0835a41fb0f6", "metadata": { "tags": [] }, "outputs": [], "source": [ "# similarity of each unique MST image to all others using CLIP image embeddings only (top-1 is guaranteed to be correct)\n", "# uses last hidden layer (which may not match as well as the last layer to human semantic judgments)\n", "if plot_all and compute_circular:\n", " print(\"Given Brain embedding, find correct Image embedding\")\n", " top_n = 10 # how many of the top n images to display\n", " fig, ax = plt.subplots(nrows=len(all_unique_images), ncols=top_n+1, figsize=(top_n*2,len(all_unique_images)*2))\n", " for trial in range(len(all_unique_images)):\n", " ax[trial, 0].imshow(utils.torch_to_Image(all_unique_images[trial]))\n", " ax[trial, 0].set_title(\"original\\nimage\")\n", " ax[trial, 0].axis(\"off\")\n", " for attempt in range(10):\n", " if trial < 50:\n", " if \"ses-0\" not in model_name:\n", " sim_half_circular = fwd_sim_halves_circular[0]\n", " unique_imgs_to_plot_circular = all_unique_images[:int(len(all_unique_images)/2)]\n", " else:\n", " sim_half_circular = fwd_sim_circular\n", " unique_imgs_to_plot_circular = all_unique_images\n", " which_circular = np.flip(np.argsort(sim_half_circular[trial]))[attempt]\n", "\n", " elif trial >= 50:\n", " if \"ses-0\" not in model_name:\n", " sim_halves_circular = fwd_sim_halves_circular[1]\n", " unique_imgs_to_plot_circular = all_unique_images[int(len(all_unique_images)/2):]\n", " else:\n", " sim_halves_circular = all_fwd_sim_circular\n", " unique_imgs_to_plot_circular = all_unique_images\n", " which_circular = np.flip(np.argsort(sim_half_circular[trial-50]))[attempt]\n", "\n", " ax[trial, attempt+1].imshow(utils.torch_to_Image(unique_imgs_to_plot_circular[which_circular]))\n", " ax[trial, attempt+1].set_title(f\"Top {attempt+1}\")\n", " ax[trial, attempt+1].axis(\"off\")\n", " fig.tight_layout()\n", " # plt.savefig('figures/circular_top10')\n", " plt.show()" ] }, { "cell_type": "markdown", "id": "0d404dec-5336-45cf-8932-833e895a9ebe", "metadata": { "tags": [] }, "source": [ "## MST Paired Retrieval (chance = 50%)" ] }, { "cell_type": "code", "execution_count": 21, "id": "06667f7d-a356-4c30-8e1b-06ebd7ff1752", "metadata": {}, "outputs": [], "source": [ "if compute_circular:\n", " all_top_sims_circular = [] # len(fwd_sim_halves[0]); for each image, contains the similarity to the top-n choices until it gets the correct answer. If len 1, top-1 is correct\n", " all_pairmate_sims_circular = [] # len(fwd_sim_halves[0]); the similarity of each image to its pairmate \n", " all_chose_lures_circular = [] # len(fwd_sim_halves[0]); True for each top-n choice if the lure was predicted to be more similar to the target \n", "\n", " if \"ses-0\" not in model_name:\n", " first_half = True\n", " sim_halves_circular = fwd_sim_halves_circular\n", " sim_halves_circular = sim_halves_circular[0] if use_first_half else sim_halves_circular[1]\n", " else:\n", " sim_halves_circular = all_fwd_sim_circular\n", " for i, img in enumerate(sim_halves_circular):\n", " if i%2==0:\n", " idx_to_pairmate = 1\n", " elif i%2==1:\n", " idx_to_pairmate = -1\n", "\n", " order_circular = img.argsort()[::-1]\n", " # print(order)\n", " top_sim_circular = []\n", " chose_lure_circular = []\n", " for idx in order_circular:\n", " sim_circular = img[idx]\n", " pairmate_sim_circular = img[i+idx_to_pairmate]\n", " top_sim_circular.append(sim_circular) \n", " chose_lure_circular.append((idx, sim_circular <= pairmate_sim_circular))\n", " # print(i, idx, img[idx], img[i+idx_to_pairmate])\n", " if idx == i:\n", " break\n", "\n", " all_top_sims_circular.append(top_sim_circular)\n", " all_pairmate_sims_circular.append(pairmate_sim_circular)\n", " all_chose_lures_circular.append(chose_lure_circular)\n", "\n", " bot_half = (all_pairmate_sims_circular < np.median(all_pairmate_sims_circular))[::2] # every other one since the sims are symmetric\n", " top_half = (all_pairmate_sims_circular > np.median(all_pairmate_sims_circular))[::2]\n", "\n", " binary_acc = []\n", " for i,(a,b) in enumerate(tqdm(MST_pairmate_indices,total=len(MST_pairmate_indices))):\n", " # print(i,a,b)\n", " with torch.no_grad():\n", " with torch.cuda.amp.autocast():\n", " emb_a = nn.functional.normalize(clip_img_embedder(all_images[[a]].to(device)).float().flatten(1),dim=-1)\n", " emb_b = nn.functional.normalize(clip_img_embedder(all_images[[b]].to(device)).float().flatten(1),dim=-1)\n", " emb_v = nn.functional.normalize(all_clipvoxels[[a]].flatten(1),dim=-1).to(device)\n", "\n", " a_sim = utils.pairwise_cosine_similarity(emb_v, emb_a).item()\n", " b_sim = utils.pairwise_cosine_similarity(emb_v, emb_b).item()\n", "\n", " binary_acc.append(a_sim > b_sim)\n", "\n", " with torch.no_grad():\n", " with torch.cuda.amp.autocast():\n", " emb_a = nn.functional.normalize(clip_img_embedder(all_images[[a]].to(device)).float().flatten(1),dim=-1)\n", " emb_b = nn.functional.normalize(clip_img_embedder(all_images[[b]].to(device)).float().flatten(1),dim=-1)\n", " emb_v = nn.functional.normalize(all_clipvoxels[[b]].flatten(1),dim=-1).to(device)\n", "\n", " a_sim = utils.pairwise_cosine_similarity(emb_v, emb_a).item()\n", " b_sim = utils.pairwise_cosine_similarity(emb_v, emb_b).item()\n", "\n", " binary_acc.append(a_sim < b_sim)\n", "\n", " assert len(binary_acc) == 50\n", " mst_score = np.mean(binary_acc)\n", " print(f\"session score: {np.mean(binary_acc):.4f} ± {np.std(binary_acc):.4f}\")\n" ] }, { "cell_type": "code", "execution_count": 22, "id": "3468021c-660d-4205-8e5d-d75f6f3c2881", "metadata": {}, "outputs": [], "source": [ "# test = np.sort(MST_pairmate_indices, axis=1)\n", "# test" ] }, { "cell_type": "code", "execution_count": 23, "id": "a032c4cc-4cf9-4b33-ac02-0e569f7757be", "metadata": {}, "outputs": [], "source": [ "# model_name" ] }, { "cell_type": "code", "execution_count": 24, "id": "130bb4d9-b7f1-40a4-a3e2-7e3699c69c49", "metadata": {}, "outputs": [], "source": [ "# paul_all_images = torch.load(f\"evals/sub-001_ses-01_bs24_MST_paul_MSTsplit/sub-001_ses-01_bs24_MST_paul_MSTsplit_all_images.pt\").to('cpu')\n", "# paul_all_clipvoxels = torch.load(f\"evals/sub-001_ses-01_bs24_MST_paul_MSTsplit/sub-001_ses-01_bs24_MST_paul_MSTsplit_all_clipvoxels.pt\").to('cpu')\n", "# paul_all_recons = torch.load(f\"evals/sub-001_ses-01_bs24_MST_paul_MSTsplit/sub-001_ses-01_bs24_MST_paul_MSTsplit_all_recons.pt\").to('cpu')\n", "# paul_all_prior_out = torch.load(f\"evals/sub-001_ses-01_bs24_MST_paul_MSTsplit/sub-001_ses-01_bs24_MST_paul_MSTsplit_all_prior_out.pt\").to('cpu')\n", "# print(paul_all_images.shape, all_images.shape)\n", "# # assert torch.eq(paul_all_images, all_images)" ] }, { "cell_type": "code", "execution_count": 25, "id": "698ffc2c-5653-49d3-9d16-38a32f9e7f6b", "metadata": { "tags": [] }, "outputs": [], "source": [ "# print(paul_all_images.shape, all_images.shape)\n", "# torch.eq(paul_all_images, all_images)" ] }, { "cell_type": "code", "execution_count": 26, "id": "23f26846-3170-4c91-a8e3-f98322e90dc0", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "assuming single session\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 50/50 [00:04<00:00, 10.23it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "session score: 0.8900 ± 0.3129\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "if \"MST\" in model_name:\n", " if \"ses-0\" not in model_name:\n", " print('assuming ses-02+ses-03 multisession model')\n", " mst_score = []\n", " for half in range(2):\n", " binary_acc = []\n", " if half==0:\n", " MST_pairmate_indices_half = MST_pairmate_indices[:int(len(MST_pairmate_indices)/2)]\n", " elif half==1:\n", " MST_pairmate_indices_half = MST_pairmate_indices[int(len(MST_pairmate_indices)/2):]\n", " for i,(a,b) in enumerate(tqdm(MST_pairmate_indices_half,total=len(MST_pairmate_indices_half))):\n", " # print(i,a,b)\n", " with torch.no_grad():\n", " with torch.cuda.amp.autocast():\n", " emb_a = nn.functional.normalize(clip_img_embedder(all_images[[a]].to(device)).float().flatten(1),dim=-1)\n", " emb_b = nn.functional.normalize(clip_img_embedder(all_images[[b]].to(device)).float().flatten(1),dim=-1)\n", " emb_v = nn.functional.normalize(all_clipvoxels[[a]].flatten(1),dim=-1).to(device)\n", "\n", " a_sim = utils.pairwise_cosine_similarity(emb_v, emb_a).item()\n", " b_sim = utils.pairwise_cosine_similarity(emb_v, emb_b).item()\n", "\n", " binary_acc.append(a_sim > b_sim)\n", "\n", " with torch.no_grad():\n", " with torch.cuda.amp.autocast():\n", " emb_a = nn.functional.normalize(clip_img_embedder(all_images[[a]].to(device)).float().flatten(1),dim=-1)\n", " emb_b = nn.functional.normalize(clip_img_embedder(all_images[[b]].to(device)).float().flatten(1),dim=-1)\n", " emb_v = nn.functional.normalize(all_clipvoxels[[b]].flatten(1),dim=-1).to(device)\n", "\n", " a_sim = utils.pairwise_cosine_similarity(emb_v, emb_a).item()\n", " b_sim = utils.pairwise_cosine_similarity(emb_v, emb_b).item()\n", "\n", " binary_acc.append(a_sim < b_sim)\n", "\n", " assert len(binary_acc) == 50 # don't want to average across both sessions; make sure it resets\n", " print(f\"ses-0{half+2} score: {np.mean(binary_acc):.4f} ± {np.std(binary_acc):.4f}\")\n", " mst_score.append((np.mean(binary_acc),np.std(binary_acc)))\n", "\n", " # print(mst_score)\n", " else:\n", " print('assuming single session')\n", " binary_acc = []\n", " for i,(a,b) in enumerate(tqdm(MST_pairmate_indices,total=len(MST_pairmate_indices))):\n", " # print(i,a,b)\n", " with torch.no_grad():\n", " with torch.cuda.amp.autocast():\n", " emb_a = nn.functional.normalize(clip_img_embedder(all_images[[a]].to(device)).float().flatten(1),dim=-1)\n", " emb_b = nn.functional.normalize(clip_img_embedder(all_images[[b]].to(device)).float().flatten(1),dim=-1)\n", " emb_v = nn.functional.normalize(all_clipvoxels[[a]].flatten(1),dim=-1).to(device)\n", "\n", " a_sim = utils.pairwise_cosine_similarity(emb_v, emb_a).item()\n", " b_sim = utils.pairwise_cosine_similarity(emb_v, emb_b).item()\n", "\n", " binary_acc.append(a_sim > b_sim)\n", "\n", " with torch.no_grad():\n", " with torch.cuda.amp.autocast():\n", " emb_a = nn.functional.normalize(clip_img_embedder(all_images[[a]].to(device)).float().flatten(1),dim=-1)\n", " emb_b = nn.functional.normalize(clip_img_embedder(all_images[[b]].to(device)).float().flatten(1),dim=-1)\n", " emb_v = nn.functional.normalize(all_clipvoxels[[b]].flatten(1),dim=-1).to(device)\n", "\n", " a_sim = utils.pairwise_cosine_similarity(emb_v, emb_a).item()\n", " b_sim = utils.pairwise_cosine_similarity(emb_v, emb_b).item()\n", "\n", " binary_acc.append(a_sim < b_sim)\n", " \n", " # assert len(binary_acc) == 50\n", " mst_score = np.mean(binary_acc)\n", " print(f\"session score: {np.mean(binary_acc):.4f} ± {np.std(binary_acc):.4f}\")\n" ] }, { "cell_type": "markdown", "id": "0a26e124-2444-434d-a399-d03c2c90cc08", "metadata": {}, "source": [ "## 2-way identification" ] }, { "cell_type": "code", "execution_count": 27, "id": "3e1778ff-5d6a-4087-b59f-0f44b9e0eada", "metadata": {}, "outputs": [], "source": [ "from torchvision.models.feature_extraction import create_feature_extractor, get_graph_node_names\n", "\n", "@torch.no_grad()\n", "def two_way_identification(all_recons, all_images, model, preprocess, feature_layer=None, return_avg=True):\n", " preds = model(torch.stack([preprocess(recon) for recon in all_recons], dim=0).to(device))\n", " reals = model(torch.stack([preprocess(indiv) for indiv in all_images], dim=0).to(device))\n", " if feature_layer is None:\n", " preds = preds.float().flatten(1).cpu().numpy()\n", " reals = reals.float().flatten(1).cpu().numpy()\n", " else:\n", " preds = preds[feature_layer].float().flatten(1).cpu().numpy()\n", " reals = reals[feature_layer].float().flatten(1).cpu().numpy()\n", "\n", " r = np.corrcoef(reals, preds)\n", " r = r[:len(all_images), len(all_images):]\n", " congruents = np.diag(r)\n", "\n", " success = r < congruents\n", " success_cnt = np.sum(success, 0)\n", "\n", " if return_avg:\n", " perf = np.mean(success_cnt) / (len(all_images)-1)\n", " return perf\n", " else:\n", " return success_cnt, len(all_images)-1\n", " \n", "all_recons=all_recons.to(device)\n", "all_images=all_images.to(device)" ] }, { "cell_type": "markdown", "id": "df6be966-52ef-4cf6-8078-8d2d9617564b", "metadata": {}, "source": [ "## PixCorr" ] }, { "cell_type": "code", "execution_count": 28, "id": "2e17ea38-a254-4e90-a910-711734fdd8eb", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).\n", " warnings.warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "torch.Size([100, 541875])\n", "torch.Size([100, 541875])\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 100/100 [00:00<00:00, 775.96it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0.19027211547192407\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "preprocess = transforms.Compose([\n", " transforms.Resize(425, interpolation=transforms.InterpolationMode.BILINEAR),\n", "])\n", "\n", "# Flatten images while keeping the batch dimension\n", "all_images_flattened = preprocess(all_images).reshape(len(all_images), -1).cpu()\n", "all_recons_flattened = preprocess(all_recons).view(len(all_recons), -1).cpu()\n", "\n", "print(all_images_flattened.shape)\n", "print(all_recons_flattened.shape)\n", "\n", "corr_stack = []\n", "\n", "corrsum = 0\n", "for i in tqdm(range(len(all_images))):\n", " corrcoef = np.corrcoef(all_images_flattened[i], all_recons_flattened[i])[0][1]\n", " if np.isnan(corrcoef):\n", " print(\"WARNING: CORRCOEF WAS NAN\")\n", " corrcoef = 0\n", " corrsum += corrcoef\n", " corr_stack.append(corrcoef)\n", "corrmean = corrsum / len(all_images)\n", "\n", "pixcorr = corrmean\n", "print(pixcorr)" ] }, { "cell_type": "code", "execution_count": 29, "id": "7e2cd891-db44-475d-a8c6-ab345eaa58f8", "metadata": {}, "outputs": [], "source": [ "# print(all_images.shape)\n", "# print(all_images_flattened.shape)\n", "# print(all_recons.shape)\n", "# print(all_recons_flattened.shape)\n", "# len(all_images)" ] }, { "cell_type": "markdown", "id": "7a556d5b-33a2-44aa-b48d-4b168316bbdd", "metadata": { "tags": [] }, "source": [ "## SSIM" ] }, { "cell_type": "code", "execution_count": 30, "id": "2326fc4c-1248-4d0f-9176-218c6460f285", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torchvision/transforms/functional.py:1603: UserWarning: The default value of the antialias parameter of all the resizing transforms (Resize(), RandomResizedCrop(), etc.) will change from None to True in v0.17, in order to be consistent across the PIL and Tensor backends. To suppress this warning, directly pass antialias=True (recommended, future default), antialias=None (current default, which means False for Tensors and True for PIL), or antialias=False (only works on Tensors - PIL will still use antialiasing). This also applies if you are using the inference transforms from the models weights: update the call to weights.transforms(antialias=True).\n", " warnings.warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "converted, now calculating ssim...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 100/100 [00:00<00:00, 120.46it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0.3447461015516486\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# see https://github.com/zijin-gu/meshconv-decoding/issues/3\n", "from skimage.color import rgb2gray\n", "from skimage.metrics import structural_similarity as ssim\n", "\n", "preprocess = transforms.Compose([\n", " transforms.Resize(425, interpolation=transforms.InterpolationMode.BILINEAR), \n", "])\n", "\n", "# convert image to grayscale with rgb2grey\n", "img_gray = rgb2gray(preprocess(all_images).permute((0,2,3,1)).cpu())\n", "recon_gray = rgb2gray(preprocess(all_recons).permute((0,2,3,1)).cpu())\n", "print(\"converted, now calculating ssim...\")\n", "\n", "ssim_score=[]\n", "for im,rec in tqdm(zip(img_gray,recon_gray),total=len(all_images)):\n", " ssim_score.append(ssim(rec, im, multichannel=True, gaussian_weights=True, sigma=1.5, use_sample_covariance=False, data_range=1.0))\n", "\n", "ssim = np.mean(ssim_score)\n", "print(ssim)" ] }, { "cell_type": "markdown", "id": "35138520-ec00-48a6-90dc-249a32a783d2", "metadata": {}, "source": [ "## AlexNet" ] }, { "cell_type": "code", "execution_count": 31, "id": "3b45cc6c-ab80-43e2-b446-c8fcb4fc54e4", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torch/overrides.py:110: UserWarning: 'has_cuda' is deprecated, please use 'torch.backends.cuda.is_built()'\n", " torch.has_cuda,\n", "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torch/overrides.py:111: UserWarning: 'has_cudnn' is deprecated, please use 'torch.backends.cudnn.is_available()'\n", " torch.has_cudnn,\n", "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torch/overrides.py:117: UserWarning: 'has_mps' is deprecated, please use 'torch.backends.mps.is_built()'\n", " torch.has_mps,\n", "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torch/overrides.py:118: UserWarning: 'has_mkldnn' is deprecated, please use 'torch.backends.mkldnn.is_available()'\n", " torch.has_mkldnn,\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "---early, AlexNet(2)---\n", "2-way Percent Correct: 0.8010\n", "\n", "---mid, AlexNet(5)---\n", "2-way Percent Correct: 0.8542\n" ] } ], "source": [ "from torchvision.models import alexnet, AlexNet_Weights\n", "alex_weights = AlexNet_Weights.IMAGENET1K_V1\n", "\n", "alex_model = create_feature_extractor(alexnet(weights=alex_weights), return_nodes=['features.4','features.11']).to(device)\n", "alex_model.eval().requires_grad_(False).to(device)\n", "\n", "# see alex_weights.transforms()\n", "preprocess = transforms.Compose([\n", " transforms.Resize(256, interpolation=transforms.InterpolationMode.BILINEAR),\n", " transforms.Normalize(mean=[0.485, 0.456, 0.406],\n", " std=[0.229, 0.224, 0.225]),\n", "])\n", "\n", "layer = 'early, AlexNet(2)'\n", "print(f\"\\n---{layer}---\")\n", "all_per_correct = two_way_identification(all_recons, all_images, \n", " alex_model, preprocess, 'features.4')\n", "alexnet2 = np.mean(all_per_correct)\n", "print(f\"2-way Percent Correct: {alexnet2:.4f}\")\n", "\n", "layer = 'mid, AlexNet(5)'\n", "print(f\"\\n---{layer}---\")\n", "all_per_correct = two_way_identification(all_recons, all_images, \n", " alex_model, preprocess, 'features.11')\n", "alexnet5 = np.mean(all_per_correct)\n", "print(f\"2-way Percent Correct: {alexnet5:.4f}\")" ] }, { "cell_type": "markdown", "id": "c296bab2-d106-469e-b997-b32d21a2cf01", "metadata": {}, "source": [ "## InceptionV3" ] }, { "cell_type": "code", "execution_count": 32, "id": "5a9c1b2b-af2a-476d-a1ac-32ee915ac2ec", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torchvision/models/feature_extraction.py:174: UserWarning: NOTE: The nodes obtained by tracing the model in eval mode are a subsequence of those obtained in train mode. When choosing nodes for feature extraction, you may need to specify output nodes for train and eval mode separately.\n", " warnings.warn(msg + suggestion_msg)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "2-way Percent Correct: 0.7205\n" ] } ], "source": [ "from torchvision.models import inception_v3, Inception_V3_Weights\n", "weights = Inception_V3_Weights.DEFAULT\n", "inception_model = create_feature_extractor(inception_v3(weights=weights), \n", " return_nodes=['avgpool']).to(device)\n", "inception_model.eval().requires_grad_(False).to(device)\n", "\n", "# see weights.transforms()\n", "preprocess = transforms.Compose([\n", " transforms.Resize(342, interpolation=transforms.InterpolationMode.BILINEAR),\n", " transforms.Normalize(mean=[0.485, 0.456, 0.406],\n", " std=[0.229, 0.224, 0.225]),\n", "])\n", "\n", "all_per_correct = two_way_identification(all_recons, all_images,\n", " inception_model, preprocess, 'avgpool')\n", " \n", "inception = np.mean(all_per_correct)\n", "print(f\"2-way Percent Correct: {inception:.4f}\")" ] }, { "cell_type": "markdown", "id": "d7a25f7f-8298-4413-b512-8a1173413e07", "metadata": {}, "source": [ "## CLIP" ] }, { "cell_type": "code", "execution_count": 33, "id": "6afbf7ce-8793-4988-a328-a632acd88aa9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2-way Percent Correct: 0.7387\n" ] } ], "source": [ "import clip\n", "clip_model, preprocess = clip.load(\"ViT-L/14\", device=device)\n", "\n", "preprocess = transforms.Compose([\n", " transforms.Resize(224, interpolation=transforms.InterpolationMode.BILINEAR),\n", " transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],\n", " std=[0.26862954, 0.26130258, 0.27577711]),\n", "])\n", "\n", "all_per_correct = two_way_identification(all_recons, all_images,\n", " clip_model.encode_image, preprocess, None) # final layer\n", "clip_ = np.mean(all_per_correct)\n", "print(f\"2-way Percent Correct: {clip_:.4f}\")" ] }, { "cell_type": "markdown", "id": "e4fed9f8-ef1a-4c6d-a83f-2a934b6e87fd", "metadata": {}, "source": [ "## Efficient Net" ] }, { "cell_type": "code", "execution_count": 34, "id": "14143c0f-1b32-43ef-98d8-8ed458df4551", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Distance: 0.8597363629795817\n" ] } ], "source": [ "import scipy as sp\n", "from torchvision.models import efficientnet_b1, EfficientNet_B1_Weights\n", "weights = EfficientNet_B1_Weights.DEFAULT\n", "eff_model = create_feature_extractor(efficientnet_b1(weights=weights), \n", " return_nodes=['avgpool'])\n", "eff_model.eval().requires_grad_(False).to(device)\n", "\n", "# see weights.transforms()\n", "preprocess = transforms.Compose([\n", " transforms.Resize(255, interpolation=transforms.InterpolationMode.BILINEAR),\n", " transforms.Normalize(mean=[0.485, 0.456, 0.406],\n", " std=[0.229, 0.224, 0.225]),\n", "])\n", "\n", "gt = eff_model(preprocess(all_images))['avgpool']\n", "gt = gt.reshape(len(gt),-1).cpu().numpy()\n", "fake = eff_model(preprocess(all_recons))['avgpool']\n", "fake = fake.reshape(len(fake),-1).cpu().numpy()\n", "\n", "effnet_nomean = np.array([sp.spatial.distance.correlation(gt[i],fake[i]) for i in range(len(gt))])\n", "effnet = effnet_nomean.mean()\n", "print(\"Distance:\",effnet)" ] }, { "cell_type": "markdown", "id": "405f669d-cab7-4c75-90cd-651283f65a9e", "metadata": {}, "source": [ "## SwAV" ] }, { "cell_type": "code", "execution_count": 35, "id": "4c60b0c4-79fe-4cff-95e9-99733c821e67", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Using cache found in /home/ri4541/.cache/torch/hub/facebookresearch_swav_main\n", "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torchvision/models/_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead.\n", " warnings.warn(\n", "/home/ri4541/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/torchvision/models/_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=None`.\n", " warnings.warn(msg)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Distance: 0.5120611452768613\n" ] } ], "source": [ "swav_model = torch.hub.load('facebookresearch/swav:main', 'resnet50')\n", "swav_model = create_feature_extractor(swav_model, \n", " return_nodes=['avgpool'])\n", "swav_model.eval().requires_grad_(False).to(device)\n", "\n", "preprocess = transforms.Compose([\n", " transforms.Resize(224, interpolation=transforms.InterpolationMode.BILINEAR),\n", " transforms.Normalize(mean=[0.485, 0.456, 0.406],\n", " std=[0.229, 0.224, 0.225]),\n", "])\n", "\n", "gt = swav_model(preprocess(all_images))['avgpool']\n", "gt = gt.reshape(len(gt),-1).cpu().numpy()\n", "fake = swav_model(preprocess(all_recons))['avgpool']\n", "fake = fake.reshape(len(fake),-1).cpu().numpy()\n", "\n", "swav_nomean = np.array([sp.spatial.distance.correlation(gt[i],fake[i]) for i in range(len(gt))])\n", "swav = swav_nomean.mean()\n", "print(\"Distance:\",swav)" ] }, { "cell_type": "code", "execution_count": 36, "id": "8ebeeff0-49ab-4bf5-9e12-dd45eb7ff71f", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 0\n", " metrics\n", " 0.80101\n", " 0.854242\n", " 0.720505\n", " 0.738687\n", " 0.859736\n", " 0.512061\n", " 0.71\n", " 0.7\n", " 0.89\n" ] }, { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: '/scratch/gpfs/ri4541/MindEyeV2/src/mindeyev2/evals/sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0/final_evals'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[36], line 13\u001b[0m\n\u001b[1;32m 11\u001b[0m final_evals_path \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00meval_dir\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m/final_evals\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 12\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m saving:\n\u001b[0;32m---> 13\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28;43mopen\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mfinal_evals_path\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mw\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mas\u001b[39;00m f:\n\u001b[1;32m 14\u001b[0m f\u001b[38;5;241m.\u001b[39mwrite(df)\n\u001b[1;32m 15\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124msaved final evals!\u001b[39m\u001b[38;5;124m'\u001b[39m)\n", "File \u001b[0;32m~/.conda/envs/rt_mindEye2/lib/python3.11/site-packages/IPython/core/interactiveshell.py:324\u001b[0m, in \u001b[0;36m_modified_open\u001b[0;34m(file, *args, **kwargs)\u001b[0m\n\u001b[1;32m 317\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m file \u001b[38;5;129;01min\u001b[39;00m {\u001b[38;5;241m0\u001b[39m, \u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m}:\n\u001b[1;32m 318\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[1;32m 319\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mIPython won\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mt let you open fd=\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mfile\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m by default \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 320\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mas it is likely to crash IPython. If you know what you are doing, \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 321\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124myou can use builtins\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m open.\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 322\u001b[0m )\n\u001b[0;32m--> 324\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mio_open\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfile\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n", "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: '/scratch/gpfs/ri4541/MindEyeV2/src/mindeyev2/evals/sub-001_ses-01_bs24_MST_paul_MSTsplit_random_seed_0/final_evals'" ] } ], "source": [ "#[pixcorr, ssim, alexnet2, alexnet5, inception, clip_, effnet, swav, percent_correct_fwd, percent_correct_bwd]\n", "import pandas as pd\n", "# pd.options.display.float_format = '{:.2%}'.format\n", "# pd.reset_option('all')\n", "if \"ses-0\" not in model_name:\n", " df = pd.DataFrame([\"metrics\", alexnet2, alexnet5, inception, clip_, effnet, swav, fwd_acc, bwd_acc, mst_score]).to_string(index=False)\n", "else:\n", " df = pd.DataFrame([\"metrics\", alexnet2, alexnet5, inception, clip_, effnet, swav, all_fwd_acc[0], all_bwd_acc[0], mst_score]).to_string(index=False)\n", "print(df)\n", "# print(model_name_plus_suffix)\n", "final_evals_path = f\"{eval_dir}/final_evals\"\n", "if saving:\n", " with open(final_evals_path, 'w') as f:\n", " f.write(df)\n", " print('saved final evals!')" ] }, { "cell_type": "code", "execution_count": null, "id": "0446fb2a-fd3f-451f-b9b2-38aa95a2be8d", "metadata": {}, "outputs": [], "source": [ "with open(final_evals_path, 'r') as f:\n", " for line in f:\n", " print(line, end='')\n" ] }, { "cell_type": "code", "execution_count": null, "id": "fd74e27c-6d79-4d49-bcc9-f6b85fadc752", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "rt_mindEye2 [~/.conda/envs/rt_mindEye2/]", "language": "python", "name": "conda_rt_mindeye2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" } }, "nbformat": 4, "nbformat_minor": 5 }