repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
HazyResearch/pdftotree
pdftotree/visual/visual_utils.py
do_intersect
def do_intersect(bb1, bb2): """ Helper function that returns True if two bounding boxes overlap. """ if bb1[0] + bb1[2] < bb2[0] or bb2[0] + bb2[2] < bb1[0]: return False if bb1[1] + bb1[3] < bb2[1] or bb2[1] + bb2[3] < bb1[1]: return False return True
python
def do_intersect(bb1, bb2): """ Helper function that returns True if two bounding boxes overlap. """ if bb1[0] + bb1[2] < bb2[0] or bb2[0] + bb2[2] < bb1[0]: return False if bb1[1] + bb1[3] < bb2[1] or bb2[1] + bb2[3] < bb1[1]: return False return True
[ "def", "do_intersect", "(", "bb1", ",", "bb2", ")", ":", "if", "bb1", "[", "0", "]", "+", "bb1", "[", "2", "]", "<", "bb2", "[", "0", "]", "or", "bb2", "[", "0", "]", "+", "bb2", "[", "2", "]", "<", "bb1", "[", "0", "]", ":", "return", ...
Helper function that returns True if two bounding boxes overlap.
[ "Helper", "function", "that", "returns", "True", "if", "two", "bounding", "boxes", "overlap", "." ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/visual/visual_utils.py#L63-L71
HazyResearch/pdftotree
pdftotree/visual/visual_utils.py
get_bboxes
def get_bboxes( img, mask, nb_boxes=100, score_thresh=0.5, iou_thresh=0.2, prop_size=0.09, prop_scale=1.2, ): """ Uses selective search to generate candidate bounding boxes and keeps the ones that have the largest iou with the predicted mask. :param img: original image :...
python
def get_bboxes( img, mask, nb_boxes=100, score_thresh=0.5, iou_thresh=0.2, prop_size=0.09, prop_scale=1.2, ): """ Uses selective search to generate candidate bounding boxes and keeps the ones that have the largest iou with the predicted mask. :param img: original image :...
[ "def", "get_bboxes", "(", "img", ",", "mask", ",", "nb_boxes", "=", "100", ",", "score_thresh", "=", "0.5", ",", "iou_thresh", "=", "0.2", ",", "prop_size", "=", "0.09", ",", "prop_scale", "=", "1.2", ",", ")", ":", "min_size", "=", "int", "(", "img"...
Uses selective search to generate candidate bounding boxes and keeps the ones that have the largest iou with the predicted mask. :param img: original image :param mask: predicted mask :param nb_boxes: max number of candidate bounding boxes :param score_thresh: scre threshold to consider prediction ...
[ "Uses", "selective", "search", "to", "generate", "candidate", "bounding", "boxes", "and", "keeps", "the", "ones", "that", "have", "the", "largest", "iou", "with", "the", "predicted", "mask", "." ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/visual/visual_utils.py#L74-L141
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_utils.py
analyze_pages
def analyze_pages(file_name, char_margin=1.0): """ Input: the file path to the PDF file Output: yields the layout object for each page in the PDF """ log = logging.getLogger(__name__) # Open a PDF file. with open(os.path.realpath(file_name), "rb") as fp: # Create a PDF parser object ...
python
def analyze_pages(file_name, char_margin=1.0): """ Input: the file path to the PDF file Output: yields the layout object for each page in the PDF """ log = logging.getLogger(__name__) # Open a PDF file. with open(os.path.realpath(file_name), "rb") as fp: # Create a PDF parser object ...
[ "def", "analyze_pages", "(", "file_name", ",", "char_margin", "=", "1.0", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "# Open a PDF file.", "with", "open", "(", "os", ".", "path", ".", "realpath", "(", "file_name", ")", ",", ...
Input: the file path to the PDF file Output: yields the layout object for each page in the PDF
[ "Input", ":", "the", "file", "path", "to", "the", "PDF", "file", "Output", ":", "yields", "the", "layout", "object", "for", "each", "page", "in", "the", "PDF" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_utils.py#L110-L143
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_utils.py
normalize_pdf
def normalize_pdf(layout, scaler): """ Normalizes pdf object coordinates (bot left) to image conventions (top left origin). Returns the list of chars and average char size """ chars = [] mentions = [] height = scaler * layout.height font_size_counter = collections.Counter() # Lin...
python
def normalize_pdf(layout, scaler): """ Normalizes pdf object coordinates (bot left) to image conventions (top left origin). Returns the list of chars and average char size """ chars = [] mentions = [] height = scaler * layout.height font_size_counter = collections.Counter() # Lin...
[ "def", "normalize_pdf", "(", "layout", ",", "scaler", ")", ":", "chars", "=", "[", "]", "mentions", "=", "[", "]", "height", "=", "scaler", "*", "layout", ".", "height", "font_size_counter", "=", "collections", ".", "Counter", "(", ")", "# Lines longer tha...
Normalizes pdf object coordinates (bot left) to image conventions (top left origin). Returns the list of chars and average char size
[ "Normalizes", "pdf", "object", "coordinates", "(", "bot", "left", ")", "to", "image", "conventions", "(", "top", "left", "origin", ")", ".", "Returns", "the", "list", "of", "chars", "and", "average", "char", "size" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_utils.py#L146-L218
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_utils.py
_print_dict
def _print_dict(elem_dict): """ Print a dict in a readable way """ for key, value in sorted(elem_dict.iteritems()): if isinstance(value, collections.Iterable): print(key, len(value)) else: print(key, value)
python
def _print_dict(elem_dict): """ Print a dict in a readable way """ for key, value in sorted(elem_dict.iteritems()): if isinstance(value, collections.Iterable): print(key, len(value)) else: print(key, value)
[ "def", "_print_dict", "(", "elem_dict", ")", ":", "for", "key", ",", "value", "in", "sorted", "(", "elem_dict", ".", "iteritems", "(", ")", ")", ":", "if", "isinstance", "(", "value", ",", "collections", ".", "Iterable", ")", ":", "print", "(", "key", ...
Print a dict in a readable way
[ "Print", "a", "dict", "in", "a", "readable", "way" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_utils.py#L221-L229
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_utils.py
_font_of_mention
def _font_of_mention(m): """ Returns the font type and size of the first alphanumeric char in the text or None if there isn't any. """ for ch in m: if isinstance(ch, LTChar) and ch.get_text().isalnum(): return (ch.fontname, _font_size_of(ch)) return (None, 0)
python
def _font_of_mention(m): """ Returns the font type and size of the first alphanumeric char in the text or None if there isn't any. """ for ch in m: if isinstance(ch, LTChar) and ch.get_text().isalnum(): return (ch.fontname, _font_size_of(ch)) return (None, 0)
[ "def", "_font_of_mention", "(", "m", ")", ":", "for", "ch", "in", "m", ":", "if", "isinstance", "(", "ch", ",", "LTChar", ")", "and", "ch", ".", "get_text", "(", ")", ".", "isalnum", "(", ")", ":", "return", "(", "ch", ".", "fontname", ",", "_fon...
Returns the font type and size of the first alphanumeric char in the text or None if there isn't any.
[ "Returns", "the", "font", "type", "and", "size", "of", "the", "first", "alphanumeric", "char", "in", "the", "text", "or", "None", "if", "there", "isn", "t", "any", "." ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_utils.py#L238-L246
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_utils.py
_allowed_char
def _allowed_char(c): """ Returns whether the given unicode char is allowed in output """ c = ord(c) if c < 0: return False if c < 128: return _ascii_allowed[c] # Genereally allow unicodes, TODO: check for unicode control characters # characters return True
python
def _allowed_char(c): """ Returns whether the given unicode char is allowed in output """ c = ord(c) if c < 0: return False if c < 128: return _ascii_allowed[c] # Genereally allow unicodes, TODO: check for unicode control characters # characters return True
[ "def", "_allowed_char", "(", "c", ")", ":", "c", "=", "ord", "(", "c", ")", "if", "c", "<", "0", ":", "return", "False", "if", "c", "<", "128", ":", "return", "_ascii_allowed", "[", "c", "]", "# Genereally allow unicodes, TODO: check for unicode control char...
Returns whether the given unicode char is allowed in output
[ "Returns", "whether", "the", "given", "unicode", "char", "is", "allowed", "in", "output" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_utils.py#L258-L269
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_utils.py
keep_allowed_chars
def keep_allowed_chars(text): """ Cleans the text for output """ # print ','.join(str(ord(c)) for c in text) return "".join(" " if c == "\n" else c for c in text.strip() if _allowed_char(c))
python
def keep_allowed_chars(text): """ Cleans the text for output """ # print ','.join(str(ord(c)) for c in text) return "".join(" " if c == "\n" else c for c in text.strip() if _allowed_char(c))
[ "def", "keep_allowed_chars", "(", "text", ")", ":", "# print ','.join(str(ord(c)) for c in text)", "return", "\"\"", ".", "join", "(", "\" \"", "if", "c", "==", "\"\\n\"", "else", "c", "for", "c", "in", "text", ".", "strip", "(", ")", "if", "_allowed_char"...
Cleans the text for output
[ "Cleans", "the", "text", "for", "output" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_utils.py#L272-L277
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_utils.py
CustomPDFPageAggregator.paint_path
def paint_path(self, gstate, stroke, fill, evenodd, path): """ Converting long paths to small segments each time we m=Move or h=ClosePath for polygon """ shape = "".join(x[0] for x in path) prev_split = 0 for i in range(len(shape)): if shape[i] == "m" ...
python
def paint_path(self, gstate, stroke, fill, evenodd, path): """ Converting long paths to small segments each time we m=Move or h=ClosePath for polygon """ shape = "".join(x[0] for x in path) prev_split = 0 for i in range(len(shape)): if shape[i] == "m" ...
[ "def", "paint_path", "(", "self", ",", "gstate", ",", "stroke", ",", "fill", ",", "evenodd", ",", "path", ")", ":", "shape", "=", "\"\"", ".", "join", "(", "x", "[", "0", "]", "for", "x", "in", "path", ")", "prev_split", "=", "0", "for", "i", "...
Converting long paths to small segments each time we m=Move or h=ClosePath for polygon
[ "Converting", "long", "paths", "to", "small", "segments", "each", "time", "we", "m", "=", "Move", "or", "h", "=", "ClosePath", "for", "polygon" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_utils.py#L53-L74
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_utils.py
CustomPDFPageAggregator.paint_single_path
def paint_single_path(self, gstate, stroke, fill, evenodd, path): """ Converting a single path draw command into lines and curves objects """ if len(path) < 2: return shape = "".join(x[0] for x in path) pts = [] for p in path: for i in ran...
python
def paint_single_path(self, gstate, stroke, fill, evenodd, path): """ Converting a single path draw command into lines and curves objects """ if len(path) < 2: return shape = "".join(x[0] for x in path) pts = [] for p in path: for i in ran...
[ "def", "paint_single_path", "(", "self", ",", "gstate", ",", "stroke", ",", "fill", ",", "evenodd", ",", "path", ")", ":", "if", "len", "(", "path", ")", "<", "2", ":", "return", "shape", "=", "\"\"", ".", "join", "(", "x", "[", "0", "]", "for", ...
Converting a single path draw command into lines and curves objects
[ "Converting", "a", "single", "path", "draw", "command", "into", "lines", "and", "curves", "objects" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_utils.py#L76-L107
HazyResearch/pdftotree
pdftotree/utils/pdf/layout_utils.py
traverse_layout
def traverse_layout(root, callback): """ Tree walker and invokes the callback as it traverse pdf object tree """ callback(root) if isinstance(root, collections.Iterable): for child in root: traverse_layout(child, callback)
python
def traverse_layout(root, callback): """ Tree walker and invokes the callback as it traverse pdf object tree """ callback(root) if isinstance(root, collections.Iterable): for child in root: traverse_layout(child, callback)
[ "def", "traverse_layout", "(", "root", ",", "callback", ")", ":", "callback", "(", "root", ")", "if", "isinstance", "(", "root", ",", "collections", ".", "Iterable", ")", ":", "for", "child", "in", "root", ":", "traverse_layout", "(", "child", ",", "call...
Tree walker and invokes the callback as it traverse pdf object tree
[ "Tree", "walker", "and", "invokes", "the", "callback", "as", "it", "traverse", "pdf", "object", "tree" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/layout_utils.py#L17-L25
HazyResearch/pdftotree
pdftotree/utils/pdf/layout_utils.py
get_near_items
def get_near_items(tree, tree_key): """ Check both possible neighbors for key in a binary tree """ try: yield tree.floor_item(tree_key) except KeyError: pass try: yield tree.ceiling_item(tree_key) except KeyError: pass
python
def get_near_items(tree, tree_key): """ Check both possible neighbors for key in a binary tree """ try: yield tree.floor_item(tree_key) except KeyError: pass try: yield tree.ceiling_item(tree_key) except KeyError: pass
[ "def", "get_near_items", "(", "tree", ",", "tree_key", ")", ":", "try", ":", "yield", "tree", ".", "floor_item", "(", "tree_key", ")", "except", "KeyError", ":", "pass", "try", ":", "yield", "tree", ".", "ceiling_item", "(", "tree_key", ")", "except", "K...
Check both possible neighbors for key in a binary tree
[ "Check", "both", "possible", "neighbors", "for", "key", "in", "a", "binary", "tree" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/layout_utils.py#L28-L40
HazyResearch/pdftotree
pdftotree/utils/pdf/layout_utils.py
align_add
def align_add(tree, key, item, align_thres=2.0): """ Adding the item object to a binary tree with the given key while allow for small key differences close_enough_func that checks if two keys are within threshold """ for near_key, near_list in get_near_items(tree, key): if abs(key - ...
python
def align_add(tree, key, item, align_thres=2.0): """ Adding the item object to a binary tree with the given key while allow for small key differences close_enough_func that checks if two keys are within threshold """ for near_key, near_list in get_near_items(tree, key): if abs(key - ...
[ "def", "align_add", "(", "tree", ",", "key", ",", "item", ",", "align_thres", "=", "2.0", ")", ":", "for", "near_key", ",", "near_list", "in", "get_near_items", "(", "tree", ",", "key", ")", ":", "if", "abs", "(", "key", "-", "near_key", ")", "<", ...
Adding the item object to a binary tree with the given key while allow for small key differences close_enough_func that checks if two keys are within threshold
[ "Adding", "the", "item", "object", "to", "a", "binary", "tree", "with", "the", "given", "key", "while", "allow", "for", "small", "key", "differences", "close_enough_func", "that", "checks", "if", "two", "keys", "are", "within", "threshold" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/layout_utils.py#L43-L55
HazyResearch/pdftotree
pdftotree/utils/pdf/layout_utils.py
collect_table_content
def collect_table_content(table_bboxes, elems): """ Returns a list of elements that are contained inside the corresponding supplied bbox. """ # list of table content chars table_contents = [[] for _ in range(len(table_bboxes))] prev_content = None prev_bbox = None for cid, c in enume...
python
def collect_table_content(table_bboxes, elems): """ Returns a list of elements that are contained inside the corresponding supplied bbox. """ # list of table content chars table_contents = [[] for _ in range(len(table_bboxes))] prev_content = None prev_bbox = None for cid, c in enume...
[ "def", "collect_table_content", "(", "table_bboxes", ",", "elems", ")", ":", "# list of table content chars", "table_contents", "=", "[", "[", "]", "for", "_", "in", "range", "(", "len", "(", "table_bboxes", ")", ")", "]", "prev_content", "=", "None", "prev_bb...
Returns a list of elements that are contained inside the corresponding supplied bbox.
[ "Returns", "a", "list", "of", "elements", "that", "are", "contained", "inside", "the", "corresponding", "supplied", "bbox", "." ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/layout_utils.py#L120-L150
HazyResearch/pdftotree
pdftotree/utils/pdf/layout_utils.py
_gaps_from
def _gaps_from(intervals): """ From a list of intervals extract a list of sorted gaps in the form of [(g,i)] where g is the size of the ith gap. """ sliding_window = zip(intervals, intervals[1:]) gaps = [b[0] - a[1] for a, b in sliding_window] return gaps
python
def _gaps_from(intervals): """ From a list of intervals extract a list of sorted gaps in the form of [(g,i)] where g is the size of the ith gap. """ sliding_window = zip(intervals, intervals[1:]) gaps = [b[0] - a[1] for a, b in sliding_window] return gaps
[ "def", "_gaps_from", "(", "intervals", ")", ":", "sliding_window", "=", "zip", "(", "intervals", ",", "intervals", "[", "1", ":", "]", ")", "gaps", "=", "[", "b", "[", "0", "]", "-", "a", "[", "1", "]", "for", "a", ",", "b", "in", "sliding_window...
From a list of intervals extract a list of sorted gaps in the form of [(g,i)] where g is the size of the ith gap.
[ "From", "a", "list", "of", "intervals", "extract", "a", "list", "of", "sorted", "gaps", "in", "the", "form", "of", "[", "(", "g", "i", ")", "]", "where", "g", "is", "the", "size", "of", "the", "ith", "gap", "." ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/layout_utils.py#L157-L165
HazyResearch/pdftotree
pdftotree/utils/pdf/layout_utils.py
project_onto
def project_onto(objs, axis, min_gap_size=4.0): """ Projects object bboxes onto the axis and return the unioned intervals and groups of objects in intervals. """ if axis == "x": axis = 0 if axis == "y": axis = 1 axis_end = axis + 2 if axis == 0: # if projecting onto X ax...
python
def project_onto(objs, axis, min_gap_size=4.0): """ Projects object bboxes onto the axis and return the unioned intervals and groups of objects in intervals. """ if axis == "x": axis = 0 if axis == "y": axis = 1 axis_end = axis + 2 if axis == 0: # if projecting onto X ax...
[ "def", "project_onto", "(", "objs", ",", "axis", ",", "min_gap_size", "=", "4.0", ")", ":", "if", "axis", "==", "\"x\"", ":", "axis", "=", "0", "if", "axis", "==", "\"y\"", ":", "axis", "=", "1", "axis_end", "=", "axis", "+", "2", "if", "axis", "...
Projects object bboxes onto the axis and return the unioned intervals and groups of objects in intervals.
[ "Projects", "object", "bboxes", "onto", "the", "axis", "and", "return", "the", "unioned", "intervals", "and", "groups", "of", "objects", "in", "intervals", "." ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/layout_utils.py#L168-L214
HazyResearch/pdftotree
pdftotree/utils/pdf/layout_utils.py
recursive_xy_divide
def recursive_xy_divide(elems, avg_font_size): """ Recursively group/divide the document by white stripes by projecting elements onto alternating axes as intervals. avg_font_size: the minimum gap size between elements below which we consider interval continuous. """ log = logging.getLogger(...
python
def recursive_xy_divide(elems, avg_font_size): """ Recursively group/divide the document by white stripes by projecting elements onto alternating axes as intervals. avg_font_size: the minimum gap size between elements below which we consider interval continuous. """ log = logging.getLogger(...
[ "def", "recursive_xy_divide", "(", "elems", ",", "avg_font_size", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "log", ".", "info", "(", "avg_font_size", ")", "objects", "=", "list", "(", "elems", ".", "mentions", ")", "objects",...
Recursively group/divide the document by white stripes by projecting elements onto alternating axes as intervals. avg_font_size: the minimum gap size between elements below which we consider interval continuous.
[ "Recursively", "group", "/", "divide", "the", "document", "by", "white", "stripes", "by", "projecting", "elements", "onto", "alternating", "axes", "as", "intervals", "." ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/layout_utils.py#L217-L273
HazyResearch/pdftotree
pdftotree/utils/bbox_utils.py
doOverlap
def doOverlap(bbox1, bbox2): """ :param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: 1 if the two rectangles overlap """ if bbox1[2] < bbox2[0] or bbox2[2] < bbox1[0]: return False if bbox1[3] < bbox2[1] or bbox2[3] < bbox1[1]...
python
def doOverlap(bbox1, bbox2): """ :param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: 1 if the two rectangles overlap """ if bbox1[2] < bbox2[0] or bbox2[2] < bbox1[0]: return False if bbox1[3] < bbox2[1] or bbox2[3] < bbox1[1]...
[ "def", "doOverlap", "(", "bbox1", ",", "bbox2", ")", ":", "if", "bbox1", "[", "2", "]", "<", "bbox2", "[", "0", "]", "or", "bbox2", "[", "2", "]", "<", "bbox1", "[", "0", "]", ":", "return", "False", "if", "bbox1", "[", "3", "]", "<", "bbox2"...
:param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: 1 if the two rectangles overlap
[ ":", "param", "bbox1", ":", "bounding", "box", "of", "the", "first", "rectangle", ":", "param", "bbox2", ":", "bounding", "box", "of", "the", "second", "rectangle", ":", "return", ":", "1", "if", "the", "two", "rectangles", "overlap" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/bbox_utils.py#L4-L14
HazyResearch/pdftotree
pdftotree/utils/bbox_utils.py
isContained
def isContained(bbox1, bbox2, tol=TOLERANCE): """ :param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: True if bbox1 is contaned in bbox2 """ if bbox1[0] > bbox2[0] - tol and bbox1[1] > bbox2[1] - tol: if bbox1[2] < bbox2[2] + tol ...
python
def isContained(bbox1, bbox2, tol=TOLERANCE): """ :param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: True if bbox1 is contaned in bbox2 """ if bbox1[0] > bbox2[0] - tol and bbox1[1] > bbox2[1] - tol: if bbox1[2] < bbox2[2] + tol ...
[ "def", "isContained", "(", "bbox1", ",", "bbox2", ",", "tol", "=", "TOLERANCE", ")", ":", "if", "bbox1", "[", "0", "]", ">", "bbox2", "[", "0", "]", "-", "tol", "and", "bbox1", "[", "1", "]", ">", "bbox2", "[", "1", "]", "-", "tol", ":", "if"...
:param bbox1: bounding box of the first rectangle :param bbox2: bounding box of the second rectangle :return: True if bbox1 is contaned in bbox2
[ ":", "param", "bbox1", ":", "bounding", "box", "of", "the", "first", "rectangle", ":", "param", "bbox2", ":", "bounding", "box", "of", "the", "second", "rectangle", ":", "return", ":", "True", "if", "bbox1", "is", "contaned", "in", "bbox2" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/bbox_utils.py#L17-L26
HazyResearch/pdftotree
pdftotree/utils/bbox_utils.py
mergeBboxes
def mergeBboxes(bbox1, bbox2): """ :param bbox1: (top, left, bottom, right) :param bbox2: (top, left, bottom, right) :return: Merge bounding boxes """ if isContained(bbox1, bbox2): return bbox2 elif isContained(bbox2, bbox1): return bbox1 else: return ( ...
python
def mergeBboxes(bbox1, bbox2): """ :param bbox1: (top, left, bottom, right) :param bbox2: (top, left, bottom, right) :return: Merge bounding boxes """ if isContained(bbox1, bbox2): return bbox2 elif isContained(bbox2, bbox1): return bbox1 else: return ( ...
[ "def", "mergeBboxes", "(", "bbox1", ",", "bbox2", ")", ":", "if", "isContained", "(", "bbox1", ",", "bbox2", ")", ":", "return", "bbox2", "elif", "isContained", "(", "bbox2", ",", "bbox1", ")", ":", "return", "bbox1", "else", ":", "return", "(", "min",...
:param bbox1: (top, left, bottom, right) :param bbox2: (top, left, bottom, right) :return: Merge bounding boxes
[ ":", "param", "bbox1", ":", "(", "top", "left", "bottom", "right", ")", ":", "param", "bbox2", ":", "(", "top", "left", "bottom", "right", ")", ":", "return", ":", "Merge", "bounding", "boxes" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/bbox_utils.py#L29-L45
HazyResearch/pdftotree
pdftotree/utils/bbox_utils.py
get_rectangles
def get_rectangles(vertical_lines, horizontal_lines): """ :param vertical_lines: list of vertical lines coordinates :param horizontal_lines: list of horizontal lines coordinates :return: List of bounding boxes for tables """ rectangles = [] i = 0 j = 0 while i < len(horizontal_lines)...
python
def get_rectangles(vertical_lines, horizontal_lines): """ :param vertical_lines: list of vertical lines coordinates :param horizontal_lines: list of horizontal lines coordinates :return: List of bounding boxes for tables """ rectangles = [] i = 0 j = 0 while i < len(horizontal_lines)...
[ "def", "get_rectangles", "(", "vertical_lines", ",", "horizontal_lines", ")", ":", "rectangles", "=", "[", "]", "i", "=", "0", "j", "=", "0", "while", "i", "<", "len", "(", "horizontal_lines", ")", "and", "j", "<", "len", "(", "vertical_lines", ")", ":...
:param vertical_lines: list of vertical lines coordinates :param horizontal_lines: list of horizontal lines coordinates :return: List of bounding boxes for tables
[ ":", "param", "vertical_lines", ":", "list", "of", "vertical", "lines", "coordinates", ":", "param", "horizontal_lines", ":", "list", "of", "horizontal", "lines", "coordinates", ":", "return", ":", "List", "of", "bounding", "boxes", "for", "tables" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/bbox_utils.py#L48-L78
HazyResearch/pdftotree
pdftotree/utils/bbox_utils.py
get_outer_bounding_boxes
def get_outer_bounding_boxes(rectangles): """ :param rectangles: list of bounding boxes (top, left, bottom, right) :return: outer bounding boxes (only the largest bbox when bboxes intersect) """ if len(rectangles) == 0: return [] outer_bboxes = [rectangles[0]] for bbox2 in rectangles...
python
def get_outer_bounding_boxes(rectangles): """ :param rectangles: list of bounding boxes (top, left, bottom, right) :return: outer bounding boxes (only the largest bbox when bboxes intersect) """ if len(rectangles) == 0: return [] outer_bboxes = [rectangles[0]] for bbox2 in rectangles...
[ "def", "get_outer_bounding_boxes", "(", "rectangles", ")", ":", "if", "len", "(", "rectangles", ")", "==", "0", ":", "return", "[", "]", "outer_bboxes", "=", "[", "rectangles", "[", "0", "]", "]", "for", "bbox2", "in", "rectangles", "[", "1", ":", "]",...
:param rectangles: list of bounding boxes (top, left, bottom, right) :return: outer bounding boxes (only the largest bbox when bboxes intersect)
[ ":", "param", "rectangles", ":", "list", "of", "bounding", "boxes", "(", "top", "left", "bottom", "right", ")", ":", "return", ":", "outer", "bounding", "boxes", "(", "only", "the", "largest", "bbox", "when", "bboxes", "intersect", ")" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/bbox_utils.py#L81-L99
HazyResearch/pdftotree
pdftotree/utils/bbox_utils.py
get_intersection
def get_intersection(bbox1, bbox2): """ :param bbox1: (page, width, height, top, left, bottom, right) :param bbox2: (page, width, height, top, left, bottom, right) :return: intersection if bboxes are in the same page and intersect """ intersection = [] page_1, page_width, page_height, top_1,...
python
def get_intersection(bbox1, bbox2): """ :param bbox1: (page, width, height, top, left, bottom, right) :param bbox2: (page, width, height, top, left, bottom, right) :return: intersection if bboxes are in the same page and intersect """ intersection = [] page_1, page_width, page_height, top_1,...
[ "def", "get_intersection", "(", "bbox1", ",", "bbox2", ")", ":", "intersection", "=", "[", "]", "page_1", ",", "page_width", ",", "page_height", ",", "top_1", ",", "left_1", ",", "bottom_1", ",", "right_1", "=", "bbox1", "page_2", ",", "_", ",", "_", "...
:param bbox1: (page, width, height, top, left, bottom, right) :param bbox2: (page, width, height, top, left, bottom, right) :return: intersection if bboxes are in the same page and intersect
[ ":", "param", "bbox1", ":", "(", "page", "width", "height", "top", "left", "bottom", "right", ")", ":", "param", "bbox2", ":", "(", "page", "width", "height", "top", "left", "bottom", "right", ")", ":", "return", ":", "intersection", "if", "bboxes", "a...
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/bbox_utils.py#L102-L126
HazyResearch/pdftotree
pdftotree/utils/bbox_utils.py
compute_iou
def compute_iou(bbox1, bbox2): """ :param bbox1: (page, width, height, top, left, bottom, right) :param bbox2: (page, width, height, top, left, bottom, right) :return: intersection over union if bboxes are in the same page and intersect """ top_1, left_1, bottom_1, right_1 = bbox1 top_2, lef...
python
def compute_iou(bbox1, bbox2): """ :param bbox1: (page, width, height, top, left, bottom, right) :param bbox2: (page, width, height, top, left, bottom, right) :return: intersection over union if bboxes are in the same page and intersect """ top_1, left_1, bottom_1, right_1 = bbox1 top_2, lef...
[ "def", "compute_iou", "(", "bbox1", ",", "bbox2", ")", ":", "top_1", ",", "left_1", ",", "bottom_1", ",", "right_1", "=", "bbox1", "top_2", ",", "left_2", ",", "bottom_2", ",", "right_2", "=", "bbox2", "if", "doOverlap", "(", "(", "top_1", ",", "left_1...
:param bbox1: (page, width, height, top, left, bottom, right) :param bbox2: (page, width, height, top, left, bottom, right) :return: intersection over union if bboxes are in the same page and intersect
[ ":", "param", "bbox1", ":", "(", "page", "width", "height", "top", "left", "bottom", "right", ")", ":", "param", "bbox2", ":", "(", "page", "width", "height", "top", "left", "bottom", "right", ")", ":", "return", ":", "intersection", "over", "union", "...
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/bbox_utils.py#L129-L149
HazyResearch/pdftotree
pdftotree/utils/display_utils.py
display_bounding_boxes
def display_bounding_boxes(img, blocks, alternatecolors=False, color=Color("blue")): """ Displays each of the bounding boxes passed in 'boxes' on an image of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right) """ draw = Drawing() draw.fill_color = Col...
python
def display_bounding_boxes(img, blocks, alternatecolors=False, color=Color("blue")): """ Displays each of the bounding boxes passed in 'boxes' on an image of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right) """ draw = Drawing() draw.fill_color = Col...
[ "def", "display_bounding_boxes", "(", "img", ",", "blocks", ",", "alternatecolors", "=", "False", ",", "color", "=", "Color", "(", "\"blue\"", ")", ")", ":", "draw", "=", "Drawing", "(", ")", "draw", ".", "fill_color", "=", "Color", "(", "\"rgba(0, 0, 0, 0...
Displays each of the bounding boxes passed in 'boxes' on an image of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right)
[ "Displays", "each", "of", "the", "bounding", "boxes", "passed", "in", "boxes", "on", "an", "image", "of", "the", "pdf", "pointed", "to", "by", "pdf_file", "boxes", "is", "a", "list", "of", "5", "-", "tuples", "(", "page", "top", "left", "bottom", "righ...
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/display_utils.py#L8-L31
HazyResearch/pdftotree
pdftotree/utils/display_utils.py
display_bounding_boxes_within_notebook
def display_bounding_boxes_within_notebook( page_num, extractor, blocks, alternatecolors=False, color=Color("blue") ): """ Displays each of the bounding boxes passed in 'boxes' on an image of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right) """ elem...
python
def display_bounding_boxes_within_notebook( page_num, extractor, blocks, alternatecolors=False, color=Color("blue") ): """ Displays each of the bounding boxes passed in 'boxes' on an image of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right) """ elem...
[ "def", "display_bounding_boxes_within_notebook", "(", "page_num", ",", "extractor", ",", "blocks", ",", "alternatecolors", "=", "False", ",", "color", "=", "Color", "(", "\"blue\"", ")", ")", ":", "elems", "=", "extractor", ".", "elems", "[", "page_num", "]", ...
Displays each of the bounding boxes passed in 'boxes' on an image of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right)
[ "Displays", "each", "of", "the", "bounding", "boxes", "passed", "in", "boxes", "on", "an", "image", "of", "the", "pdf", "pointed", "to", "by", "pdf_file", "boxes", "is", "a", "list", "of", "5", "-", "tuples", "(", "page", "top", "left", "bottom", "righ...
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/display_utils.py#L34-L62
HazyResearch/pdftotree
pdftotree/utils/display_utils.py
pdf_to_img
def pdf_to_img(pdf_file, page_num, page_width, page_height): """ Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object """ img = Image(filename="{}[{}]".format(pdf_file, page_num - 1)) i...
python
def pdf_to_img(pdf_file, page_num, page_width, page_height): """ Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object """ img = Image(filename="{}[{}]".format(pdf_file, page_num - 1)) i...
[ "def", "pdf_to_img", "(", "pdf_file", ",", "page_num", ",", "page_width", ",", "page_height", ")", ":", "img", "=", "Image", "(", "filename", "=", "\"{}[{}]\"", ".", "format", "(", "pdf_file", ",", "page_num", "-", "1", ")", ")", "img", ".", "resize", ...
Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object
[ "Converts", "pdf", "file", "into", "image", ":", "param", "pdf_file", ":", "path", "to", "the", "pdf", "file", ":", "param", "page_num", ":", "page", "number", "to", "convert", "(", "index", "starting", "at", "1", ")", ":", "return", ":", "wand", "imag...
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/display_utils.py#L65-L74
HazyResearch/pdftotree
pdftotree/utils/pdf/render.py
Renderer.draw_rect
def draw_rect(self, bbox, cell_val): """ Fills the bbox with the content values Float bbox values are normalized to have non-zero area """ new_x0 = int(bbox[x0]) new_y0 = int(bbox[y0]) new_x1 = max(new_x0 + 1, int(bbox[x1])) new_y1 = max(new_y0 + 1, int(bb...
python
def draw_rect(self, bbox, cell_val): """ Fills the bbox with the content values Float bbox values are normalized to have non-zero area """ new_x0 = int(bbox[x0]) new_y0 = int(bbox[y0]) new_x1 = max(new_x0 + 1, int(bbox[x1])) new_y1 = max(new_y0 + 1, int(bb...
[ "def", "draw_rect", "(", "self", ",", "bbox", ",", "cell_val", ")", ":", "new_x0", "=", "int", "(", "bbox", "[", "x0", "]", ")", "new_y0", "=", "int", "(", "bbox", "[", "y0", "]", ")", "new_x1", "=", "max", "(", "new_x0", "+", "1", ",", "int", ...
Fills the bbox with the content values Float bbox values are normalized to have non-zero area
[ "Fills", "the", "bbox", "with", "the", "content", "values", "Float", "bbox", "values", "are", "normalized", "to", "have", "non", "-", "zero", "area" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/render.py#L57-L67
HazyResearch/pdftotree
pdftotree/TreeVisualizer.py
TreeVisualizer.display_boxes
def display_boxes(self, tree, html_path, filename_prefix, alternate_colors=False): """ Displays each of the bounding boxes passed in 'boxes' on images of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right) """ imgs = [] colo...
python
def display_boxes(self, tree, html_path, filename_prefix, alternate_colors=False): """ Displays each of the bounding boxes passed in 'boxes' on images of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right) """ imgs = [] colo...
[ "def", "display_boxes", "(", "self", ",", "tree", ",", "html_path", ",", "filename_prefix", ",", "alternate_colors", "=", "False", ")", ":", "imgs", "=", "[", "]", "colors", "=", "{", "\"section_header\"", ":", "Color", "(", "\"blue\"", ")", ",", "\"figure...
Displays each of the bounding boxes passed in 'boxes' on images of the pdf pointed to by pdf_file boxes is a list of 5-tuples (page, top, left, bottom, right)
[ "Displays", "each", "of", "the", "bounding", "boxes", "passed", "in", "boxes", "on", "images", "of", "the", "pdf", "pointed", "to", "by", "pdf_file", "boxes", "is", "a", "list", "of", "5", "-", "tuples", "(", "page", "top", "left", "bottom", "right", "...
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/TreeVisualizer.py#L22-L59
HazyResearch/pdftotree
pdftotree/TreeVisualizer.py
TreeVisualizer.display_candidates
def display_candidates(self, tree, html_path, filename_prefix): """ Displays the bounding boxes corresponding to candidates on an image of the pdf boxes is a list of 5-tuples (page, top, left, bottom, right) """ imgs = self.display_boxes( tree, html_path, filename_pre...
python
def display_candidates(self, tree, html_path, filename_prefix): """ Displays the bounding boxes corresponding to candidates on an image of the pdf boxes is a list of 5-tuples (page, top, left, bottom, right) """ imgs = self.display_boxes( tree, html_path, filename_pre...
[ "def", "display_candidates", "(", "self", ",", "tree", ",", "html_path", ",", "filename_prefix", ")", ":", "imgs", "=", "self", ".", "display_boxes", "(", "tree", ",", "html_path", ",", "filename_prefix", ",", "alternate_colors", "=", "True", ")", "return", ...
Displays the bounding boxes corresponding to candidates on an image of the pdf boxes is a list of 5-tuples (page, top, left, bottom, right)
[ "Displays", "the", "bounding", "boxes", "corresponding", "to", "candidates", "on", "an", "image", "of", "the", "pdf", "boxes", "is", "a", "list", "of", "5", "-", "tuples", "(", "page", "top", "left", "bottom", "right", ")" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/TreeVisualizer.py#L61-L69
HazyResearch/pdftotree
pdftotree/TreeVisualizer.py
TreeVisualizer.pdf_to_img
def pdf_to_img(self, page_num, pdf_dim=None): """ Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object """ if not pdf_dim: pdf_dim = get_pdf_dim(self...
python
def pdf_to_img(self, page_num, pdf_dim=None): """ Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object """ if not pdf_dim: pdf_dim = get_pdf_dim(self...
[ "def", "pdf_to_img", "(", "self", ",", "page_num", ",", "pdf_dim", "=", "None", ")", ":", "if", "not", "pdf_dim", ":", "pdf_dim", "=", "get_pdf_dim", "(", "self", ".", "pdf_file", ")", "page_width", ",", "page_height", "=", "pdf_dim", "img", "=", "Image"...
Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object
[ "Converts", "pdf", "file", "into", "image", ":", "param", "pdf_file", ":", "path", "to", "the", "pdf", "file", ":", "param", "page_num", ":", "page", "number", "to", "convert", "(", "index", "starting", "at", "1", ")", ":", "return", ":", "wand", "imag...
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/TreeVisualizer.py#L71-L83
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_parsers.py
parse_layout
def parse_layout(elems, font_stat, combine=False): """ Parses pdf texts into a hypergraph grouped into rows and columns and then output """ boxes_segments = elems.segments boxes_curves = elems.curves boxes_figures = elems.figures page_width = elems.layout.width # page_height = elems...
python
def parse_layout(elems, font_stat, combine=False): """ Parses pdf texts into a hypergraph grouped into rows and columns and then output """ boxes_segments = elems.segments boxes_curves = elems.curves boxes_figures = elems.figures page_width = elems.layout.width # page_height = elems...
[ "def", "parse_layout", "(", "elems", ",", "font_stat", ",", "combine", "=", "False", ")", ":", "boxes_segments", "=", "elems", ".", "segments", "boxes_curves", "=", "elems", ".", "curves", "boxes_figures", "=", "elems", ".", "figures", "page_width", "=", "el...
Parses pdf texts into a hypergraph grouped into rows and columns and then output
[ "Parses", "pdf", "texts", "into", "a", "hypergraph", "grouped", "into", "rows", "and", "columns", "and", "then", "output" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_parsers.py#L23-L63
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_parsers.py
merge_nodes
def merge_nodes(nodes, plane, page_stat, merge_indices): """ Merges overlapping nodes """ # Merge inner boxes to the best outer box # nodes.sort(key=Node.area) to_be_removed = set() for inner_idx in range(len(nodes)): inner = nodes[inner_idx] outers = [] outers_indice...
python
def merge_nodes(nodes, plane, page_stat, merge_indices): """ Merges overlapping nodes """ # Merge inner boxes to the best outer box # nodes.sort(key=Node.area) to_be_removed = set() for inner_idx in range(len(nodes)): inner = nodes[inner_idx] outers = [] outers_indice...
[ "def", "merge_nodes", "(", "nodes", ",", "plane", ",", "page_stat", ",", "merge_indices", ")", ":", "# Merge inner boxes to the best outer box", "# nodes.sort(key=Node.area)", "to_be_removed", "=", "set", "(", ")", "for", "inner_idx", "in", "range", "(", "len", "(",...
Merges overlapping nodes
[ "Merges", "overlapping", "nodes" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_parsers.py#L1266-L1296
HazyResearch/pdftotree
pdftotree/utils/pdf/pdf_parsers.py
get_most_common_font_pts
def get_most_common_font_pts(mentions, font_stat): """ font_stat: Counter object of font sizes """ log = logging.getLogger(__name__) try: # default min font size of 1 pt in case no font present most_common_font_size = font_stat.most_common(1)[0][0] count = 0.01 # avoid divi...
python
def get_most_common_font_pts(mentions, font_stat): """ font_stat: Counter object of font sizes """ log = logging.getLogger(__name__) try: # default min font size of 1 pt in case no font present most_common_font_size = font_stat.most_common(1)[0][0] count = 0.01 # avoid divi...
[ "def", "get_most_common_font_pts", "(", "mentions", ",", "font_stat", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "try", ":", "# default min font size of 1 pt in case no font present", "most_common_font_size", "=", "font_stat", ".", "most_co...
font_stat: Counter object of font sizes
[ "font_stat", ":", "Counter", "object", "of", "font", "sizes" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/pdf_parsers.py#L1299-L1318
HazyResearch/pdftotree
pdftotree/utils/pdf/node.py
_get_cols
def _get_cols(row_content): """ Counting the number columns based on the content of this row """ cols = [] subcell_col = [] prev_bar = None for _coord, item in row_content: if isinstance(item, LTTextLine): subcell_col.append(item) else: # bar, add column content ...
python
def _get_cols(row_content): """ Counting the number columns based on the content of this row """ cols = [] subcell_col = [] prev_bar = None for _coord, item in row_content: if isinstance(item, LTTextLine): subcell_col.append(item) else: # bar, add column content ...
[ "def", "_get_cols", "(", "row_content", ")", ":", "cols", "=", "[", "]", "subcell_col", "=", "[", "]", "prev_bar", "=", "None", "for", "_coord", ",", "item", "in", "row_content", ":", "if", "isinstance", "(", "item", ",", "LTTextLine", ")", ":", "subce...
Counting the number columns based on the content of this row
[ "Counting", "the", "number", "columns", "based", "on", "the", "content", "of", "this", "row" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/node.py#L187-L206
HazyResearch/pdftotree
pdftotree/utils/pdf/node.py
_one_contains_other
def _one_contains_other(s1, s2): """ Whether one set contains the other """ return min(len(s1), len(s2)) == len(s1 & s2)
python
def _one_contains_other(s1, s2): """ Whether one set contains the other """ return min(len(s1), len(s2)) == len(s1 & s2)
[ "def", "_one_contains_other", "(", "s1", ",", "s2", ")", ":", "return", "min", "(", "len", "(", "s1", ")", ",", "len", "(", "s2", ")", ")", "==", "len", "(", "s1", "&", "s2", ")" ]
Whether one set contains the other
[ "Whether", "one", "set", "contains", "the", "other" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/node.py#L241-L245
HazyResearch/pdftotree
pdftotree/utils/pdf/node.py
Node.is_table
def is_table(self): """ Count the node's number of mention al ignment in both axes to determine if the node is a table. """ if self.type_counts["text"] < 6 or "figure" in self.type_counts: return False for e in self.elems: # Characters written as c...
python
def is_table(self): """ Count the node's number of mention al ignment in both axes to determine if the node is a table. """ if self.type_counts["text"] < 6 or "figure" in self.type_counts: return False for e in self.elems: # Characters written as c...
[ "def", "is_table", "(", "self", ")", ":", "if", "self", ".", "type_counts", "[", "\"text\"", "]", "<", "6", "or", "\"figure\"", "in", "self", ".", "type_counts", ":", "return", "False", "for", "e", "in", "self", ".", "elems", ":", "# Characters written a...
Count the node's number of mention al ignment in both axes to determine if the node is a table.
[ "Count", "the", "node", "s", "number", "of", "mention", "al", "ignment", "in", "both", "axes", "to", "determine", "if", "the", "node", "is", "a", "table", "." ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/node.py#L73-L115
HazyResearch/pdftotree
pdftotree/utils/pdf/node.py
Node.get_grid
def get_grid(self): """ Standardize the layout of the table into grids """ mentions, lines = _split_text_n_lines(self.elems) # Sort mentions in reading order where y values are snapped to half # height-sized grid mentions.sort(key=lambda m: (m.yc_grid, m.xc)) ...
python
def get_grid(self): """ Standardize the layout of the table into grids """ mentions, lines = _split_text_n_lines(self.elems) # Sort mentions in reading order where y values are snapped to half # height-sized grid mentions.sort(key=lambda m: (m.yc_grid, m.xc)) ...
[ "def", "get_grid", "(", "self", ")", ":", "mentions", ",", "lines", "=", "_split_text_n_lines", "(", "self", ".", "elems", ")", "# Sort mentions in reading order where y values are snapped to half", "# height-sized grid", "mentions", ".", "sort", "(", "key", "=", "lam...
Standardize the layout of the table into grids
[ "Standardize", "the", "layout", "of", "the", "table", "into", "grids" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/node.py#L118-L128
HazyResearch/pdftotree
pdftotree/utils/lines_utils.py
reorder_lines
def reorder_lines(lines, tol=TOLERANCE): """ Changes the line coordinates to be given as (top, left, bottom, right) :param lines: list of lines coordinates :return: reordered list of lines coordinates """ reordered_lines = [] for line in lines: # we divide by tol and multiply by tol ...
python
def reorder_lines(lines, tol=TOLERANCE): """ Changes the line coordinates to be given as (top, left, bottom, right) :param lines: list of lines coordinates :return: reordered list of lines coordinates """ reordered_lines = [] for line in lines: # we divide by tol and multiply by tol ...
[ "def", "reorder_lines", "(", "lines", ",", "tol", "=", "TOLERANCE", ")", ":", "reordered_lines", "=", "[", "]", "for", "line", "in", "lines", ":", "# we divide by tol and multiply by tol to truncate numbers, stairs function", "reordered_lines", "+=", "[", "(", "int", ...
Changes the line coordinates to be given as (top, left, bottom, right) :param lines: list of lines coordinates :return: reordered list of lines coordinates
[ "Changes", "the", "line", "coordinates", "to", "be", "given", "as", "(", "top", "left", "bottom", "right", ")", ":", "param", "lines", ":", "list", "of", "lines", "coordinates", ":", "return", ":", "reordered", "list", "of", "lines", "coordinates" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/lines_utils.py#L4-L21
HazyResearch/pdftotree
pdftotree/utils/lines_utils.py
merge_vertical_lines
def merge_vertical_lines(lines, tol=TOLERANCE): """ This function merges lines segment when they are vertically aligned :param lines: list of lines coordinates (top, left, bottom, right) :return: list of merged lines coordinates """ if len(lines) == 0: return [] merged_lines = [lines...
python
def merge_vertical_lines(lines, tol=TOLERANCE): """ This function merges lines segment when they are vertically aligned :param lines: list of lines coordinates (top, left, bottom, right) :return: list of merged lines coordinates """ if len(lines) == 0: return [] merged_lines = [lines...
[ "def", "merge_vertical_lines", "(", "lines", ",", "tol", "=", "TOLERANCE", ")", ":", "if", "len", "(", "lines", ")", "==", "0", ":", "return", "[", "]", "merged_lines", "=", "[", "lines", "[", "0", "]", "]", "for", "line", "in", "lines", "[", "1", ...
This function merges lines segment when they are vertically aligned :param lines: list of lines coordinates (top, left, bottom, right) :return: list of merged lines coordinates
[ "This", "function", "merges", "lines", "segment", "when", "they", "are", "vertically", "aligned", ":", "param", "lines", ":", "list", "of", "lines", "coordinates", "(", "top", "left", "bottom", "right", ")", ":", "return", ":", "list", "of", "merged", "lin...
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/lines_utils.py#L24-L45
HazyResearch/pdftotree
pdftotree/utils/lines_utils.py
get_vertical_and_horizontal
def get_vertical_and_horizontal(lines): """ Extracts vertical and horizontal lines lists :param lines: list of lines coordinates :return: vertical_lines, horitontal_lines (2 lists of coordinates) """ # TODO: add some angle tolerance when lines are not perfectly aligned (eg: # scanned pdf) ...
python
def get_vertical_and_horizontal(lines): """ Extracts vertical and horizontal lines lists :param lines: list of lines coordinates :return: vertical_lines, horitontal_lines (2 lists of coordinates) """ # TODO: add some angle tolerance when lines are not perfectly aligned (eg: # scanned pdf) ...
[ "def", "get_vertical_and_horizontal", "(", "lines", ")", ":", "# TODO: add some angle tolerance when lines are not perfectly aligned (eg:", "# scanned pdf)", "vertical_lines", "=", "sorted", "(", "[", "e", "for", "e", "in", "lines", "if", "e", "[", "1", "]", "==", "e"...
Extracts vertical and horizontal lines lists :param lines: list of lines coordinates :return: vertical_lines, horitontal_lines (2 lists of coordinates)
[ "Extracts", "vertical", "and", "horizontal", "lines", "lists", ":", "param", "lines", ":", "list", "of", "lines", "coordinates", ":", "return", ":", "vertical_lines", "horitontal_lines", "(", "2", "lists", "of", "coordinates", ")" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/lines_utils.py#L72-L88
HazyResearch/pdftotree
pdftotree/utils/img_utils.py
lazy_load_font
def lazy_load_font(font_size=default_font_size): """ Lazy loading font according to system platform """ if font_size not in _font_cache: if _platform.startswith("darwin"): font_path = "/Library/Fonts/Arial.ttf" elif _platform.startswith("linux"): font_path = "/usr...
python
def lazy_load_font(font_size=default_font_size): """ Lazy loading font according to system platform """ if font_size not in _font_cache: if _platform.startswith("darwin"): font_path = "/Library/Fonts/Arial.ttf" elif _platform.startswith("linux"): font_path = "/usr...
[ "def", "lazy_load_font", "(", "font_size", "=", "default_font_size", ")", ":", "if", "font_size", "not", "in", "_font_cache", ":", "if", "_platform", ".", "startswith", "(", "\"darwin\"", ")", ":", "font_path", "=", "\"/Library/Fonts/Arial.ttf\"", "elif", "_platfo...
Lazy loading font according to system platform
[ "Lazy", "loading", "font", "according", "to", "system", "platform" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/img_utils.py#L24-L36
HazyResearch/pdftotree
pdftotree/utils/img_utils.py
normalize_bbox
def normalize_bbox(coords, ymax, scaler=2): """ scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left) """ return [ coords[0] * scaler, ymax - (coords[3] * scaler), coords[2] * scaler, ymax - (coords[1] * scaler), ]
python
def normalize_bbox(coords, ymax, scaler=2): """ scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left) """ return [ coords[0] * scaler, ymax - (coords[3] * scaler), coords[2] * scaler, ymax - (coords[1] * scaler), ]
[ "def", "normalize_bbox", "(", "coords", ",", "ymax", ",", "scaler", "=", "2", ")", ":", "return", "[", "coords", "[", "0", "]", "*", "scaler", ",", "ymax", "-", "(", "coords", "[", "3", "]", "*", "scaler", ")", ",", "coords", "[", "2", "]", "*"...
scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left)
[ "scales", "all", "coordinates", "and", "flip", "y", "axis", "due", "to", "different", "origin", "coordinates", "(", "top", "left", "vs", ".", "bottom", "left", ")" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/img_utils.py#L39-L49
HazyResearch/pdftotree
pdftotree/utils/img_utils.py
normalize_pts
def normalize_pts(pts, ymax, scaler=2): """ scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left) """ return [(x * scaler, ymax - (y * scaler)) for x, y in pts]
python
def normalize_pts(pts, ymax, scaler=2): """ scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left) """ return [(x * scaler, ymax - (y * scaler)) for x, y in pts]
[ "def", "normalize_pts", "(", "pts", ",", "ymax", ",", "scaler", "=", "2", ")", ":", "return", "[", "(", "x", "*", "scaler", ",", "ymax", "-", "(", "y", "*", "scaler", ")", ")", "for", "x", ",", "y", "in", "pts", "]" ]
scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left)
[ "scales", "all", "coordinates", "and", "flip", "y", "axis", "due", "to", "different", "origin", "coordinates", "(", "top", "left", "vs", ".", "bottom", "left", ")" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/img_utils.py#L52-L57
HazyResearch/pdftotree
pdftotree/utils/img_utils.py
render_debug_img
def render_debug_img( file_name, page_num, elems, nodes=[], scaler=1, print_segments=False, print_curves=True, print_table_bbox=True, print_text_as_rect=True, ): """ Shows an image rendering of the pdf page along with debugging info printed """ # For debugging sho...
python
def render_debug_img( file_name, page_num, elems, nodes=[], scaler=1, print_segments=False, print_curves=True, print_table_bbox=True, print_text_as_rect=True, ): """ Shows an image rendering of the pdf page along with debugging info printed """ # For debugging sho...
[ "def", "render_debug_img", "(", "file_name", ",", "page_num", ",", "elems", ",", "nodes", "=", "[", "]", ",", "scaler", "=", "1", ",", "print_segments", "=", "False", ",", "print_curves", "=", "True", ",", "print_table_bbox", "=", "True", ",", "print_text_...
Shows an image rendering of the pdf page along with debugging info printed
[ "Shows", "an", "image", "rendering", "of", "the", "pdf", "page", "along", "with", "debugging", "info", "printed" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/img_utils.py#L93-L160
HazyResearch/pdftotree
pdftotree/ml/TableExtractML.py
TableExtractorML.get_labels
def get_labels(self, gt_tables): """ :param gt_tables: dict, keys are page number and values are list of tables bbox within that page :return: """ labels = np.zeros(len(self.candidates)) for i, candidate in enumerate(self.candidates): ...
python
def get_labels(self, gt_tables): """ :param gt_tables: dict, keys are page number and values are list of tables bbox within that page :return: """ labels = np.zeros(len(self.candidates)) for i, candidate in enumerate(self.candidates): ...
[ "def", "get_labels", "(", "self", ",", "gt_tables", ")", ":", "labels", "=", "np", ".", "zeros", "(", "len", "(", "self", ".", "candidates", ")", ")", "for", "i", ",", "candidate", "in", "enumerate", "(", "self", ".", "candidates", ")", ":", "page_nu...
:param gt_tables: dict, keys are page number and values are list of tables bbox within that page :return:
[ ":", "param", "gt_tables", ":", "dict", "keys", "are", "page", "number", "and", "values", "are", "list", "of", "tables", "bbox", "within", "that", "page", ":", "return", ":" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/ml/TableExtractML.py#L222-L250
HazyResearch/pdftotree
pdftotree/ml/features.py
get_text_sparsity
def get_text_sparsity(bbox, mentions): """ computes text area coverage :param mentions: :return: """ b = bbox[-4:] bbox_area = (b[2] - b[0]) * (b[3] - b[1]) text_area = 0 for m in mentions: text_area += (m.x1 - m.x0) * (m.y1 - m.y0) try: return 1.0 * text_area / b...
python
def get_text_sparsity(bbox, mentions): """ computes text area coverage :param mentions: :return: """ b = bbox[-4:] bbox_area = (b[2] - b[0]) * (b[3] - b[1]) text_area = 0 for m in mentions: text_area += (m.x1 - m.x0) * (m.y1 - m.y0) try: return 1.0 * text_area / b...
[ "def", "get_text_sparsity", "(", "bbox", ",", "mentions", ")", ":", "b", "=", "bbox", "[", "-", "4", ":", "]", "bbox_area", "=", "(", "b", "[", "2", "]", "-", "b", "[", "0", "]", ")", "*", "(", "b", "[", "3", "]", "-", "b", "[", "1", "]",...
computes text area coverage :param mentions: :return:
[ "computes", "text", "area", "coverage", ":", "param", "mentions", ":", ":", "return", ":" ]
train
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/ml/features.py#L53-L67
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
_partition_estimators
def _partition_estimators(n_estimators, n_jobs): """Private function used to partition estimators between jobs.""" # Compute the number of jobs if n_jobs == -1: n_jobs = min(cpu_count(), n_estimators) else: n_jobs = min(n_jobs, n_estimators) # Partition estimators between jobs ...
python
def _partition_estimators(n_estimators, n_jobs): """Private function used to partition estimators between jobs.""" # Compute the number of jobs if n_jobs == -1: n_jobs = min(cpu_count(), n_estimators) else: n_jobs = min(n_jobs, n_estimators) # Partition estimators between jobs ...
[ "def", "_partition_estimators", "(", "n_estimators", ",", "n_jobs", ")", ":", "# Compute the number of jobs", "if", "n_jobs", "==", "-", "1", ":", "n_jobs", "=", "min", "(", "cpu_count", "(", ")", ",", "n_estimators", ")", "else", ":", "n_jobs", "=", "min", ...
Private function used to partition estimators between jobs.
[ "Private", "function", "used", "to", "partition", "estimators", "between", "jobs", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L36-L51
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
_parallel_build_estimators
def _parallel_build_estimators(n_estimators, ensemble, X, y, cost_mat, seeds, verbose): """Private function used to build a batch of estimators within a job.""" # Retrieve settings n_samples, n_features = X.shape max_samples = ensemble.max_samples max_features = ensemb...
python
def _parallel_build_estimators(n_estimators, ensemble, X, y, cost_mat, seeds, verbose): """Private function used to build a batch of estimators within a job.""" # Retrieve settings n_samples, n_features = X.shape max_samples = ensemble.max_samples max_features = ensemb...
[ "def", "_parallel_build_estimators", "(", "n_estimators", ",", "ensemble", ",", "X", ",", "y", ",", "cost_mat", ",", "seeds", ",", "verbose", ")", ":", "# Retrieve settings", "n_samples", ",", "n_features", "=", "X", ".", "shape", "max_samples", "=", "ensemble...
Private function used to build a batch of estimators within a job.
[ "Private", "function", "used", "to", "build", "a", "batch", "of", "estimators", "within", "a", "job", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L54-L116
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
_parallel_predict_proba
def _parallel_predict_proba(estimators, estimators_features, X, n_classes, combination, estimators_weight): """Private function used to compute (proba-)predictions within a job.""" n_samples = X.shape[0] proba = np.zeros((n_samples, n_classes)) for estimator, features, weight in zip(estimators, estimat...
python
def _parallel_predict_proba(estimators, estimators_features, X, n_classes, combination, estimators_weight): """Private function used to compute (proba-)predictions within a job.""" n_samples = X.shape[0] proba = np.zeros((n_samples, n_classes)) for estimator, features, weight in zip(estimators, estimat...
[ "def", "_parallel_predict_proba", "(", "estimators", ",", "estimators_features", ",", "X", ",", "n_classes", ",", "combination", ",", "estimators_weight", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "proba", "=", "np", ".", "zeros", "(", ...
Private function used to compute (proba-)predictions within a job.
[ "Private", "function", "used", "to", "compute", "(", "proba", "-", ")", "predictions", "within", "a", "job", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L119-L131
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
_parallel_predict
def _parallel_predict(estimators, estimators_features, X, n_classes, combination, estimators_weight): """Private function used to compute predictions within a job.""" n_samples = X.shape[0] pred = np.zeros((n_samples, n_classes)) n_estimators = len(estimators) for estimator, features, weight in zip...
python
def _parallel_predict(estimators, estimators_features, X, n_classes, combination, estimators_weight): """Private function used to compute predictions within a job.""" n_samples = X.shape[0] pred = np.zeros((n_samples, n_classes)) n_estimators = len(estimators) for estimator, features, weight in zip...
[ "def", "_parallel_predict", "(", "estimators", ",", "estimators_features", ",", "X", ",", "n_classes", ",", "combination", ",", "estimators_weight", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "pred", "=", "np", ".", "zeros", "(", "(", ...
Private function used to compute predictions within a job.
[ "Private", "function", "used", "to", "compute", "predictions", "within", "a", "job", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L134-L150
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
_create_stacking_set
def _create_stacking_set(estimators, estimators_features, estimators_weight, X, combination): """Private function used to create the stacking training set.""" n_samples = X.shape[0] valid_estimators = np.nonzero(estimators_weight)[0] n_valid_estimators = valid_estimators.shape[0] X_stacking = np.ze...
python
def _create_stacking_set(estimators, estimators_features, estimators_weight, X, combination): """Private function used to create the stacking training set.""" n_samples = X.shape[0] valid_estimators = np.nonzero(estimators_weight)[0] n_valid_estimators = valid_estimators.shape[0] X_stacking = np.ze...
[ "def", "_create_stacking_set", "(", "estimators", ",", "estimators_features", ",", "estimators_weight", ",", "X", ",", "combination", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "valid_estimators", "=", "np", ".", "nonzero", "(", "estimators_...
Private function used to create the stacking training set.
[ "Private", "function", "used", "to", "create", "the", "stacking", "training", "set", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L153-L167
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
BaseBagging.fit
def fit(self, X, y, cost_mat, sample_weight=None): """Build a Bagging ensemble of estimators from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape = [n_samples, n_features] The training input samples. Sparse matrices are accepted only i...
python
def fit(self, X, y, cost_mat, sample_weight=None): """Build a Bagging ensemble of estimators from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape = [n_samples, n_features] The training input samples. Sparse matrices are accepted only i...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "cost_mat", ",", "sample_weight", "=", "None", ")", ":", "random_state", "=", "check_random_state", "(", "self", ".", "random_state", ")", "# Convert data", "# X, y = check_X_y(X, y, ['csr', 'csc', 'coo']) # Not i...
Build a Bagging ensemble of estimators from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape = [n_samples, n_features] The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. ...
[ "Build", "a", "Bagging", "ensemble", "of", "estimators", "from", "the", "training", "set", "(", "X", "y", ")", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L202-L293
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
BaseBagging._fit_bmr_model
def _fit_bmr_model(self, X, y): """Private function used to fit the BayesMinimumRisk model.""" self.f_bmr = BayesMinimumRiskClassifier() X_bmr = self.predict_proba(X) self.f_bmr.fit(y, X_bmr) return self
python
def _fit_bmr_model(self, X, y): """Private function used to fit the BayesMinimumRisk model.""" self.f_bmr = BayesMinimumRiskClassifier() X_bmr = self.predict_proba(X) self.f_bmr.fit(y, X_bmr) return self
[ "def", "_fit_bmr_model", "(", "self", ",", "X", ",", "y", ")", ":", "self", ".", "f_bmr", "=", "BayesMinimumRiskClassifier", "(", ")", "X_bmr", "=", "self", ".", "predict_proba", "(", "X", ")", "self", ".", "f_bmr", ".", "fit", "(", "y", ",", "X_bmr"...
Private function used to fit the BayesMinimumRisk model.
[ "Private", "function", "used", "to", "fit", "the", "BayesMinimumRisk", "model", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L295-L300
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
BaseBagging._fit_stacking_model
def _fit_stacking_model(self,X, y, cost_mat, max_iter=100): """Private function used to fit the stacking model.""" self.f_staking = CostSensitiveLogisticRegression(verbose=self.verbose, max_iter=max_iter) X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_, ...
python
def _fit_stacking_model(self,X, y, cost_mat, max_iter=100): """Private function used to fit the stacking model.""" self.f_staking = CostSensitiveLogisticRegression(verbose=self.verbose, max_iter=max_iter) X_stacking = _create_stacking_set(self.estimators_, self.estimators_features_, ...
[ "def", "_fit_stacking_model", "(", "self", ",", "X", ",", "y", ",", "cost_mat", ",", "max_iter", "=", "100", ")", ":", "self", ".", "f_staking", "=", "CostSensitiveLogisticRegression", "(", "verbose", "=", "self", ".", "verbose", ",", "max_iter", "=", "max...
Private function used to fit the stacking model.
[ "Private", "function", "used", "to", "fit", "the", "stacking", "model", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L302-L308
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
BaseBagging._evaluate_oob_savings
def _evaluate_oob_savings(self, X, y, cost_mat): """Private function used to calculate the OOB Savings of each estimator.""" estimators_weight = [] for estimator, samples, features in zip(self.estimators_, self.estimators_samples_, self.estimators_...
python
def _evaluate_oob_savings(self, X, y, cost_mat): """Private function used to calculate the OOB Savings of each estimator.""" estimators_weight = [] for estimator, samples, features in zip(self.estimators_, self.estimators_samples_, self.estimators_...
[ "def", "_evaluate_oob_savings", "(", "self", ",", "X", ",", "y", ",", "cost_mat", ")", ":", "estimators_weight", "=", "[", "]", "for", "estimator", ",", "samples", ",", "features", "in", "zip", "(", "self", ".", "estimators_", ",", "self", ".", "estimato...
Private function used to calculate the OOB Savings of each estimator.
[ "Private", "function", "used", "to", "calculate", "the", "OOB", "Savings", "of", "each", "estimator", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L311-L334
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
BaggingClassifier.predict
def predict(self, X, cost_mat=None): """Predict class for X. The predicted class of an input sample is computed as the class with the highest mean predicted probability. If base estimators do not implement a ``predict_proba`` method, then it resorts to voting. Parameters ...
python
def predict(self, X, cost_mat=None): """Predict class for X. The predicted class of an input sample is computed as the class with the highest mean predicted probability. If base estimators do not implement a ``predict_proba`` method, then it resorts to voting. Parameters ...
[ "def", "predict", "(", "self", ",", "X", ",", "cost_mat", "=", "None", ")", ":", "# Check data", "# X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) # Dont in version 0.15", "if", "self", ".", "n_features_", "!=", "X", ".", "shape", "[", "1", "]", ":", "ra...
Predict class for X. The predicted class of an input sample is computed as the class with the highest mean predicted probability. If base estimators do not implement a ``predict_proba`` method, then it resorts to voting. Parameters ---------- X : {array-like, sparse mat...
[ "Predict", "class", "for", "X", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L491-L554
albahnsen/CostSensitiveClassification
costcla/models/bagging.py
BaggingClassifier.predict_proba
def predict_proba(self, X): """Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble. If base estimators do not implement a ``predict_proba`` method, th...
python
def predict_proba(self, X): """Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble. If base estimators do not implement a ``predict_proba`` method, th...
[ "def", "predict_proba", "(", "self", ",", "X", ")", ":", "# Check data", "# X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) # Dont in version 0.15", "if", "self", ".", "n_features_", "!=", "X", ".", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "...
Predict class probabilities for X. The predicted class probabilities of an input sample is computed as the mean predicted class probabilities of the base estimators in the ensemble. If base estimators do not implement a ``predict_proba`` method, then it resorts to voting and the predict...
[ "Predict", "class", "probabilities", "for", "X", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/bagging.py#L556-L610
albahnsen/CostSensitiveClassification
costcla/sampling/cost_sampling.py
cost_sampling
def cost_sampling(X, y, cost_mat, method='RejectionSampling', oversampling_norm=0.1, max_wc=97.5): """Cost-proportionate sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground...
python
def cost_sampling(X, y, cost_mat, method='RejectionSampling', oversampling_norm=0.1, max_wc=97.5): """Cost-proportionate sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground...
[ "def", "cost_sampling", "(", "X", ",", "y", ",", "cost_mat", ",", "method", "=", "'RejectionSampling'", ",", "oversampling_norm", "=", "0.1", ",", "max_wc", "=", "97.5", ")", ":", "#TODO: Check consistency of input", "# The methods are construct only for the misclassifi...
Cost-proportionate sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] Cost matrix ...
[ "Cost", "-", "proportionate", "sampling", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/cost_sampling.py#L11-L123
albahnsen/CostSensitiveClassification
costcla/datasets/base.py
load_churn
def load_churn(): """Load and return the churn dataset (classification). The bank marketing is a easily transformable example-dependent cost-sensitive classification dataset. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to le...
python
def load_churn(): """Load and return the churn dataset (classification). The bank marketing is a easily transformable example-dependent cost-sensitive classification dataset. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to le...
[ "def", "load_churn", "(", ")", ":", "module_path", "=", "dirname", "(", "__file__", ")", "raw_data", "=", "pd", ".", "read_csv", "(", "join", "(", "module_path", ",", "'data'", ",", "'churn_tv_subscriptions.csv.gz'", ")", ",", "delimiter", "=", "','", ",", ...
Load and return the churn dataset (classification). The bank marketing is a easily transformable example-dependent cost-sensitive classification dataset. Returns ------- data : Bunch Dictionary-like object, the interesting attributes are: 'data', the data to learn, 'target', the classi...
[ "Load", "and", "return", "the", "churn", "dataset", "(", "classification", ")", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/datasets/base.py#L26-L78
albahnsen/CostSensitiveClassification
costcla/datasets/base.py
load_bankmarketing
def load_bankmarketing(cost_mat_parameters=None): """Load and return the bank marketing dataset (classification). The bank marketing is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-like object, optional (defa...
python
def load_bankmarketing(cost_mat_parameters=None): """Load and return the bank marketing dataset (classification). The bank marketing is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-like object, optional (defa...
[ "def", "load_bankmarketing", "(", "cost_mat_parameters", "=", "None", ")", ":", "module_path", "=", "dirname", "(", "__file__", ")", "raw_data", "=", "pd", ".", "read_csv", "(", "join", "(", "module_path", ",", "'data'", ",", "'bankmarketing.csv.gz'", ")", ","...
Load and return the bank marketing dataset (classification). The bank marketing is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-like object, optional (default=None) If not None, must include 'per_balance'...
[ "Load", "and", "return", "the", "bank", "marketing", "dataset", "(", "classification", ")", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/datasets/base.py#L81-L180
albahnsen/CostSensitiveClassification
costcla/datasets/base.py
load_creditscoring1
def load_creditscoring1(cost_mat_parameters=None): """Load and return the credit scoring Kaggle Credit competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-...
python
def load_creditscoring1(cost_mat_parameters=None): """Load and return the credit scoring Kaggle Credit competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-...
[ "def", "load_creditscoring1", "(", "cost_mat_parameters", "=", "None", ")", ":", "module_path", "=", "dirname", "(", "__file__", ")", "raw_data", "=", "pd", ".", "read_csv", "(", "join", "(", "module_path", ",", "'data'", ",", "'creditscoring1.csv.gz'", ")", "...
Load and return the credit scoring Kaggle Credit competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-like object, optional (default=None) If not None, ...
[ "Load", "and", "return", "the", "credit", "scoring", "Kaggle", "Credit", "competition", "dataset", "(", "classification", ")", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/datasets/base.py#L183-L249
albahnsen/CostSensitiveClassification
costcla/datasets/base.py
load_creditscoring2
def load_creditscoring2(cost_mat_parameters=None): """Load and return the credit scoring PAKDD 2009 competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-lik...
python
def load_creditscoring2(cost_mat_parameters=None): """Load and return the credit scoring PAKDD 2009 competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-lik...
[ "def", "load_creditscoring2", "(", "cost_mat_parameters", "=", "None", ")", ":", "module_path", "=", "dirname", "(", "__file__", ")", "raw_data", "=", "pd", ".", "read_csv", "(", "join", "(", "module_path", ",", "'data'", ",", "'creditscoring2.csv.gz'", ")", "...
Load and return the credit scoring PAKDD 2009 competition dataset (classification). The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset. Parameters ---------- cost_mat_parameters : Dictionary-like object, optional (default=None) If not None, mus...
[ "Load", "and", "return", "the", "credit", "scoring", "PAKDD", "2009", "competition", "dataset", "(", "classification", ")", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/datasets/base.py#L252-L333
albahnsen/CostSensitiveClassification
costcla/datasets/base.py
_creditscoring_costmat
def _creditscoring_costmat(income, debt, pi_1, cost_mat_parameters): """ Private function to calculate the cost matrix of credit scoring models. Parameters ---------- income : array of shape = [n_samples] Monthly income of each example debt : array of shape = [n_samples] Debt ratio...
python
def _creditscoring_costmat(income, debt, pi_1, cost_mat_parameters): """ Private function to calculate the cost matrix of credit scoring models. Parameters ---------- income : array of shape = [n_samples] Monthly income of each example debt : array of shape = [n_samples] Debt ratio...
[ "def", "_creditscoring_costmat", "(", "income", ",", "debt", ",", "pi_1", ",", "cost_mat_parameters", ")", ":", "def", "calculate_a", "(", "cl_i", ",", "int_", ",", "n_term", ")", ":", "\"\"\" Private function \"\"\"", "return", "cl_i", "*", "(", "(", "int_", ...
Private function to calculate the cost matrix of credit scoring models. Parameters ---------- income : array of shape = [n_samples] Monthly income of each example debt : array of shape = [n_samples] Debt ratio each example pi_1 : float Percentage of positives in the traini...
[ "Private", "function", "to", "calculate", "the", "cost", "matrix", "of", "credit", "scoring", "models", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/datasets/base.py#L336-L415
albahnsen/CostSensitiveClassification
costcla/probcal/probcal.py
_convexhull
def _convexhull(P): """ Private function that calculate the convex hull of a set of points The algorithm was taken from [1]. http://code.activestate.com/recipes/66527-finding-the-convex-hull-of-a-set-of-2d-points/ References ---------- .. [1] Alex Martelli, Anna Ravenscroft, David Ascher, 'Pyt...
python
def _convexhull(P): """ Private function that calculate the convex hull of a set of points The algorithm was taken from [1]. http://code.activestate.com/recipes/66527-finding-the-convex-hull-of-a-set-of-2d-points/ References ---------- .. [1] Alex Martelli, Anna Ravenscroft, David Ascher, 'Pyt...
[ "def", "_convexhull", "(", "P", ")", ":", "def", "mydet", "(", "p", ",", "q", ",", "r", ")", ":", "\"\"\"Calc. determinant of a special matrix with three 2D points.\n\n The sign, \"-\" or \"+\", determines the side, right or left,\n respectivly, on which the point r lie...
Private function that calculate the convex hull of a set of points The algorithm was taken from [1]. http://code.activestate.com/recipes/66527-finding-the-convex-hull-of-a-set-of-2d-points/ References ---------- .. [1] Alex Martelli, Anna Ravenscroft, David Ascher, 'Python Cookbook', O'Reilly Medi...
[ "Private", "function", "that", "calculate", "the", "convex", "hull", "of", "a", "set", "of", "points", "The", "algorithm", "was", "taken", "from", "[", "1", "]", ".", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "recipes", "/", "6652...
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/probcal/probcal.py#L164-L225
albahnsen/CostSensitiveClassification
costcla/probcal/probcal.py
ROCConvexHull.fit
def fit(self, y, p): """ Fit the calibration map Parameters ---------- y_true : array-like of shape = [n_samples] True class to be used for calibrating the probabilities y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be used for...
python
def fit(self, y, p): """ Fit the calibration map Parameters ---------- y_true : array-like of shape = [n_samples] True class to be used for calibrating the probabilities y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be used for...
[ "def", "fit", "(", "self", ",", "y", ",", "p", ")", ":", "# TODO: Check input", "if", "p", ".", "size", "!=", "p", ".", "shape", "[", "0", "]", ":", "p", "=", "p", "[", ":", ",", "1", "]", "fpr", ",", "tpr", ",", "thresholds", "=", "roc_curve...
Fit the calibration map Parameters ---------- y_true : array-like of shape = [n_samples] True class to be used for calibrating the probabilities y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be used for calibrating the probabilities ...
[ "Fit", "the", "calibration", "map" ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/probcal/probcal.py#L62-L135
albahnsen/CostSensitiveClassification
costcla/probcal/probcal.py
ROCConvexHull.predict_proba
def predict_proba(self, p): """ Calculate the calibrated probabilities Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be calibrated using calibration map Returns ------- y_prob_cal : array-like of shape...
python
def predict_proba(self, p): """ Calculate the calibrated probabilities Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be calibrated using calibration map Returns ------- y_prob_cal : array-like of shape...
[ "def", "predict_proba", "(", "self", ",", "p", ")", ":", "# TODO: Check input", "if", "p", ".", "size", "!=", "p", ".", "shape", "[", "0", "]", ":", "p", "=", "p", "[", ":", ",", "1", "]", "calibrated_proba", "=", "np", ".", "zeros", "(", "p", ...
Calculate the calibrated probabilities Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities to be calibrated using calibration map Returns ------- y_prob_cal : array-like of shape = [n_samples, 1] Predicted ...
[ "Calculate", "the", "calibrated", "probabilities" ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/probcal/probcal.py#L137-L161
albahnsen/CostSensitiveClassification
costcla/utils/cross_validation.py
cross_val_score
def cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs'): """Evaluate a score by cross-validation Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. ...
python
def cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs'): """Evaluate a score by cross-validation Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. ...
[ "def", "cross_val_score", "(", "estimator", ",", "X", ",", "y", "=", "None", ",", "scoring", "=", "None", ",", "cv", "=", "None", ",", "n_jobs", "=", "1", ",", "verbose", "=", "0", ",", "fit_params", "=", "None", ",", "pre_dispatch", "=", "'2*n_jobs'...
Evaluate a score by cross-validation Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like The data to fit. Can be, for example a list, or an array at least 2d. y : array-like, optional, default: None The ta...
[ "Evaluate", "a", "score", "by", "cross", "-", "validation" ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1080-L1151
albahnsen/CostSensitiveClassification
costcla/utils/cross_validation.py
_fit_and_score
def _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score=False, return_parameters=False): """Fit estimator and compute scores for a given dataset split. Parameters ---------- estimator : estimator object implement...
python
def _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score=False, return_parameters=False): """Fit estimator and compute scores for a given dataset split. Parameters ---------- estimator : estimator object implement...
[ "def", "_fit_and_score", "(", "estimator", ",", "X", ",", "y", ",", "scorer", ",", "train", ",", "test", ",", "verbose", ",", "parameters", ",", "fit_params", ",", "return_train_score", "=", "False", ",", "return_parameters", "=", "False", ")", ":", "if", ...
Fit estimator and compute scores for a given dataset split. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like of shape at least 2D The data to fit. y : array-like, optional, default: None The target vari...
[ "Fit", "estimator", "and", "compute", "scores", "for", "a", "given", "dataset", "split", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1154-L1255
albahnsen/CostSensitiveClassification
costcla/utils/cross_validation.py
_safe_split
def _safe_split(estimator, X, y, indices, train_indices=None): """Create subset of dataset and properly handle kernels.""" if hasattr(estimator, 'kernel') and isinstance(estimator.kernel, collections.Callable): # cannot compute the kernel values with custom function raise ValueError("Cannot use ...
python
def _safe_split(estimator, X, y, indices, train_indices=None): """Create subset of dataset and properly handle kernels.""" if hasattr(estimator, 'kernel') and isinstance(estimator.kernel, collections.Callable): # cannot compute the kernel values with custom function raise ValueError("Cannot use ...
[ "def", "_safe_split", "(", "estimator", ",", "X", ",", "y", ",", "indices", ",", "train_indices", "=", "None", ")", ":", "if", "hasattr", "(", "estimator", ",", "'kernel'", ")", "and", "isinstance", "(", "estimator", ".", "kernel", ",", "collections", "....
Create subset of dataset and properly handle kernels.
[ "Create", "subset", "of", "dataset", "and", "properly", "handle", "kernels", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1258-L1287
albahnsen/CostSensitiveClassification
costcla/utils/cross_validation.py
_score
def _score(estimator, X_test, y_test, scorer): """Compute the score of an estimator on a given test set.""" if y_test is None: score = scorer(estimator, X_test) else: score = scorer(estimator, X_test, y_test) if not isinstance(score, numbers.Number): raise ValueError("scoring mus...
python
def _score(estimator, X_test, y_test, scorer): """Compute the score of an estimator on a given test set.""" if y_test is None: score = scorer(estimator, X_test) else: score = scorer(estimator, X_test, y_test) if not isinstance(score, numbers.Number): raise ValueError("scoring mus...
[ "def", "_score", "(", "estimator", ",", "X_test", ",", "y_test", ",", "scorer", ")", ":", "if", "y_test", "is", "None", ":", "score", "=", "scorer", "(", "estimator", ",", "X_test", ")", "else", ":", "score", "=", "scorer", "(", "estimator", ",", "X_...
Compute the score of an estimator on a given test set.
[ "Compute", "the", "score", "of", "an", "estimator", "on", "a", "given", "test", "set", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1290-L1299
albahnsen/CostSensitiveClassification
costcla/utils/cross_validation.py
_shuffle
def _shuffle(y, labels, random_state): """Return a shuffled copy of y eventually shuffle among same labels.""" if labels is None: ind = random_state.permutation(len(y)) else: ind = np.arange(len(labels)) for label in np.unique(labels): this_mask = (labels == label) ...
python
def _shuffle(y, labels, random_state): """Return a shuffled copy of y eventually shuffle among same labels.""" if labels is None: ind = random_state.permutation(len(y)) else: ind = np.arange(len(labels)) for label in np.unique(labels): this_mask = (labels == label) ...
[ "def", "_shuffle", "(", "y", ",", "labels", ",", "random_state", ")", ":", "if", "labels", "is", "None", ":", "ind", "=", "random_state", ".", "permutation", "(", "len", "(", "y", ")", ")", "else", ":", "ind", "=", "np", ".", "arange", "(", "len", ...
Return a shuffled copy of y eventually shuffle among same labels.
[ "Return", "a", "shuffled", "copy", "of", "y", "eventually", "shuffle", "among", "same", "labels", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1311-L1320
albahnsen/CostSensitiveClassification
costcla/utils/cross_validation.py
check_cv
def check_cv(cv, X=None, y=None, classifier=False): """Input checker utility for building a CV in a user friendly way. Parameters ---------- cv : int, a cv generator instance, or None The input specifying which cv generator to use. It can be an integer, in which case it is the number of...
python
def check_cv(cv, X=None, y=None, classifier=False): """Input checker utility for building a CV in a user friendly way. Parameters ---------- cv : int, a cv generator instance, or None The input specifying which cv generator to use. It can be an integer, in which case it is the number of...
[ "def", "check_cv", "(", "cv", ",", "X", "=", "None", ",", "y", "=", "None", ",", "classifier", "=", "False", ")", ":", "return", "_check_cv", "(", "cv", ",", "X", "=", "X", ",", "y", "=", "y", ",", "classifier", "=", "classifier", ",", "warn_mask...
Input checker utility for building a CV in a user friendly way. Parameters ---------- cv : int, a cv generator instance, or None The input specifying which cv generator to use. It can be an integer, in which case it is the number of folds in a KFold, None, in which case 3 fold is us...
[ "Input", "checker", "utility", "for", "building", "a", "CV", "in", "a", "user", "friendly", "way", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/utils/cross_validation.py#L1323-L1350
albahnsen/CostSensitiveClassification
costcla/sampling/_smote.py
_SMOTE
def _SMOTE(T, N, k, h = 1.0): """ Returns (N/100) * n_minority_samples synthetic minority samples. Parameters ---------- T : array-like, shape = [n_minority_samples, n_features] Holds the minority samples N : percetange of new synthetic samples: n_synthetic_samples = N/100 * n_m...
python
def _SMOTE(T, N, k, h = 1.0): """ Returns (N/100) * n_minority_samples synthetic minority samples. Parameters ---------- T : array-like, shape = [n_minority_samples, n_features] Holds the minority samples N : percetange of new synthetic samples: n_synthetic_samples = N/100 * n_m...
[ "def", "_SMOTE", "(", "T", ",", "N", ",", "k", ",", "h", "=", "1.0", ")", ":", "n_minority_samples", ",", "n_features", "=", "T", ".", "shape", "if", "N", "<", "100", ":", "#create synthetic samples only for a subset of T.", "#TODO: select random minortiy sample...
Returns (N/100) * n_minority_samples synthetic minority samples. Parameters ---------- T : array-like, shape = [n_minority_samples, n_features] Holds the minority samples N : percetange of new synthetic samples: n_synthetic_samples = N/100 * n_minority_samples. Can be < 100. k : int...
[ "Returns", "(", "N", "/", "100", ")", "*", "n_minority_samples", "synthetic", "minority", "samples", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/_smote.py#L40-L89
albahnsen/CostSensitiveClassification
costcla/sampling/_smote.py
_borderlineSMOTE
def _borderlineSMOTE(X, y, minority_target, N, k): """ Returns synthetic minority samples. Parameters ---------- X : array-like, shape = [n__samples, n_features] Holds the minority and majority samples y : array-like, shape = [n__samples] Holds the class targets for samples ...
python
def _borderlineSMOTE(X, y, minority_target, N, k): """ Returns synthetic minority samples. Parameters ---------- X : array-like, shape = [n__samples, n_features] Holds the minority and majority samples y : array-like, shape = [n__samples] Holds the class targets for samples ...
[ "def", "_borderlineSMOTE", "(", "X", ",", "y", ",", "minority_target", ",", "N", ",", "k", ")", ":", "n_samples", ",", "_", "=", "X", ".", "shape", "#Learn nearest neighbours on complete training set", "neigh", "=", "NearestNeighbors", "(", "n_neighbors", "=", ...
Returns synthetic minority samples. Parameters ---------- X : array-like, shape = [n__samples, n_features] Holds the minority and majority samples y : array-like, shape = [n__samples] Holds the class targets for samples minority_target : value for minority class N : percetange o...
[ "Returns", "synthetic", "minority", "samples", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/_smote.py#L91-L147
albahnsen/CostSensitiveClassification
costcla/metrics/__init__.py
binary_classification_metrics
def binary_classification_metrics(y_true, y_pred, y_prob): #TODO: update description """classification_metrics. This function cal... Parameters ---------- y_true : array-like Ground truth (correct) labels. y_pred : array-like Predicted labels, as returned by a classifier. ...
python
def binary_classification_metrics(y_true, y_pred, y_prob): #TODO: update description """classification_metrics. This function cal... Parameters ---------- y_true : array-like Ground truth (correct) labels. y_pred : array-like Predicted labels, as returned by a classifier. ...
[ "def", "binary_classification_metrics", "(", "y_true", ",", "y_pred", ",", "y_prob", ")", ":", "#TODO: update description", "y_true", "=", "column_or_1d", "(", "y_true", ")", "y_pred", "=", "column_or_1d", "(", "y_pred", ")", "y_prob", "=", "column_or_1d", "(", ...
classification_metrics. This function cal... Parameters ---------- y_true : array-like Ground truth (correct) labels. y_pred : array-like Predicted labels, as returned by a classifier. y_prob : array-like Predicted probabilities, as returned by a classifier. Retu...
[ "classification_metrics", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/metrics/__init__.py#L22-L92
albahnsen/CostSensitiveClassification
costcla/models/directcost.py
BayesMinimumRiskClassifier.fit
def fit(self,y_true_cal=None, y_prob_cal=None): """ If calibration, then train the calibration of probabilities Parameters ---------- y_true_cal : array-like of shape = [n_samples], optional default = None True class to be used for calibrating the probabilities y_pr...
python
def fit(self,y_true_cal=None, y_prob_cal=None): """ If calibration, then train the calibration of probabilities Parameters ---------- y_true_cal : array-like of shape = [n_samples], optional default = None True class to be used for calibrating the probabilities y_pr...
[ "def", "fit", "(", "self", ",", "y_true_cal", "=", "None", ",", "y_prob_cal", "=", "None", ")", ":", "if", "self", ".", "calibration", ":", "self", ".", "cal", "=", "ROCConvexHull", "(", ")", "self", ".", "cal", ".", "fit", "(", "y_true_cal", ",", ...
If calibration, then train the calibration of probabilities Parameters ---------- y_true_cal : array-like of shape = [n_samples], optional default = None True class to be used for calibrating the probabilities y_prob_cal : array-like of shape = [n_samples, 2], optional defa...
[ "If", "calibration", "then", "train", "the", "calibration", "of", "probabilities" ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L56-L74
albahnsen/CostSensitiveClassification
costcla/models/directcost.py
BayesMinimumRiskClassifier.predict
def predict(self, y_prob, cost_mat): """ Calculate the prediction using the Bayes minimum risk classifier. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of shape = [n_samples, 4] Cost m...
python
def predict(self, y_prob, cost_mat): """ Calculate the prediction using the Bayes minimum risk classifier. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of shape = [n_samples, 4] Cost m...
[ "def", "predict", "(", "self", ",", "y_prob", ",", "cost_mat", ")", ":", "if", "self", ".", "calibration", ":", "y_prob", "[", ":", ",", "1", "]", "=", "self", ".", "cal", ".", "predict_proba", "(", "y_prob", "[", ":", ",", "1", "]", ")", "y_prob...
Calculate the prediction using the Bayes minimum risk classifier. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classification problem W...
[ "Calculate", "the", "prediction", "using", "the", "Bayes", "minimum", "risk", "classifier", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L76-L105
albahnsen/CostSensitiveClassification
costcla/models/directcost.py
BayesMinimumRiskClassifier.fit_predict
def fit_predict(self, y_prob, cost_mat, y_true_cal=None, y_prob_cal=None): """ Calculate the prediction using the Bayes minimum risk classifier. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of sha...
python
def fit_predict(self, y_prob, cost_mat, y_true_cal=None, y_prob_cal=None): """ Calculate the prediction using the Bayes minimum risk classifier. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of sha...
[ "def", "fit_predict", "(", "self", ",", "y_prob", ",", "cost_mat", ",", "y_true_cal", "=", "None", ",", "y_prob_cal", "=", "None", ")", ":", "#TODO: Check input", "if", "self", ".", "calibration", ":", "self", ".", "cal", "=", "ROCConvexHull", "(", ")", ...
Calculate the prediction using the Bayes minimum risk classifier. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classification problem W...
[ "Calculate", "the", "prediction", "using", "the", "Bayes", "minimum", "risk", "classifier", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L107-L150
albahnsen/CostSensitiveClassification
costcla/models/directcost.py
ThresholdingOptimization.fit
def fit(self, y_prob, cost_mat, y_true): """ Calculate the optimal threshold using the ThresholdingOptimization. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of shape = [n_samples, 4] ...
python
def fit(self, y_prob, cost_mat, y_true): """ Calculate the optimal threshold using the ThresholdingOptimization. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of shape = [n_samples, 4] ...
[ "def", "fit", "(", "self", ",", "y_prob", ",", "cost_mat", ",", "y_true", ")", ":", "#TODO: Check input", "if", "self", ".", "calibration", ":", "cal", "=", "ROCConvexHull", "(", ")", "cal", ".", "fit", "(", "y_true", ",", "y_prob", "[", ":", ",", "1...
Calculate the optimal threshold using the ThresholdingOptimization. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classification problem ...
[ "Calculate", "the", "optimal", "threshold", "using", "the", "ThresholdingOptimization", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L199-L238
albahnsen/CostSensitiveClassification
costcla/models/directcost.py
ThresholdingOptimization.predict
def predict(self, y_prob): """ Calculate the prediction using the ThresholdingOptimization. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. Returns ------- y_pred : array-like of shape = [n_samples] ...
python
def predict(self, y_prob): """ Calculate the prediction using the ThresholdingOptimization. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. Returns ------- y_pred : array-like of shape = [n_samples] ...
[ "def", "predict", "(", "self", ",", "y_prob", ")", ":", "y_pred", "=", "np", ".", "floor", "(", "y_prob", "[", ":", ",", "1", "]", "+", "(", "1", "-", "self", ".", "threshold_", ")", ")", "return", "y_pred" ]
Calculate the prediction using the ThresholdingOptimization. Parameters ---------- y_prob : array-like of shape = [n_samples, 2] Predicted probabilities. Returns ------- y_pred : array-like of shape = [n_samples] Predicted class
[ "Calculate", "the", "prediction", "using", "the", "ThresholdingOptimization", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/directcost.py#L240-L255
albahnsen/CostSensitiveClassification
costcla/sampling/sampling.py
undersampling
def undersampling(X, y, cost_mat=None, per=0.5): """Under-sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shap...
python
def undersampling(X, y, cost_mat=None, per=0.5): """Under-sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shap...
[ "def", "undersampling", "(", "X", ",", "y", ",", "cost_mat", "=", "None", ",", "per", "=", "0.5", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "#TODO: allow y different from (0, 1)", "num_y1", "=", "y", ".", "sum", "(", ")", "num_y0", ...
Under-sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4], optional (default=None) ...
[ "Under", "-", "sampling", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/sampling.py#L11-L57
albahnsen/CostSensitiveClassification
costcla/sampling/sampling.py
smote
def smote(X, y, cost_mat=None, per=0.5): """SMOTE: synthetic minority over-sampling technique Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cos...
python
def smote(X, y, cost_mat=None, per=0.5): """SMOTE: synthetic minority over-sampling technique Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cos...
[ "def", "smote", "(", "X", ",", "y", ",", "cost_mat", "=", "None", ",", "per", "=", "0.5", ")", ":", "#TODO: Add random state", "#TODO: Check input", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "#TODO: allow y different from (0, 1)", "num_y1", "=", "y...
SMOTE: synthetic minority over-sampling technique Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4], op...
[ "SMOTE", ":", "synthetic", "minority", "over", "-", "sampling", "technique" ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/sampling/sampling.py#L60-L128
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier._node_cost
def _node_cost(self, y_true, cost_mat): """ Private function to calculate the cost of a node. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classifi...
python
def _node_cost(self, y_true, cost_mat): """ Private function to calculate the cost of a node. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classifi...
[ "def", "_node_cost", "(", "self", ",", "y_true", ",", "cost_mat", ")", ":", "n_samples", "=", "len", "(", "y_true", ")", "# Evaluates the cost by predicting the node as positive and negative", "costs", "=", "np", ".", "zeros", "(", "2", ")", "costs", "[", "0", ...
Private function to calculate the cost of a node. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] Cost matrix of the classification problem Where the columns represe...
[ "Private", "function", "to", "calculate", "the", "cost", "of", "a", "node", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L138-L183
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier._calculate_gain
def _calculate_gain(self, cost_base, y_true, X, cost_mat, split): """ Private function to calculate the gain in cost of using split in the current node. Parameters ---------- cost_base : float Cost of the naive prediction y_true : array indicator matrix ...
python
def _calculate_gain(self, cost_base, y_true, X, cost_mat, split): """ Private function to calculate the gain in cost of using split in the current node. Parameters ---------- cost_base : float Cost of the naive prediction y_true : array indicator matrix ...
[ "def", "_calculate_gain", "(", "self", ",", "cost_base", ",", "y_true", ",", "X", ",", "cost_mat", ",", "split", ")", ":", "# Check if cost_base == 0, then no gain is possible", "#TODO: This must be check in _best_split", "if", "cost_base", "==", "0.0", ":", "return", ...
Private function to calculate the gain in cost of using split in the current node. Parameters ---------- cost_base : float Cost of the naive prediction y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_...
[ "Private", "function", "to", "calculate", "the", "gain", "in", "cost", "of", "using", "split", "in", "the", "current", "node", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L185-L242
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier._best_split
def _best_split(self, y_true, X, cost_mat): """ Private function to calculate the split that gives the best gain. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samples, n_features] The i...
python
def _best_split(self, y_true, X, cost_mat): """ Private function to calculate the split that gives the best gain. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samples, n_features] The i...
[ "def", "_best_split", "(", "self", ",", "y_true", ",", "X", ",", "cost_mat", ")", ":", "n_samples", ",", "n_features", "=", "X", ".", "shape", "num_pct", "=", "self", ".", "num_pct", "cost_base", ",", "y_pred", ",", "y_prob", "=", "self", ".", "_node_c...
Private function to calculate the split that gives the best gain. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samples, n_features] The input samples. cost_mat : array-like of shape = ...
[ "Private", "function", "to", "calculate", "the", "split", "that", "gives", "the", "best", "gain", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L244-L302
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier._tree_grow
def _tree_grow(self, y_true, X, cost_mat, level=0): """ Private recursive function to grow the decision tree. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samples, n_features] The input...
python
def _tree_grow(self, y_true, X, cost_mat, level=0): """ Private recursive function to grow the decision tree. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samples, n_features] The input...
[ "def", "_tree_grow", "(", "self", ",", "y_true", ",", "X", ",", "cost_mat", ",", "level", "=", "0", ")", ":", "#TODO: Find error, add min_samples_split", "if", "len", "(", "X", ".", "shape", ")", "==", "1", ":", "tree", "=", "dict", "(", "y_pred", "=",...
Private recursive function to grow the decision tree. Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samples, n_features] The input samples. cost_mat : array-like of shape = [n_samples, ...
[ "Private", "recursive", "function", "to", "grow", "the", "decision", "tree", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L304-L369
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier.fit
def fit(self, X, y, cost_mat, check_input=False): """ Build a example-dependent cost-sensitive decision tree from the training set (X, y, cost_mat) Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samp...
python
def fit(self, X, y, cost_mat, check_input=False): """ Build a example-dependent cost-sensitive decision tree from the training set (X, y, cost_mat) Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samp...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "cost_mat", ",", "check_input", "=", "False", ")", ":", "#TODO: Check input", "#TODO: Add random state", "n_samples", ",", "self", ".", "n_features_", "=", "X", ".", "shape", "self", ".", "tree_", "=", ...
Build a example-dependent cost-sensitive decision tree from the training set (X, y, cost_mat) Parameters ---------- y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_samples, n_features] The input samples. cost_...
[ "Build", "a", "example", "-", "dependent", "cost", "-", "sensitive", "decision", "tree", "from", "the", "training", "set", "(", "X", "y", "cost_mat", ")" ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L379-L442
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier._nodes
def _nodes(self, tree): """ Private function that find the number of nodes in a tree. Parameters ---------- tree : object Returns ------- nodes : array like of shape [n_nodes] """ def recourse(temp_tree_, nodes): if isinstance(temp_tr...
python
def _nodes(self, tree): """ Private function that find the number of nodes in a tree. Parameters ---------- tree : object Returns ------- nodes : array like of shape [n_nodes] """ def recourse(temp_tree_, nodes): if isinstance(temp_tr...
[ "def", "_nodes", "(", "self", ",", "tree", ")", ":", "def", "recourse", "(", "temp_tree_", ",", "nodes", ")", ":", "if", "isinstance", "(", "temp_tree_", ",", "dict", ")", ":", "if", "temp_tree_", "[", "'split'", "]", "!=", "-", "1", ":", "nodes", ...
Private function that find the number of nodes in a tree. Parameters ---------- tree : object Returns ------- nodes : array like of shape [n_nodes]
[ "Private", "function", "that", "find", "the", "number", "of", "nodes", "in", "a", "tree", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L444-L466
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier._classify
def _classify(self, X, tree, proba=False): """ Private function that classify a dataset using tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. tree : object proba : bool, optional (default=False) ...
python
def _classify(self, X, tree, proba=False): """ Private function that classify a dataset using tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. tree : object proba : bool, optional (default=False) ...
[ "def", "_classify", "(", "self", ",", "X", ",", "tree", ",", "proba", "=", "False", ")", ":", "n_samples", ",", "n_features", "=", "X", ".", "shape", "predicted", "=", "np", ".", "ones", "(", "n_samples", ")", "# Check if final node", "if", "tree", "["...
Private function that classify a dataset using tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. tree : object proba : bool, optional (default=False) If True then return probabilities else return class ...
[ "Private", "function", "that", "classify", "a", "dataset", "using", "tree", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L468-L513
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier.predict
def predict(self, X): """ Predict class of X. The predicted class for each sample in X is returned. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- y : array of shape = [n_samples] ...
python
def predict(self, X): """ Predict class of X. The predicted class for each sample in X is returned. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- y : array of shape = [n_samples] ...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "#TODO: Check consistency of X", "if", "self", ".", "pruned", ":", "tree_", "=", "self", ".", "tree_", ".", "tree_pruned", "else", ":", "tree_", "=", "self", ".", "tree_", ".", "tree", "return", "self", ...
Predict class of X. The predicted class for each sample in X is returned. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- y : array of shape = [n_samples] The predicted classes,
[ "Predict", "class", "of", "X", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L515-L537
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier.predict_proba
def predict_proba(self, X): """Predict class probabilities of the input samples X. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- prob : array of shape = [n_samples, 2] The class...
python
def predict_proba(self, X): """Predict class probabilities of the input samples X. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- prob : array of shape = [n_samples, 2] The class...
[ "def", "predict_proba", "(", "self", ",", "X", ")", ":", "#TODO: Check consistency of X", "n_samples", ",", "n_features", "=", "X", ".", "shape", "prob", "=", "np", ".", "zeros", "(", "(", "n_samples", ",", "2", ")", ")", "if", "self", ".", "pruned", "...
Predict class probabilities of the input samples X. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- prob : array of shape = [n_samples, 2] The class probabilities of the input samples.
[ "Predict", "class", "probabilities", "of", "the", "input", "samples", "X", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L539-L564
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier._delete_node
def _delete_node(self, tree, node): """ Private function that eliminate node from tree. Parameters ---------- tree : object node : int node to be eliminated from tree Returns ------- pruned_tree : object """ # Calculate gai...
python
def _delete_node(self, tree, node): """ Private function that eliminate node from tree. Parameters ---------- tree : object node : int node to be eliminated from tree Returns ------- pruned_tree : object """ # Calculate gai...
[ "def", "_delete_node", "(", "self", ",", "tree", ",", "node", ")", ":", "# Calculate gains", "temp_tree", "=", "copy", ".", "deepcopy", "(", "tree", ")", "def", "recourse", "(", "temp_tree_", ",", "del_node", ")", ":", "if", "isinstance", "(", "temp_tree_"...
Private function that eliminate node from tree. Parameters ---------- tree : object node : int node to be eliminated from tree Returns ------- pruned_tree : object
[ "Private", "function", "that", "eliminate", "node", "from", "tree", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L566-L599
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier._pruning
def _pruning(self, X, y_true, cost_mat): """ Private function that prune the decision tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y_true : array indicator matrix Ground truth (correct) labels. ...
python
def _pruning(self, X, y_true, cost_mat): """ Private function that prune the decision tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y_true : array indicator matrix Ground truth (correct) labels. ...
[ "def", "_pruning", "(", "self", ",", "X", ",", "y_true", ",", "cost_mat", ")", ":", "# Calculate gains", "nodes", "=", "self", ".", "_nodes", "(", "self", ".", "tree_", ".", "tree_pruned", ")", "n_nodes", "=", "len", "(", "nodes", ")", "gains", "=", ...
Private function that prune the decision tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y_true : array indicator matrix Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] ...
[ "Private", "function", "that", "prune", "the", "decision", "tree", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L601-L652
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
CostSensitiveDecisionTreeClassifier.pruning
def pruning(self, X, y, cost_mat): """ Function that prune the decision tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y_true : array indicator matrix Ground truth (correct) labels. cost_mat : a...
python
def pruning(self, X, y, cost_mat): """ Function that prune the decision tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y_true : array indicator matrix Ground truth (correct) labels. cost_mat : a...
[ "def", "pruning", "(", "self", ",", "X", ",", "y", ",", "cost_mat", ")", ":", "self", ".", "tree_", ".", "tree_pruned", "=", "copy", ".", "deepcopy", "(", "self", ".", "tree_", ".", "tree", ")", "if", "self", ".", "tree_", ".", "n_nodes", ">", "0...
Function that prune the decision tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y_true : array indicator matrix Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] ...
[ "Function", "that", "prune", "the", "decision", "tree", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L654-L676
albahnsen/CostSensitiveClassification
costcla/metrics/costs.py
cost_loss
def cost_loss(y_true, y_pred, cost_mat): #TODO: update description """Cost classification loss. This function calculates the cost of using y_pred on y_true with cost-matrix cost-mat. It differ from traditional classification evaluation measures since measures such as accuracy asing the same cost to...
python
def cost_loss(y_true, y_pred, cost_mat): #TODO: update description """Cost classification loss. This function calculates the cost of using y_pred on y_true with cost-matrix cost-mat. It differ from traditional classification evaluation measures since measures such as accuracy asing the same cost to...
[ "def", "cost_loss", "(", "y_true", ",", "y_pred", ",", "cost_mat", ")", ":", "#TODO: update description", "#TODO: Check consistency of cost_mat", "y_true", "=", "column_or_1d", "(", "y_true", ")", "y_true", "=", "(", "y_true", "==", "1", ")", ".", "astype", "(",...
Cost classification loss. This function calculates the cost of using y_pred on y_true with cost-matrix cost-mat. It differ from traditional classification evaluation measures since measures such as accuracy asing the same cost to different errors, but that is not the real case in several real-world cla...
[ "Cost", "classification", "loss", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/metrics/costs.py#L19-L81
albahnsen/CostSensitiveClassification
costcla/metrics/costs.py
savings_score
def savings_score(y_true, y_pred, cost_mat): #TODO: update description """Savings score. This function calculates the savings cost of using y_pred on y_true with cost-matrix cost-mat, as the difference of y_pred and the cost_loss of a naive classification model. Parameters ---------- y...
python
def savings_score(y_true, y_pred, cost_mat): #TODO: update description """Savings score. This function calculates the savings cost of using y_pred on y_true with cost-matrix cost-mat, as the difference of y_pred and the cost_loss of a naive classification model. Parameters ---------- y...
[ "def", "savings_score", "(", "y_true", ",", "y_pred", ",", "cost_mat", ")", ":", "#TODO: update description", "#TODO: Check consistency of cost_mat", "y_true", "=", "column_or_1d", "(", "y_true", ")", "y_pred", "=", "column_or_1d", "(", "y_pred", ")", "n_samples", "...
Savings score. This function calculates the savings cost of using y_pred on y_true with cost-matrix cost-mat, as the difference of y_pred and the cost_loss of a naive classification model. Parameters ---------- y_true : array-like or label indicator matrix Ground truth (correct) labels...
[ "Savings", "score", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/metrics/costs.py#L84-L143
albahnsen/CostSensitiveClassification
costcla/metrics/costs.py
brier_score_loss
def brier_score_loss(y_true, y_prob): """Compute the Brier score The smaller the Brier score, the better, hence the naming with "loss". Across all items in a set N predictions, the Brier score measures the mean squared difference between (1) the predicted probability assigned to the possible outco...
python
def brier_score_loss(y_true, y_prob): """Compute the Brier score The smaller the Brier score, the better, hence the naming with "loss". Across all items in a set N predictions, the Brier score measures the mean squared difference between (1) the predicted probability assigned to the possible outco...
[ "def", "brier_score_loss", "(", "y_true", ",", "y_prob", ")", ":", "y_true", "=", "column_or_1d", "(", "y_true", ")", "y_prob", "=", "column_or_1d", "(", "y_prob", ")", "return", "np", ".", "mean", "(", "(", "y_true", "-", "y_prob", ")", "**", "2", ")"...
Compute the Brier score The smaller the Brier score, the better, hence the naming with "loss". Across all items in a set N predictions, the Brier score measures the mean squared difference between (1) the predicted probability assigned to the possible outcomes for item i, and (2) the actual outcome. ...
[ "Compute", "the", "Brier", "score" ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/metrics/costs.py#L149-L200
albahnsen/CostSensitiveClassification
costcla/models/regression.py
_intercept_dot
def _intercept_dot(w, X): """Computes y * np.dot(X, w). It takes into consideration if the intercept should be fit or not. Parameters ---------- w : ndarray, shape (n_features,) or (n_features + 1,) Coefficient vector. X : {array-like, sparse matrix}, shape (n_samples, n_features) ...
python
def _intercept_dot(w, X): """Computes y * np.dot(X, w). It takes into consideration if the intercept should be fit or not. Parameters ---------- w : ndarray, shape (n_features,) or (n_features + 1,) Coefficient vector. X : {array-like, sparse matrix}, shape (n_samples, n_features) ...
[ "def", "_intercept_dot", "(", "w", ",", "X", ")", ":", "c", "=", "0.", "if", "w", ".", "size", "==", "X", ".", "shape", "[", "1", "]", "+", "1", ":", "c", "=", "w", "[", "-", "1", "]", "w", "=", "w", "[", ":", "-", "1", "]", "z", "=",...
Computes y * np.dot(X, w). It takes into consideration if the intercept should be fit or not. Parameters ---------- w : ndarray, shape (n_features,) or (n_features + 1,) Coefficient vector. X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data.
[ "Computes", "y", "*", "np", ".", "dot", "(", "X", "w", ")", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/regression.py#L20-L40
albahnsen/CostSensitiveClassification
costcla/models/regression.py
_logistic_cost_loss
def _logistic_cost_loss(w, X, y, cost_mat, alpha): """Computes the logistic loss. Parameters ---------- w : array-like, shape (n_w, n_features,) or (n_w, n_features + 1,) Coefficient vector or matrix of coefficient. X : array-like, shape (n_samples, n_features) Training data. ...
python
def _logistic_cost_loss(w, X, y, cost_mat, alpha): """Computes the logistic loss. Parameters ---------- w : array-like, shape (n_w, n_features,) or (n_w, n_features + 1,) Coefficient vector or matrix of coefficient. X : array-like, shape (n_samples, n_features) Training data. ...
[ "def", "_logistic_cost_loss", "(", "w", ",", "X", ",", "y", ",", "cost_mat", ",", "alpha", ")", ":", "if", "w", ".", "shape", "[", "0", "]", "==", "w", ".", "size", ":", "# Only evaluating one w", "return", "_logistic_cost_loss_i", "(", "w", ",", "X", ...
Computes the logistic loss. Parameters ---------- w : array-like, shape (n_w, n_features,) or (n_w, n_features + 1,) Coefficient vector or matrix of coefficient. X : array-like, shape (n_samples, n_features) Training data. y : ndarray, shape (n_samples,) Array of labels. ...
[ "Computes", "the", "logistic", "loss", "." ]
train
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/regression.py#L58-L98