Spaces:
Running
Running
File size: 7,324 Bytes
642d5e2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
#based on https://github.com/CompVis/taming-transformers
import matplotlib.pyplot as plt
import seaborn as sns
import os
from pathlib import Path
import torchvision
import torch
import numpy as np
from PIL import Image
import json
import csv
import pandas as pd
from sklearn.metrics import ConfusionMatrixDisplay
def dump_to_json(dict, ckpt_path, name='results', get_fig_path=True):
if get_fig_path:
root = get_fig_pth(ckpt_path)
else:
root = ckpt_path
if not os.path.exists(root):
os.mkdir(root)
with open(os.path.join(root, name+".json"), "w") as outfile:
json.dump(dict, outfile)
def save_to_cvs(ckpt_path, postfix, file_name, list_of_created_sequence):
if ckpt_path is not None:
root = get_fig_pth(ckpt_path, postfix=postfix)
else:
root = postfix
file = open(os.path.join(root, file_name), 'w')
with file:
write = csv.writer(file)
write.writerows(list_of_created_sequence)
def save_to_txt(arr, ckpt_path, name='results'):
root = get_fig_pth(ckpt_path)
with open(os.path.join(root, name+".txt"), "w") as outfile:
outfile.write(str(arr))
def save_image_grid(torch_images, ckpt_path=None, subfolder=None, postfix="", nrow=10):
if ckpt_path is not None:
root = get_fig_pth(ckpt_path, postfix=subfolder)
else:
root = subfolder
grid = torchvision.utils.make_grid(torch_images, nrow=nrow)
grid = torch.clamp(grid, -1., 1.)
grid = (grid+1.0)/2.0 # -1,1 -> 0,1; c,h,w
grid = grid.transpose(0,1).transpose(1,2).squeeze(-1)
grid = grid.cpu().numpy()
grid = (grid*255).astype(np.uint8)
filename = "code_changes_"+postfix+".png"
path = os.path.join(root, filename)
os.makedirs(os.path.split(path)[0], exist_ok=True)
Image.fromarray(grid).save(path, bbox_inches='tight')
def unprocess_image(torch_image):
torch_image = torch.clamp(torch_image, -1., 1.)
torch_image = (torch_image+1.0)/2.0 # -1,1 -> 0,1; c,h,w
torch_image = torch_image.transpose(0,1).transpose(1,2).squeeze(-1)
torch_image = torch_image.cpu().numpy()
torch_image = (torch_image*255).astype(np.uint8)
return torch_image
def save_image(torch_image, image_name, ckpt_path=None, subfolder=None):
if ckpt_path is not None:
root = get_fig_pth(ckpt_path, postfix=subfolder)
else:
root = subfolder
torch_image = unprocess_image(torch_image)
filename = image_name+".png"
path = os.path.join(root, filename)
os.makedirs(os.path.split(path)[0], exist_ok=True)
fig = plt.figure()
plt.imshow(torch_image[0].squeeze())
fig.savefig(path,bbox_inches='tight',dpi=300)
def get_fig_pth(ckpt_path, postfix=None):
figs_postfix = 'figs'
postfix = os.path.join(figs_postfix, postfix) if postfix is not None else figs_postfix
parent_path = Path(ckpt_path).parent.parent.absolute()
fig_path = Path(os.path.join(parent_path, postfix))
os.makedirs(fig_path, exist_ok=True)
return fig_path
def plot_heatmap(heatmap, ckpt_path=None, title='default', postfix=None):
if ckpt_path is not None:
path = get_fig_pth(ckpt_path, postfix=postfix)
else:
path = postfix
# show
fig = plt.figure()
ax = plt.imshow(heatmap, cmap='hot', interpolation='nearest')
plt.tick_params(left=False, bottom=False)
# cbar = ax.collections[0].colorbar
cbar = plt.colorbar(ax)
cbar.ax.tick_params(labelsize=15)
plt.axis('off')
plt.show()
fig.savefig(os.path.join(path, title+ " heat_map.png"),bbox_inches='tight',dpi=300)
pd.DataFrame(heatmap.numpy()).to_csv(os.path.join(path, title+ " heat_map.csv"))
def plot_heatmap_at_path(heatmap, save_path, ckpt_path=None, title='default', postfix=None):
if ckpt_path is not None:
path = get_fig_pth(ckpt_path, postfix=postfix)
else:
path = postfix
# show
fig = plt.figure()
ax = plt.imshow(heatmap, cmap='hot', interpolation='nearest')
plt.tick_params(left=False, bottom=False)
# cbar = ax.collections[0].colorbar
cbar = plt.colorbar(ax)
cbar.ax.tick_params(labelsize=15)
plt.axis('off')
plt.show()
fig.savefig(os.path.join(save_path, title+ "_heat_map.png"),bbox_inches='tight',dpi=300)
pd.DataFrame(heatmap.numpy()).to_csv(os.path.join(save_path, title+ "_heat_map.csv"))
def plot_confusionmatrix(preds, classes, classnames, ckpt_path, postfix=None, title="", get_fig_path=True):
fig, ax = plt.subplots(figsize=(30,30))
preds_max = np.argmax(preds.cpu().numpy(), axis=-1)
disp = ConfusionMatrixDisplay.from_predictions(classes.cpu().numpy(), preds_max, display_labels=classnames, normalize='true', xticks_rotation='vertical', ax=ax)
disp.plot()
if get_fig_path:
fig_path = get_fig_pth(ckpt_path, postfix=postfix)
else:
fig_path = ckpt_path
if not os.path.exists(fig_path):
os.mkdir(fig_path)
print(fig_path)
fig.savefig(os.path.join(fig_path, title+ " heat_map.png"))
def plot_confusionmatrix_colormap(preds, classes, classnames, ckpt_path, postfix=None, title="", get_fig_path=True):
fig, ax = plt.subplots(figsize=(30,30))
preds_max = np.argmax(preds.cpu().numpy(), axis=-1)
class_labels = list(range(len(classnames)))
disp = ConfusionMatrixDisplay.from_predictions(classes.cpu().numpy(), preds_max, display_labels=class_labels, normalize='true', xticks_rotation='vertical', ax=ax, cmap='coolwarm')
disp.plot()
if get_fig_path:
fig_path = get_fig_pth(ckpt_path, postfix=postfix)
else:
fig_path = ckpt_path
if not os.path.exists(fig_path):
os.mkdir(fig_path)
print(fig_path)
fig.savefig(os.path.join(fig_path, title+ " heat_map_coolwarm.png"))
class Histogram_plotter:
def __init__(self, codes_per_phylolevel, n_phylolevels, n_embed,
converter,
indx_to_label,
ckpt_path, directory):
self.codes_per_phylolevel = codes_per_phylolevel
self.n_phylolevels = n_phylolevels
self.n_embed = n_embed
self.converter = converter
self.ckpt_path = ckpt_path
self.directory = directory
self.indx_to_label = indx_to_label
def plot_histograms(self, histograms, species_indx, is_nonattribute=False, prefix="species"):
fig, axs = plt.subplots(self.codes_per_phylolevel, self.n_phylolevels, figsize = (5*self.n_phylolevels,30))
for i, ax in enumerate(axs.reshape(-1)):
ax.hist(histograms[i], density=True, range=(0, self.n_embed-1), bins=self.n_embed)
if not is_nonattribute:
code_location, level = self.converter.get_code_reshaped_index(i)
ax.set_title("code "+ str(code_location) + "/level " +str(level))
else:
ax.set_title("code "+ str(i))
plt.show()
sub_dir = 'attribute' if not is_nonattribute else 'non_attribute'
fig.savefig(os.path.join(get_fig_pth(self.ckpt_path, postfix=self.directory+'/'+sub_dir), "{}_{}_{}_hostogram.png".format(prefix, species_indx, self.indx_to_label[species_indx])),bbox_inches='tight',dpi=300)
plt.close(fig)
|