code stringlengths 17 6.64M |
|---|
def main():
script_dir = os.path.dirname(os.path.abspath(__file__))
raw_images_root = os.path.join(script_dir, 'icons8_raw')
final_images_root = os.path.join(script_dir, 'icons8')
final_size = (28, 28)
resample_strategy = Image.NEAREST
for category in os.listdir(raw_images_root):
if (n... |
def get_qualities(f, repeats):
'\n Get map of quality ratings from CSV file of annotations\n\n :param f: path to CSV annotations\n :return: map of filenames to quality ratings\n '
quality_dict = {}
with open(f, 'r') as csv_fp:
csv_reader = csv.DictReader(csv_fp)
for row in csv_... |
def count_qualities(q1, q2):
'\n Get map of quality ratings from CSV file of annotations\n\n :param q1: first quality map\n :param q2: second quality map\n :return: list of total qualities from both annotators\n '
quality_counts = [0, 0, 0, 0]
for key in q1.keys():
quality = q1[key]... |
def calculate_po(q1, q2):
"\n Calculate Po for Cohen's Kappa\n\n :param q1: first quality map\n :param q2: second quality map\n :return: Po\n "
total = 0
agreed = 0
mismatched = []
for f in q1.keys():
total += 1
if (q1[f] == q2[f]):
agreed += 1
el... |
def get_proportions(q):
'\n Get proportion of each quality score\n\n :param q: quality score map\n :return: map of proportions of each class\n '
total = 0
p_map = {GOOD: 0, POOR: 0, FAIR: 0, UNSATISFACTORY: 0}
for f in q.keys():
p_map[q[f]] = (p_map[q[f]] + 1)
total += 1
... |
def calculate_pe(p1, p2):
"\n Calculate Pe for Cohen's Kappa\n\n :param p1: quality proportions for first annotator\n :param p2: quality proportions for second annotator\n :return: Pe\n "
p_poor = (p1[POOR] * p2[POOR])
p_fair = (p1[FAIR] * p2[FAIR])
p_uns = (p1[UNSATISFACTORY] * p2[UNSA... |
def convert_2d_segmentation_nifti_to_img(nifti_file: str, output_filename: str, transform=None, export_dtype=np.uint8):
img = sitk.GetArrayFromImage(sitk.ReadImage(nifti_file))
assert (img.shape[0] == 1), 'This function can only export 2D segmentations!'
img = img[0]
if (transform is not None):
... |
def create_masks(mask_dict, img_path, mask1_path, mask2_path):
'\n Create and save masks from annotations\n\n :param mask_dict: dictionary of polygon annotations\n :param img_path: path to image file\n :param mask1_path: path for capsule mask\n :param mask2_path: path for region mask\n '
for... |
def process_file(annotation_file):
'\n Extract region shape information from annotation file\n\n :param annotation_file: CSV file of annotations\n :return: dictionary of extracted information\n '
filename = ''
mask_dict = {}
with open(annotation_file, 'r') as csv_fp:
csv_reader = c... |
def get_dsc_coef(pair, capsule_path, region_path):
'\n Compute DSC scores for given masks\n\n :param pair: set of images to compare\n :param capsule_path: path to region mask for first segmentation\n :param region_path: path to capsule mask for second segmentation\n :return: list of DSC scores for ... |
def get_hd(pair, capsule_path, region_path, conversion):
'\n Compute Hausdorff distance for given masks\n\n :param pair: set of images to compare\n :param capsule_path: path to region mask for first segmentation\n :param region_path: path to capsule mask for second segmentation\n :param conversion:... |
def get_point_nums(f):
'\n Get number of points for each image in annotation file\n\n :param f: path to annotation file\n :return: map of image to the number of points per class\n '
point_dict = {}
with open(f, 'r') as csv_fp:
csv_reader = csv.DictReader(csv_fp)
for row in csv_... |
def get_percent_change(val1, val2):
if (val1 == 0):
return 0
else:
return abs(((100 * (val2 - val1)) / val1))
|
def get_mask_sensitivity(regions):
coefs = []
for i in range(2, 5):
new_coefs = []
masks = generate_masks(None, regions, i, 2)
new_coefs.append(compute_dsc(masks[0], masks[1]))
kernel = np.ones((3, 3), np.uint8)
og_mask = masks[1].copy().astype('uint8')
masks[1]... |
def get_views(f):
'\n Get view counts from given annotation file\n\n :param f: VGG annotations file\n :return: dictionary of views for each file\n '
view_dict = {}
with open(f, 'r') as csv_fp:
csv_reader = csv.DictReader(csv_fp)
for row in csv_reader:
filename = row... |
def restrict_segmentations(mask_path, output_path):
cap_img_path = os.path.join(mask_path, 'capsule')
reg_img_path = os.path.join(mask_path, 'regions')
maybe_mkdir(os.path.join(output_path, 'capsule'))
maybe_mkdir(os.path.join(output_path, 'regions'))
for f in os.listdir(cap_img_path):
cap... |
def clean_segmentations(mask_path, output_path):
cap_img_path = os.path.join(mask_path, 'capsule')
reg_img_path = os.path.join(mask_path, 'regions')
maybe_mkdir(os.path.join(output_path, 'capsule'))
maybe_mkdir(os.path.join(output_path, 'regions'))
for f in os.listdir(cap_img_path):
cap_im... |
def str_to_bool(value):
if isinstance(value, bool):
return value
if (value.lower() in {'false', 'f', '0', 'no', 'n'}):
return False
elif (value.lower() in {'true', 't', '1', 'yes', 'y'}):
return True
raise ValueError(f'{value} is not a valid boolean value')
|
def maybe_mkdir(directory):
if (not os.path.exists(directory)):
os.mkdir(directory)
|
def number_image(filename, name):
if (name not in patient_map):
patient_map[name] = len(patient_map)
return ((str(patient_map[name]) + '_') + filename)
|
def mask_and_convert_to_png(dcm_path, args, filename):
'\n Masks and saves dicom at given path to new anonymized png file\n\n :param dcm_path: path to DICOM file to process\n :param args: script arguments\n :param filename: filename to save to\n '
dicom = None
filenames = []
included_pa... |
def mask_and_save_to_dicom(dcm_path, args, filename):
'\n Masks and saves dicom at given path to new anonymized DICOM file\n\n :param dcm_path: path to DICOM file to process\n :param args: script arguments\n :param filename: filename to save to\n '
dicom = Dicom(dcm_path)
metadata = dicom.m... |
def mask_and_save_to_nii(dcm_path, args, filename):
'\n Masks and saves dicom at given path to new anonymized nifty file\n\n :param dcm_path: path to DICOM file to process\n :param args: script arguments\n :param filename: filename to save to\n '
dicom = None
filenames = []
included_pat... |
def maybe_mkdir(dirname):
if (not os.path.exists(dirname)):
os.makedirs(dirname)
|
def write_rows_to_file(csv_file, rows):
'\n Write given rows of data to CSV file\n\n :param csv_file: path to output CSV files\n :param rows: rows of data to write to file\n '
with open(csv_file, 'w', newline='') as fp:
csv_writer = csv.writer(fp)
for row in rows:
csv_w... |
def format_floats_for_csv(l):
new_l = []
for num in l:
truncated_num = float(('%.2f' % num))
new_l.append(truncated_num)
return new_l
|
def estimate_nakagami(arr):
arr = arr.astype(np.int64)
N = arr.size
arr2 = np.square(arr)
arr4 = np.square(arr2)
e_x2 = (np.sum(arr2) / N)
e_x4 = (np.sum(arr4) / N)
nak_scale = e_x2
if ((e_x4 - (e_x2 ** 2)) == 0):
nak_shape = 0
else:
nak_shape = ((e_x2 ** 2) / (e_x4... |
def compute_nak_for_mask(img, mask, num_classes):
all_nak_params = []
for i in range(1, (num_classes + 1)):
pixels = img[np.where((mask == i))]
nak_params = estimate_nakagami(pixels)
all_nak_params.append(nak_params)
return all_nak_params
|
def compute_snr_for_mask(img, mask, num_classes):
all_snr = []
for i in range(1, (num_classes + 1)):
pixels = img[np.where((mask == i))]
if (pixels.size > 0):
mean = np.mean(pixels)
std = np.std(pixels)
snr = np.log10((mean / std))
else:
... |
def kl_divergence(p, q):
'\n Taken from https://towardsdatascience.com/kl-divergence-python-example-b87069e4b810\n '
return np.sum(np.where((p != 0), (p * np.log((p / q))), 0))
|
def compute_nakagami_kl_divergence(params1, params2):
lim = (max(params1[1], params2[1]) * 4)
x = np.arange(0.01, lim, 0.01)
p = nakagami.pdf(x, params1[0], loc=0, scale=params2[1])
q = nakagami.pdf(x, params2[0], loc=0, scale=params2[1])
if ((params1[0] == 0) and (params1[1] == 0) and (params2[0]... |
def get_dsc_coef(capsule1_path, region1_path, capsule2_path, region2_path):
'\n Compute DSC coefficient for given masks\n\n :param capsule1_path: path to capsule mask for first segmentation\n :param region1_path: path to region mask for first segmentation\n :param capsule2_path: path to capsule mask f... |
def generate_score_csv(path1, path2, outpath, score_func=get_dsc_coef):
'\n Compute DSC coefficients for mask pairs at given paths and save to\n CSV file\n\n :param path1: path first set of masks\n :param path2: path to second set of masks\n :param outpath: path to DSC score CSV file\n '
wit... |
def get_precision(capsule1_path, region1_path, capsule2_path, region2_path):
'\n Compute precision for given masks\n\n :param capsule1_path: path to capsule mask for first segmentation\n :param region1_path: path to region mask for first segmentation\n :param capsule2_path: path to capsule mask for se... |
def get_recall(capsule1_path, region1_path, capsule2_path, region2_path):
'\n Compute recall for given masks\n\n :param capsule1_path: path to capsule mask for first segmentation\n :param region1_path: path to region mask for first segmentation\n :param capsule2_path: path to capsule mask for second s... |
def get_hd(capsule1_path, region1_path, capsule2_path, region2_path, conversion):
'\n Compute Hausdorff distance for given masks\n\n :param capsule1_path: path to capsule mask for first segmentation\n :param region1_path: path to region mask for first segmentation\n :param capsule2_path: path to capsu... |
def generate_hd_csv(path1, path2, converter, outpath):
'\n Compute Hausdorff distances for mask pairs at given paths and save to\n CSV file\n\n :param path1: path first set of masks\n :param path2: path to second set of masks\n :param converter: map of pixel to mm conversions\n :param outpath: p... |
def get_conversions(conversion_file):
'\n Build dictionary containing pixel to mm conversions\n\n :param conversion_file: CSV file containing pixel to mm conversions\n :return: dictionary of pixel to mm conversions\n '
conversions = {}
with open(conversion_file, 'r') as csv_fp:
csv_rea... |
def get_repeat_sets(csv_file):
'\n Get sets of repeated files for intrarater variability\n\n :param csv_file: CSV file with sets of repeated files\n :return: list of lists of repeated filesets\n '
files = []
with open(csv_file, 'r') as csv_fp:
csv_reader = csv.DictReader(csv_fp)
... |
def get_repeats(csv_file):
'\n Get list of repeated files\n\n :param csv_file: CSV file with sets of repeated files\n :return: list of repeated files to exclude\n '
files = []
with open(csv_file, 'r') as csv_fp:
csv_reader = csv.DictReader(csv_fp)
for row in csv_reader:
... |
def generate_masks(capsules, regions, cls, num):
'\n Get separated masks for each class from segmentation file\n\n :param capsules: capsule segmentation\n :param regions: regions segmentation\n :param cls: class to extract\n :param num: number of segmentations in list\n :return: masks for specif... |
def compute_dsc(mask1, mask2):
'\n Compute DSC score for given masks\n\n :param mask1: first mask\n :param mask2: second mask\n :return: DSC score\n '
intersection = np.logical_and(mask1, mask2)
if ((mask1.sum() + mask2.sum()) != 0):
dsc_coef = ((2 * intersection.sum()) / (mask1.sum... |
def compute_precision(pred, truth):
'\n Compute precision for given masks\n\n :param mask1: first mask\n :param mask2: second mask\n :return: precision\n '
tp = np.logical_and(truth, pred).sum()
fp = np.logical_and(np.logical_not(truth), pred).sum()
if (tp.sum() == 0):
precision... |
def compute_recall(pred, truth):
'\n Compute precision for given masks\n\n :param mask1: first mask\n :param mask2: second mask\n :return: recall\n '
tp = np.logical_and(truth, pred).sum()
fn = np.logical_and(truth, np.logical_not(pred)).sum()
if (tp.sum() == 0):
recall = 0.0
... |
def compute_hd(mask1, mask2):
'\n Compute Hausdorff distance for given masks\n\n :param mask1: first mask\n :param mask2: second mask\n :return: Hausdorff distance\n '
if ((mask1.sum() > 0) and (mask2.sum() > 0)):
hausdorff_distance_filter = sitk.HausdorffDistanceImageFilter()
i... |
class Wrapper():
def __init__(self, d):
self.d = d
def __getattr__(self, x):
return self.d[x]
|
class HereBeDragons():
d = {}
FLAGS = Wrapper(d)
def __getattr__(self, x):
return self.do_define
def do_define(self, k, v, *x):
self.d[k] = v
|
def db(audio):
if (len(audio.shape) > 1):
maxx = np.max(np.abs(audio), axis=1)
return ((20 * np.log10(maxx)) if np.any((maxx != 0)) else np.array([0]))
maxx = np.max(np.abs(audio))
return ((20 * np.log10(maxx)) if (maxx != 0) else np.array([0]))
|
def load_wav(input_wav_file):
(fs, audio) = wav.read(input_wav_file)
assert (fs == 16000)
print('source dB', db(audio))
return audio
|
def save_wav(audio, output_wav_file):
wav.write(output_wav_file, 16000, np.array(np.clip(np.round(audio), (- (2 ** 15)), ((2 ** 15) - 1)), dtype=np.int16))
print('output dB', db(audio))
|
def levenshteinDistance(s1, s2):
if (len(s1) > len(s2)):
(s1, s2) = (s2, s1)
distances = range((len(s1) + 1))
for (i2, c2) in enumerate(s2):
distances_ = [(i2 + 1)]
for (i1, c1) in enumerate(s1):
if (c1 == c2):
distances_.append(distances[i1])
... |
def highpass_filter(data, cutoff=7000, fs=16000, order=10):
(b, a) = butter(order, (cutoff / (0.5 * fs)), btype='high', analog=False)
return lfilter(b, a, data)
|
def get_new_pop(elite_pop, elite_pop_scores, pop_size):
scores_logits = np.exp((elite_pop_scores - elite_pop_scores.max()))
elite_pop_probs = (scores_logits / scores_logits.sum())
cand1 = elite_pop[np.random.choice(len(elite_pop), p=elite_pop_probs, size=pop_size)]
cand2 = elite_pop[np.random.choice(l... |
def mutate_pop(pop, mutation_p, noise_stdev, elite_pop):
noise = (np.random.randn(*pop.shape) * noise_stdev)
noise = highpass_filter(noise)
mask = (np.random.rand(pop.shape[0], elite_pop.shape[1]) < mutation_p)
new_pop = (pop + (noise * mask))
return new_pop
|
class Genetic():
def __init__(self, input_wave_file, output_wave_file, target_phrase):
self.pop_size = 100
self.elite_size = 10
self.mutation_p = 0.005
self.noise_stdev = 40
self.noise_threshold = 1
self.mu = 0.9
self.alpha = 0.001
self.max_iters = ... |
def buildOrigCDFs(f, g):
global F
global G
global n
global m
F = np.sort(f)
n = len(F)
G = np.sort(g)
m = len(G)
|
def buildNewCDFs(f, g):
global Fb
global Gb
Fb = np.sort(f)
Gb = np.sort(g)
|
def invG(p):
index = int(np.ceil((p * m)))
if (index >= m):
return G[(m - 1)]
elif (index == 0):
return G[0]
return G[(index - 1)]
|
def invF(p):
index = int(np.ceil((p * n)))
if (index >= n):
return F[(n - 1)]
elif (index == 0):
return F[0]
return F[(index - 1)]
|
def invGnew(p, M):
index = int(np.ceil((p * M)))
if (index >= M):
return Gb[(M - 1)]
elif (index == 0):
return Gb[0]
return Gb[(index - 1)]
|
def invFnew(p, N):
index = int(np.ceil((p * N)))
if (index >= N):
return Fb[(N - 1)]
elif (index == 0):
return Fb[0]
return Fb[(index - 1)]
|
def epsilon(dp):
s = 0.0
se = 0.0
for p in np.arange(0, 1, dp):
temp = (invG(p) - invF(p))
tempe = max(temp, 0)
s = (s + ((temp * temp) * dp))
se = (se + ((tempe * tempe) * dp))
if (s != 0):
return (se / s)
else:
print('The denominator is 0')
... |
def epsilonNew(dp, N, M):
denom = 0.0
numer = 0.0
for p in np.arange(0, 1, dp):
diff = (invGnew(p, M) - invFnew(p, N))
posdiff = max(diff, 0)
denom += ((diff * diff) * dp)
numer += ((posdiff * posdiff) * dp)
if (denom != 0.0):
return (numer / denom)
else:
... |
def COS(data_A, data_B):
print('AVG ', np.average(data_A), np.average(data_B))
print('STD ', np.std(data_A), np.std(data_B))
print('MEDIAN ', np.median(data_A), np.median(data_B))
print('MIN ', np.min(data_A), np.min(data_B))
print('MAX ', np.max(data_A), np.max(data_B))
|
def MannWhitney(data_A, data_B):
if ((n < 20) or (m < 20)):
print('Use only when the number of observation in each sample is > 20')
return 1.0
(_, pval) = Utest(data_A, data_B, alternative='less')
return pval
|
def main():
if (len(sys.argv) < 3):
print('Not enough arguments\n')
sys.exit()
filename_A = sys.argv[1]
filename_B = sys.argv[2]
alpha = float(sys.argv[3])
with open(filename_A) as f:
data_A = f.read().splitlines()
with open(filename_B) as f:
data_B = f.read().s... |
class InputFeatures(object):
'A single set of features of data.'
def __init__(self, input_ids, head_span, tail_span, token_masks):
self.input_ids = input_ids
self.head_span = head_span
self.tail_span = tail_span
self.token_masks = token_masks
|
class Instance(object):
def __init__(self, words, relation, head, tail, headpos, tailpos, headtype, tailtype, ner=None, is_noise=None):
self.words = words
self.relation = relation
self.head = head
self.tail = tail
self.headpos = headpos
self.tailpos = tailpos
... |
class Data():
def __init__(self, args, mode='train'):
if (mode == 'train'):
data_file = args.train_data_file
elif (mode == 'test'):
data_file = args.test_data_file
elif (mode == 'dev'):
data_file = args.dev_data_file
elif (mode == 'test_noise'):... |
class InputFeatures(object):
'A single set of features of data.'
def __init__(self, input_ids, head_span, tail_span, token_masks):
self.input_ids = input_ids
self.head_span = head_span
self.tail_span = tail_span
self.token_masks = token_masks
|
class Instance(object):
def __init__(self, words, relation, head, tail, headpos, tailpos, headtype, tailtype, d_rel='', ner=None, is_noise=None):
self.words = words
self.relation = relation
self.head = head
self.tail = tail
self.headpos = headpos
self.tailpos = tai... |
class Data():
def __init__(self, args, mode='train'):
if (mode == 'train'):
data_file = args.train_data_file
elif (mode == 'test'):
data_file = args.test_data_file
elif (mode == 'dev'):
data_file = args.dev_data_file
elif (mode == 'test_noise'):... |
class WordTokenizer(object):
'Runs WordPiece tokenziation.'
def __init__(self, vocab=None, unk_token='[UNK]', pad_token='[PAD]'):
self.vocab = load_vocab(vocab)
self.inv_vocab = {v: k for (k, v) in self.vocab.items()}
self.unk_token = unk_token
self.pad_token = pad_token
... |
def is_whitespace(char):
' Checks whether `chars` is a whitespace character.\n \t, \n, and \r are technically contorl characters but we treat them\n as whitespace since they are generally considered as such.\n '
if ((char == ' ') or (char == '\t') or (char == '\n') or (char == '\r')):
... |
def is_control(char):
' Checks whether `chars` is a control character.\n These are technically control characters but we count them as whitespace characters.\n '
if ((char == '\t') or (char == '\n') or (char == '\r')):
return False
cat = unicodedata.category(char)
if cat.startswit... |
def is_punctuation(char):
' Checks whether `chars` is a punctuation character.\n We treat all non-letter/number ASCII as punctuation. Characters such as "^", "$", and "`" are not in the Unicode.\n Punctuation class but we treat them as punctuation anyways, for consistency.\n '
cp = ord(char)
... |
def is_chinese_char(cp):
' Checks whether CP is the codepoint of a CJK character.\n This defines a "chinese character" as anything in the CJK Unicode block:\n https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n Note that the CJK Unicode block is NOT all Japanese and Kore... |
def convert_to_unicode(text):
"Converts `text` to Unicode (if it's not already), assuming utf-8 input."
if six.PY3:
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode('utf-8', 'ignore')
else:
raise ValueError(('Uns... |
def clean_text(text):
output = []
for char in text:
cp = ord(char)
if ((cp == 0) or (cp == 65533) or is_control(char)):
continue
if is_whitespace(char):
output.append(' ')
else:
output.append(char)
return ''.join(output)
|
def split_on_whitespace(text):
" Runs basic whitespace cleaning and splitting on a peice of text.\n e.g, 'a b c' -> ['a', 'b', 'c']\n "
text = text.strip()
if (not text):
return []
return text.split()
|
def split_on_punctuation(text):
'Splits punctuation on a piece of text.'
start_new_word = True
output = []
for char in text:
if is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([... |
def tokenize_chinese_chars(text):
'Adds whitespace around any CJK character.'
output = []
for char in text:
cp = ord(char)
if is_chinese_char(cp):
output.append(' ')
output.append(char)
output.append(' ')
else:
output.append(char)
... |
def strip_accents(text):
'Strips accents from a piece of text.'
text = unicodedata.normalize('NFD', text)
output = []
for char in text:
cat = unicodedata.category(char)
if (cat == 'Mn'):
continue
output.append(char)
return ''.join(output)
|
def load_vocab(vocab_file):
vocab = json.load(open(vocab_file))
return vocab
|
def printable_text(text):
" Returns text encoded in a way suitable for print or `tf.logging`.\n These functions want `str` for both Python2 and Python3, but in one case\n it's a Unicode string and in the other it's a byte string.\n "
if six.PY3:
if isinstance(text, str):
... |
def convert_by_vocab(vocab, items, max_seq_length=None, blank_id=0, unk_id=1, uncased=True):
'Converts a sequence of [tokens|ids] using the vocab.'
output = []
unk_num = 0
for item in items:
if uncased:
item = item.lower()
if (item in vocab):
output.append(vocab... |
def convert_tokens_to_ids(vocab, tokens, max_seq_length=None, blank_id=0, unk_id=1):
return convert_by_vocab(vocab, tokens, max_seq_length, blank_id, unk_id)
|
def convert_ids_to_tokens(inv_vocab, ids):
return convert_by_vocab(inv_vocab, ids)
|
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
'Truncates a pair of sequences to a maximum sequence length.'
while True:
total_length = (len(tokens_a) + len(tokens_b))
if (total_length <= max_num_tokens):
break
trunc_tokens = (tokens_a if (len(tokens_a) > l... |
def create_int_feature(values):
feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return feature
|
def create_float_feature(values):
feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
return feature
|
def add_token(tokens_a, tokens_b=None):
assert (len(tokens_a) >= 1)
tokens = []
segment_ids = []
tokens.append('[CLS]')
segment_ids.append(0)
for token in tokens_a:
tokens.append(token)
segment_ids.append(0)
tokens.append('[SEP]')
segment_ids.append(0)
if (tokens_b ... |
def parse_arguments():
parser = argparse.ArgumentParser(description='Score a prediction file using the gold labels.')
parser.add_argument('gold_file', help='The gold relation file; one relation per line')
parser.add_argument('pred_file', help='A prediction file; one relation per line, in the same order as... |
def score(key, prediction, verbose=False, NO_RELATION='NA'):
correct_by_relation = Counter()
guessed_by_relation = Counter()
gold_by_relation = Counter()
for row in range(len(key)):
gold = key[row]
guess = prediction[row]
if ((gold == NO_RELATION) and (guess == NO_RELATION)):
... |
def curve(y_scores, y_true, num=2000):
order = np.argsort(y_scores)[::(- 1)]
guess = 0.0
right = 0.0
target = np.sum(y_true)
precisions = []
recalls = []
for o in order[:num]:
guess += 1
if (y_true[o] == 1):
right += 1
precision = (right / guess)
... |
def AUC_and_PN(y_scores, y_true):
(recalls, precisions) = curve(y_scores, y_true, 3000)
recalls_01 = recalls[(recalls < 0.1)]
precisions_01 = precisions[(recalls < 0.1)]
AUC_01 = auc(recalls_01, precisions_01)
recalls_02 = recalls[(recalls < 0.2)]
precisions_02 = precisions[(recalls < 0.2)]
... |
def bag_eval(pred_result, facts):
"\n Args:\n pred_result: a list with dict {'entpair': (head_id, tail_id), 'relation': rel, 'score': score}.\n Note that relation of NA should be excluded.\n Return:\n {'prec': narray[...], 'rec': narray[...], 'mean_prec': xx, 'f1': xx, 'auc': xx}\n ... |
class SENT_Model(nn.Module):
def __init__(self, options, vocab_file=None):
super(SENT_Model, self).__init__()
self.max_sent_len = options.max_len
self.pos_emb_dim = 50
self.ner_label_size = options.ner_label_size
self.ner_emb_dim = 50
self.vocab_size = options.voca... |
class SENT_Model(nn.Module):
def __init__(self, options, vocab_file=None):
super(SENT_Model, self).__init__()
self.max_sent_len = options.max_len
self.pos_emb_dim = 50
self.ner_label_size = options.ner_label_size
self.ner_emb_dim = 50
self.vocab_size = options.voca... |
def load_data(args, mode='train'):
data_path = (((args.save_data_path + '.') + mode) + '.data')
if os.path.exists(data_path):
print('Loading {} data from {}...'.format(mode, data_path))
with open(data_path, 'rb') as f:
data = pickle.load(f)
else:
data = Data(args, mode)... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 4