code
stringlengths
17
6.64M
class White(nn.Module): def __init__(self, dim, variance=1.0): super(White, self).__init__() self.dim = torch.tensor([dim], requires_grad=False) self.variance = torch.nn.Parameter(transform_backward(torch.tensor([variance]))) def forward(self, X, X2=None): if (X2 is None): ...
class Add(nn.Module): def __init__(self, k1, k2): super(Add, self).__init__() self.k1 = k1 self.k2 = k2 @property def variance(self): return transform_backward((transform_forward(self.k1.variance) + transform_forward(self.k2.variance))) def forward(self, X, X2=None):...
class Sparse1DTensor(): def __init__(self, y, ix): self.v = torch.tensor(y, dtype=dtype, requires_grad=False) ix_tensor = torch.tensor(ix) assert (self.v.numel() == ix_tensor.numel()), 'inputs must be same size' self.ix = {ix_tensor[i].item(): i for i in torch.arange(self.v.numel(...
class BatchIndices(): def __init__(self, N=None, ix=None, B=None): assert ((N is not None) or (ix is not None)), 'either N or ix should be provided' if ((N is not None) and (ix is not None)): assert (N == ix.numel()), 'N must = size of ix' self.N = N self.ix = ...
def main(): parser = ArgumentParser() parser.add_argument('--mode', default='train') parser.add_argument('--save_dir', default='logire-save') parser.add_argument('--train_batch_size', type=int, default=4) parser.add_argument('--test_batch_size', type=int, default=4) parser.add_argument('--Ns',...
class FeatureReader(object): def __init__(self, data_path) -> None: self.data = torch.load(data_path) def read(self, split='train'): return self.data[split]
class TextReader(object): 'read text feature' 'read and store DocRED data' def __init__(self, data_dir, save_dir, tokenizer) -> None: self.data_dir = data_dir self.save_dir = save_dir if (not os.path.exists(self.save_dir)): os.makedirs(self.save_dir) with open(...
class ERuleReader(object): 'read text feature' 'read and store DocRED data' def __init__(self, data_dir, save_dir, max_step=3) -> None: self.data_dir = data_dir self.save_dir = save_dir if (not os.path.exists(self.save_dir)): os.makedirs(self.save_dir) self.rel...
def append_chain(chains, rs): ret = [] for (chain, chain_nodes) in chains: for (r, rnode) in rs: if (rnode[0] not in chain_nodes): ret.append(((chain + r), (chain_nodes + rnode))) return ret
class BratConverter(): '\n Encapsulates the paths to convert SORE filtered files to BRAT annotations (for visualisation of results).\n ' def __init__(self, paths_to_datasets, narrowIE_path, SORE_processed_path, BRAT_output_path): '\n Initialise BratConverter with relevant paths.\n\n ...
class NarrowIEOpenIECombiner(object): '\n Encapsulates paths and settings for SORE filtering.\n ' def __init__(self, oie_data_dir, IDF_path, csv_path, SUBWORDUNIT, sp_size, number_of_clusters=50, stemming=False, stopwords=True, SUBWORD_UNIT_COMBINATION='avg', path_to_embeddings=None): '\n ...
class PrepIDFWeights(): '\n Encapsulates the setting for preparing IDF weights.\n ' def __init__(self, prefix, input_file_dir, output_dir, SUBWORDUNIT=True, STEMMING=False, STOPWORDS=False): '\n Initialise with desired settings.\n\n :param prefix: Experiment name.\n :param ...
def clean_dict(content): '\n Simple cleaning of the sentences found in the input files. Is called twice, during creation of\n OIE and narrowIE files.\n\n :param content: a dict containing {sent_id : sentence}\n :return content: a dict containing {sent_id : sentence}, where the sentences have been clea...
def write_sentences_to_txt_file(input_dict, output_folder): '\n Reads the json input from a dataset file and prepares separate text files for OIE.\n\n :param input_dict: A json-file containing unprocessed papers.\n :param output_folder: Directory to write a txt file to, for each of the document IDs found...
def convert_doc_to_sciie_format(input_dict): '\n Reads an unprocessed json file and prepares a list of sentences in the SciIE format\n\n :param input_dict: A dataset json-file containing unprocessed papers.\n :return: processed_sentences - a list of sentences ready to be input to a trained SciIE model\n ...
def quote_merger(doc): matched_spans = [] matches = matcher(doc) for (match_id, start, end) in matches: span = doc[start:end] matched_spans.append(span) for span in matched_spans: span.merge() return doc
def spacy_nlp(too_be_parsed): "\n Instantiate a Spacy nlp parser (spacy.load('en_core_web_sm', disable=['ner','tagger']), which matches a couple\n of 'trade-off' expressions as single tokens - rather than ['trade', '-', 'off'].\n\n :param too_be_parsed: Some string to be parsed, could be single or multip...
def convert_spans_to_tokenlist(predicted_spans, corresponding_data): '\n Converts the spans of relations found in a sentence to a list of tokens\n\n :param predicted_spans: SciIE output, formatted with span_start and span_end as token indices.\n :param corresponding_data: SciIE input file, which contains...
def simple_tokens_to_string(tokenlist): '\n Convert a list of tokens to a string.\n\n :param tokenlist: A list of tokens from the spacy parser\n :return : A string with all tokens concatenated, simply separated by a space.\n ' return ' '.join((x for x in tokenlist if ((x != '<s>') and (x != '</s>'...
def read_sciie_output_format(data_doc, predictions_doc, RELATIONS_TO_STORE): "\n Reads the SciIE input and predictions, and prepares a list of arguments to write to a csv file. Choices for RELATIONS_TO_STORE:\n * ALL - Use all narrow IE arguments and relations found in all documents.\n * TRADEOFFS - ...
def start_parsing(data, pred, output_csv, RELATIONS_TO_STORE): '\n Start the parsing of a single set of narrow IE predictions, and write these to a temporary CSV file.\n The CSV file will be combined with others into one large CSV. Choices for RELATIONS_TO_STORE:\n * ALL - Use all narrow IE arguments a...
def write_dicts_to_files(num_docs, dict_with_various_docs, input_doc, index, old_index, output_folder_OIE, output_folder_narrowIE): '\n Call :func:`~SORE.my_utils.convert_json_article_to_SciIE.convert_doc_to_sciie_format` (and write the results) and\n :func:`~SORE.my_utils.convert_json_article_to_OIE5.write...
def convert_documents(max_num_docs_narrowIE, input_files, output_folder_OIE, output_folder_narrowIE): '\n Reads an unprocessed json file and prepares the input document for narrow and open IE. Scraped\n text in JEB and BMC files is processed to single-sentence-dict:\n # {"doc_id": {"sent_id": {"sente...
class OpenIE5_client(object): '\n Encapsulates functionality to query the Open IE 5 standalone server.\n ' def __init__(self, csv_path, oie_data_dir, path_to_OIE_jar): '\n Initialise with relevant paths.\n\n :param csv_path: The narrow IE predictions CSV file holds the document id...
def run_OpenIE_5(csv_path, path_to_OIE_jar=None, unprocessed_paths='SORE/data/OpenIE/'): "\n To run OpenIE5 a local server has to be started and queried. Not sure if python's GIL allows running these from a single script.\n\n :param csv_path: Path to the CSV with narrow IE predictions - only documents with ...
class GithubURLDomain(Domain): '\n Resolve certain links in markdown files to github source.\n ' name = 'githuburl' ROOT = 'https://github.com/tensorpack/tensorpack/blob/master/' def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): github_url = None if ...
def setup(app): from recommonmark.transform import AutoStructify app.add_config_value('recommonmark_config', {'enable_auto_toc_tree': True}, True) app.add_transform(AutoStructify) app.add_domain(GithubURLDomain)
class DataPreparation(): '\n Encapsulates the path to the input dataset, as well as paths to write files that can be processed\n by narrow IE and Open IE systems.\n ' def __init__(self, unprocessed_data_path='SORE/data/unprocessed_data/', output_folder_narrowIE='SORE/data/narrowIE/input/', output_fo...
class NarrowIEParser(): '\n Encapsulates the path and settings for the use of narrow IE predictions.\n The RELATIONS_TO_STORE parameter determines which narrow IE extractions you use for clustering.\n * ALL - Use all narrow IE arguments and relations found in all documents.\n * TRADEOFFS - Use all...
class FilterPrep(): '\n Encapsulates paths to all OpenIE paths. Note that all .txt files prepared for Open IE will be used when training\n a SentencePiece model.\n ' def __init__(self, input_file_dir='SORE/data/OpenIE/inputs/', output_dir='SORE/data/filter_data/'): '\n Initialise Filt...
class SORE_filter(): '\n Encapsulates paths to all processed Open IE files and the processed narrow IE CSV file.\n ' def __init__(self, csv_path='data/narrowIE/tradeoffs_and_argmods.csv', sore_output_dir='SORE/data/processed_data/'): '\n\n :param csv_path:\n :param sore_output_di...
def main(all_settings): '\n Run Semi-Open Relation Extraction code following the provided settings file.\n\n :param all_settings: Settings-file provided - e.g. python run_SORE.py -s "path_to_my_settings_file.json"\n ' oie_data_dir = 'SORE/data/OpenIE/processed/' sore_output_dir = 'SORE/data/proce...
def standalone_TradeoffWordSplitter(): nlp = spacy.load('en_core_web_sm') matcher = Matcher(nlp.vocab) matcher.add('trade-off', None, [{'ORTH': 'trade'}, {'ORTH': '-'}, {'ORTH': 'off'}]) matcher.add('trade-offs', None, [{'ORTH': 'trade'}, {'ORTH': '-'}, {'ORTH': 'offs'}]) matcher.add('Trade-off', ...
def get_annotations_from_ann_file(nlp, sentence, ann_file): '\n Stores the annotations from an .ann file into the following buffers, then stores\n them in our json format.\n ' event_buffer = {} span_buffer = {} label_buffer = {} argmod_buffer = {} with open(ann_file) as f: lin...
def main(): nlp = standalone_TradeoffWordSplitter() all_files = [d for d in os.listdir(ann_dir)] data = {} for filename in all_files: if filename.endswith('.txt'): (no_extension, _) = filename.rsplit('.', maxsplit=1) (document_name, to_nr) = no_extension.rsplit('_', max...
class Scorer(object): def __init__(self, metric): self.precision_numerator = 0 self.precision_denominator = 0 self.recall_numerator = 0 self.recall_denominator = 0 self.metric = metric self.num_labels = 0 def update(self, gold, predicted, labeltype=None): ...
def compare_against_gold(gold_input, pred_input): gold_annotations = [] with open(gold_input) as o: for line in o.read().split('\n'): if (len(line) > 10): gold_annotations.append(json.loads(line)) predicted_annotations = [] with open(pred_input) as o: for li...
def standalone_TradeoffWordSplitter(): nlp = spacy.load('en_core_web_sm') matcher = Matcher(nlp.vocab) matcher.add('trade-off', None, [{'ORTH': 'trade'}, {'ORTH': '-'}, {'ORTH': 'off'}]) matcher.add('trade-offs', None, [{'ORTH': 'trade'}, {'ORTH': '-'}, {'ORTH': 'offs'}]) matcher.add('Trade-off', ...
def convert_dataset_to_SCIIE(nlp, dataset): '"\n Convert dataset to required format for SciIE:\n line1 { "clusters": [],\n "sentences": [["List", "of", "some", "tokens", "."]],\n "ner": [[[4, 4, "Generic"]]],\n "relations": [[[4, 4, 6, 17, "Tradeoff"]]],\n ...
def main(): nlp = standalone_TradeoffWordSplitter() input_files = ['../data/train_set.json', '../data/dev_set.json', '../data/test_set.json'] for input_file in input_files: output_name = (('../data/' + input_file.rsplit('/', 1)[1].rsplit('.')[0]) + '_SCIIE.json') dic_list = convert_dataset...
def standalone_TradeoffWordSplitter(): nlp = spacy.load('en_core_web_sm') matcher = Matcher(nlp.vocab) matcher.add('trade-off', None, [{'ORTH': 'trade'}, {'ORTH': '-'}, {'ORTH': 'off'}]) matcher.add('trade-offs', None, [{'ORTH': 'trade'}, {'ORTH': '-'}, {'ORTH': 'offs'}]) matcher.add('Trade-off', ...
def statistics_per_split(nlp, dataset): '\n ' doc_count = 0 token_cnt = Counter() sentence_len_cnt = Counter() relation_cnt = Counter() keyphrase_cnt = Counter() trigger_cnt = Counter() span_cnt = Counter() rel_per_keyphrase = Counter() triggers_per_sent = [] args_per_tr...
def main(): nlp = standalone_TradeoffWordSplitter() total_sent_lengths = Counter() unique_spans = Counter() unique_triggers = Counter() key_phrases = Counter() total_rel_cnt = Counter() input_files = ['../data/train_set.json', '../data/dev_set.json', '../data/test_set.json'] for input_...
def add_path(path): if (path not in sys.path): sys.path.insert(0, path)
def get_imdb(name): 'Get an imdb (image database) by name.' if (name not in __sets): raise KeyError('Unknown dataset: {}'.format(name)) return __sets[name]()
def list_imdbs(): 'List all registered imdbs.' return list(__sets.keys())
def munge(src_dir): files = os.listdir(src_dir) for fn in files: (base, ext) = os.path.splitext(fn) first = base[:14] second = base[:22] dst_dir = os.path.join('MCG', 'mat', first, second) if (not os.path.exists(dst_dir)): os.makedirs(dst_dir) src = ...
class _fasterRCNN(nn.Module): ' faster RCNN ' def __init__(self, classes, class_agnostic): super(_fasterRCNN, self).__init__() self.classes = classes self.n_classes = len(classes) self.class_agnostic = class_agnostic self.RCNN_loss_cls = 0 self.RCNN_loss_bbox =...
def conv3x3(in_planes, out_planes, stride=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 ...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.C...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) ...
def resnet18(pretrained=False): 'Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(BasicBlock, [2, 2, 2, 2]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
def resnet34(pretrained=False): 'Constructs a ResNet-34 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(BasicBlock, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model
def resnet50(pretrained=False): 'Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 6, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
def resnet101(pretrained=False): 'Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 4, 23, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model
def resnet152(pretrained=False): 'Constructs a ResNet-152 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = ResNet(Bottleneck, [3, 8, 36, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
class resnet(_fasterRCNN): def __init__(self, classes, num_layers=101, pretrained=False, class_agnostic=False): self.model_path = 'data/pretrained_model/resnet101_caffe.pth' self.dout_base_model = 1024 self.pretrained = pretrained self.class_agnostic = class_agnostic _fast...
class vgg16(_fasterRCNN): def __init__(self, classes, pretrained=False, class_agnostic=False): self.model_path = 'data/pretrained_model/vgg16_caffe.pth' self.dout_base_model = 512 self.pretrained = pretrained self.class_agnostic = class_agnostic _fasterRCNN.__init__(self, ...
def _import_symbols(locals): for symbol in dir(_lib): fn = getattr(_lib, symbol) if callable(fn): locals[symbol] = _wrap_function(fn, _ffi) else: locals[symbol] = fn __all__.append(symbol)
def nms_gpu(dets, thresh): keep = dets.new(dets.size(0), 1).zero_().int() num_out = dets.new(1).zero_().int() nms.nms_cuda(keep, dets, num_out, thresh) keep = keep[:num_out[0]] return keep
def nms(dets, thresh, force_cpu=False): 'Dispatch to either CPU or GPU NMS implementations.' if (dets.shape[0] == 0): return [] return (nms_gpu(dets, thresh) if (force_cpu == False) else nms_cpu(dets, thresh))
def _import_symbols(locals): for symbol in dir(_lib): fn = getattr(_lib, symbol) if callable(fn): locals[symbol] = _wrap_function(fn, _ffi) else: locals[symbol] = fn __all__.append(symbol)
class RoIAlignFunction(Function): def __init__(self, aligned_height, aligned_width, spatial_scale): self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) self.rois = None self.feature_size = None de...
class RoIAlign(Module): def __init__(self, aligned_height, aligned_width, spatial_scale): super(RoIAlign, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) def forward(self, features, r...
class RoIAlignAvg(Module): def __init__(self, aligned_height, aligned_width, spatial_scale): super(RoIAlignAvg, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) def forward(self, featu...
class RoIAlignMax(Module): def __init__(self, aligned_height, aligned_width, spatial_scale): super(RoIAlignMax, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) def forward(self, featu...
def _import_symbols(locals): for symbol in dir(_lib): fn = getattr(_lib, symbol) locals[symbol] = _wrap_function(fn, _ffi) __all__.append(symbol)
def _import_symbols(locals): for symbol in dir(_lib): fn = getattr(_lib, symbol) if callable(fn): locals[symbol] = _wrap_function(fn, _ffi) else: locals[symbol] = fn __all__.append(symbol)
class RoICropFunction(Function): def forward(self, input1, input2): self.input1 = input1 self.input2 = input2 self.device_c = ffi.new('int *') output = torch.zeros(input2.size()[0], input1.size()[1], input2.size()[1], input2.size()[2]) if input1.is_cuda: self.d...
class RoICropFunction(Function): def forward(self, input1, input2): self.input1 = input1.clone() self.input2 = input2.clone() output = input2.new(input2.size()[0], input1.size()[1], input2.size()[1], input2.size()[2]).zero_() assert (output.get_device() == input1.get_device()), 'o...
class _RoICrop(Module): def __init__(self, layout='BHWD'): super(_RoICrop, self).__init__() def forward(self, input1, input2): return RoICropFunction()(input1, input2)
class _ROIAlign(Function): @staticmethod def forward(ctx, input, roi, output_size, spatial_scale, sampling_ratio): ctx.save_for_backward(roi) ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.sampling_ratio = sampling_ratio ctx.input_shape = in...
class ROIAlign(nn.Module): def __init__(self, output_size, spatial_scale, sampling_ratio): super(ROIAlign, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale self.sampling_ratio = sampling_ratio def forward(self, input, rois): return ro...
class _ROIPool(Function): @staticmethod def forward(ctx, input, roi, output_size, spatial_scale): ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.input_shape = input.size() (output, argmax) = _C.roi_pool_forward(input, roi, spatial_scale, output_size...
class ROIPool(nn.Module): def __init__(self, output_size, spatial_scale): super(ROIPool, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale def forward(self, input, rois): return roi_pool(input, rois, self.output_size, self.spatial_scale) ...
def _import_symbols(locals): for symbol in dir(_lib): fn = getattr(_lib, symbol) if callable(fn): locals[symbol] = _wrap_function(fn, _ffi) else: locals[symbol] = fn __all__.append(symbol)
class RoIPoolFunction(Function): def __init__(ctx, pooled_height, pooled_width, spatial_scale): ctx.pooled_width = pooled_width ctx.pooled_height = pooled_height ctx.spatial_scale = spatial_scale ctx.feature_size = None def forward(ctx, features, rois): ctx.feature_si...
class _RoIPooling(Module): def __init__(self, pooled_height, pooled_width, spatial_scale): super(_RoIPooling, self).__init__() self.pooled_width = int(pooled_width) self.pooled_height = int(pooled_height) self.spatial_scale = float(spatial_scale) def forward(self, features, r...
class _RPN(nn.Module): ' region proposal network ' def __init__(self, din): super(_RPN, self).__init__() self.din = din self.anchor_scales = cfg.ANCHOR_SCALES self.anchor_ratios = cfg.ANCHOR_RATIOS self.feat_stride = cfg.FEAT_STRIDE[0] self.RPN_Conv = nn.Conv2d...
def get_output_dir(imdb, weights_filename): 'Return the directory where experimental artifacts are placed.\n If the directory does not exist, it is created.\n\n A canonical path is built using the name from an imdb and a network\n (if not None).\n ' outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __...
def get_output_tb_dir(imdb, weights_filename): 'Return the directory where tensorflow summaries are placed.\n If the directory does not exist, it is created.\n\n A canonical path is built using the name from an imdb and a network\n (if not None).\n ' outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'tensorboar...
def _merge_a_into_b(a, b): 'Merge config dictionary a into config dictionary b, clobbering the\n options in b whenever they are also specified in a.\n ' if (type(a) is not edict): return for (k, v) in a.items(): if (k not in b): raise KeyError('{} is not a valid config key'.f...
def cfg_from_file(filename): 'Load a config file and merge it into the default options.' import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C)
def cfg_from_list(cfg_list): 'Set config keys via list (e.g., from command line).' from ast import literal_eval assert ((len(cfg_list) % 2) == 0) for (k, v) in zip(cfg_list[0::2], cfg_list[1::2]): key_list = k.split('.') d = __C for subkey in key_list[:(- 1)]: asser...
class Logger(object): def __init__(self, log_dir): 'Create a summary writer logging to log_dir.' self.writer = tf.summary.FileWriter(log_dir) def scalar_summary(self, tag, value, step): 'Log a scalar variable.' summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_valu...
def prepare_roidb(imdb): "Enrich the imdb's roidb by adding some derived quantities that\n are useful for training. This function precomputes the maximum\n overlap, taken over ground-truth boxes, between each ROI and\n each ground-truth box. The class with maximum overlap is also\n recorded.\n " roidb = ...
def rank_roidb_ratio(roidb): ratio_large = 2 ratio_small = 0.5 ratio_list = [] for i in range(len(roidb)): width = roidb[i]['width'] height = roidb[i]['height'] ratio = (width / float(height)) if (ratio > ratio_large): roidb[i]['need_crop'] = 1 r...
def filter_roidb(roidb): print(('before filtering, there are %d images...' % len(roidb))) i = 0 while (i < len(roidb)): if (len(roidb[i]['boxes']) == 0): del roidb[i] i -= 1 i += 1 print(('after filtering, there are %d images...' % len(roidb))) return roidb
def combined_roidb(imdb_names, training=True): '\n Combine multiple roidbs\n ' def get_training_roidb(imdb): 'Returns a roidb (Region of Interest database) for use in training.' if cfg.TRAIN.USE_FLIPPED: print('Appending horizontally-flipped training examples...') im...
def get_extensions(): this_dir = os.path.dirname(os.path.abspath(__file__)) extensions_dir = os.path.join(this_dir, 'model', 'csrc') main_file = glob.glob(os.path.join(extensions_dir, '*.cpp')) source_cpu = glob.glob(os.path.join(extensions_dir, 'cpu', '*.cpp')) source_cuda = glob.glob(os.path.joi...
def parse_args(): '\n Parse input arguments\n ' parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) parser.add_argument('--net', dest='net', help='vgg16, res101', default=...
class sampler(Sampler): def __init__(self, train_size, batch_size): self.num_data = train_size self.num_per_batch = int((train_size / batch_size)) self.batch_size = batch_size self.range = torch.arange(0, batch_size).view(1, batch_size).long() self.leftover_flag = False ...
def compute_auc(s_error, p_error, a_error): assert (len(s_error) == 71) assert (len(p_error) == 48) assert (len(a_error) == 14) s_error = np.array(s_error) p_error = np.array(p_error) a_error = np.array(a_error) limit = 25 gs_error = np.zeros((limit + 1)) gp_error = np.zeros((limit...
def affine_images(images, used_for='detector'): '\n Perform affine transformation on images\n :param images: (B, C, H, W)\n :param keypoint_labels: corresponding labels\n :param value_map: value maps, used to record history learned geo_points\n :return: results of affine images, affine labels, affi...
def get_gaussian_kernel(kernlen=21, nsig=5): 'Get kernels used for generating Gaussian heatmaps' interval = (((2 * nsig) + 1.0) / kernlen) x = np.linspace(((- nsig) - (interval / 2.0)), (nsig + (interval / 2.0)), (kernlen + 1)) kern1d = np.diff(st.norm.cdf(x)) kernel_raw = np.sqrt(np.outer(kern1d,...
def value_map_load(save_dir, names, input_with_label, shape=(768, 768), value_maps_running=None): value_maps = [] for (s, name) in enumerate(names): path = os.path.join(save_dir, (name.split('.')[0] + '.png')) if (input_with_label[s] and (value_maps_running is not None) and (name in value_maps...
def value_map_save(save_dir, names, input_with_label, value_maps, value_maps_running=None): for (s, name) in enumerate(names): if input_with_label[s]: vp = value_maps[s].squeeze().numpy() if (value_maps_running is not None): value_maps_running[name] = vp ...
def train_model(model, optimizer, dataloaders, device, num_epochs, train_config): model_save_path = train_config['model_save_path'] model_save_epoch = train_config['model_save_epoch'] pke_start_epoch = train_config['pke_start_epoch'] pke_show_epoch = train_config['pke_show_epoch'] pke_show_list = ...
class DiceBCELoss(nn.Module): def __init__(self, weight=None, size_average=True): super(DiceBCELoss, self).__init__() def forward(self, inputs, targets, smooth=1): inputs = inputs.view((- 1)) targets = targets.view((- 1)) intersection = (inputs * targets).sum() dice_l...