Skip to content

Instantly share code, notes, and snippets.

@leondz
Last active August 10, 2021 10:23
Show Gist options
  • Save leondz/d220aaa74140c80c3900674eb3208131 to your computer and use it in GitHub Desktop.
Save leondz/d220aaa74140c80c3900674eb3208131 to your computer and use it in GitHub Desktop.
F-beta score variation animation
#!/usr/bin/env python3
import imageio
import math
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
def fscore(p, r, beta=1):
if p == r == 0:
return 0
return (1+beta**2) * (p * r) / ( (beta**2 * p) + r)
def populate_matrix(operator):
steps = [x/100 for x in range(0, 101)]
matrix = []
for step_p in steps:
row = []
for step_r in steps:
row.append(operator(step_p, step_r))
matrix.append(list(row))
return np.array(matrix)
def show_array(data, title='Title', labelx='recall', labely='precision', saveas=False, show=True):
cmap = 'seismic'
plt.figure(figsize=(9, 9))
plt.imshow(data, cmap=cmap, interpolation='nearest', origin='lower')
plt.title(title)
plt.xlabel(labelx)
plt.ylabel(labely)
plt.colorbar(plt.pcolor(data, cmap=cmap))
if saveas:
plt.savefig(saveas)
if show:
plt.show()
plt.close()
def fbeta_global(p,r):
global global_beta
return fscore(p,r,global_beta)
seq = 0
for i in range(-40, 41):
global_beta = math.pow(2, i/10)
f_ = populate_matrix(fbeta_global)
show_array(f_, title=f'F-score, beta={global_beta:.3f}', saveas=f'fbeta_{seq:04}.png', show=False)
seq += 1
image_path = Path('.')
images = list(image_path.glob('fbeta_????.png'))
images.sort()
image_list = []
for file_name in images:
image_list.append(imageio.imread(file_name))
# get the reverse pass in there too
loop_back = image_list[1:-1]
loop_back.reverse()
looped_images = image_list + loop_back
imageio.mimwrite('fbeta.gif', looped_images, fps=12)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment