Search is not available for this dataset
text stringlengths 75 104k |
|---|
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 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 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 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 _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 _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 _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 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 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_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 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 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 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 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 _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 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 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 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 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 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 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_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_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 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 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_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 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 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 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_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 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 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 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 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_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 _one_contains_other(s1, s2):
"""
Whether one set contains the other
"""
return min(len(s1), len(s2)) == len(s1 & s2) |
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 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 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 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 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 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 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_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 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 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_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 _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 _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_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(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 _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 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_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_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 _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 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_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 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 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_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_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_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 _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 _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 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 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 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 _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 _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 _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 _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 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 _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 _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 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 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 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 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(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 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 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 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 _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 _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 _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 _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 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 _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 _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 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_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 _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 _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, 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 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 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 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 _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 _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.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.