code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if msg is None: msg = ("This %(name)s instance is not fitted yet. Call 'fit' with " "appropriate arguments before using this method.") if not hasattr(estimator, 'fit'): raise TypeError("%s is not an estimator instance." % (estimator)) if not isinstance(attributes, (list...
def check_is_fitted(estimator, attributes, msg=None, all_or_any=all)
Perform is_fitted validation for estimator. Checks if the estimator is fitted by verifying the presence of "all_or_any" of the passed attributes and raises a NotFittedError with the given message. Parameters ---------- estimator : estimator instance. estimator instance for which the chec...
1.61315
1.764779
0.914081
if issparse(a) or issparse(b): ret = a * b if dense_output and hasattr(ret, "toarray"): ret = ret.toarray() return ret else: return np.dot(a, b)
def safe_sparse_dot(a, b, dense_output=False)
Dot product that handle the sparse matrix case correctly Uses BLAS GEMM as replacement for numpy.dot where possible to avoid unnecessary copies. Parameters ---------- a : array or sparse matrix b : array or sparse matrix dense_output : boolean, default False When False, either ``a``...
2.347307
2.978354
0.788122
check_is_fitted(self, "classes_") X = check_array(X, accept_sparse='csr') X_bin = self._transform_data(X) n_classes, n_features = self.feature_log_prob_.shape n_samples, n_features_X = X_bin.shape if n_features_X != n_features: raise ValueError( ...
def _joint_log_likelihood(self, X)
Calculate the posterior log probability of the samples X
3.3223
3.322658
0.999892
jll = self._joint_log_likelihood(X) return self.classes_[np.argmax(jll, axis=1)]
def predict(self, X)
Perform classification on an array of test vectors X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = [n_samples] Predicted target values for X
5.175931
7.980291
0.648589
jll = self._joint_log_likelihood(X) # normalize by P(x) = P(f_1, ..., f_n) log_prob_x = logsumexp(jll, axis=1) # return shape = (2,) return jll - np.atleast_2d(log_prob_x).T
def predict_log_proba(self, X)
Return log-probability estimates for the test vector X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array-like, shape = [n_samples, n_classes] Returns the log-probability of the samples for each class in ...
4.892324
6.402531
0.764124
if self.binarize is not None: X = binarize(X, threshold=self.binarize) for i in range(X.shape[1]): # initialise binarizer and save binarizer = LabelBinarizer() # fit the data to the binarizer binarizer.fit(X[:, i]) self...
def _fit_data(self, X)
Binarize the data for each column separately. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- X_transformed : array-like Returns the data where in each columns the labels are binarized.
3.355282
3.309823
1.013735
if self._binarizers == []: raise NotFittedError() if self.binarize is not None: X = binarize(X, threshold=self.binarize) if len(self._binarizers) != X.shape[1]: raise ValueError( "Expected input with %d features, got %d instead" % ...
def _transform_data(self, X)
Binarize the data for each column separately.
2.830775
2.686101
1.05386
self.feature_count_ += safe_sparse_dot(Y.T, X) self.class_count_ += Y.sum(axis=0)
def _count(self, X, Y)
Count and smooth feature occurrences.
5.343689
4.534741
1.178389
smoothed_fc = self.feature_count_ + alpha smoothed_cc = self.class_count_ + alpha * 2 self.feature_log_prob_ = (np.log(smoothed_fc) - np.log(smoothed_cc.reshape(-1, 1)))
def _update_feature_log_prob(self, alpha)
Apply smoothing to raw counts and recompute log probabilities
3.801997
3.238249
1.174091
X, y = check_X_y(X, y, 'csr') # Transform data with a label binarizer. Each column will get # transformed into a N columns (for each distinct value a column). For # a situation with 0 and 1 outcome values, the result given two # columns. X_bin = self._fit_data(X...
def fit(self, X, y, sample_weight=None)
Fit Naive Bayes classifier according to X, y Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape = [n_sam...
4.235739
4.51453
0.938246
_, n_features = X_bin.shape # The parameter class_log_prior_ has shape (2,). The values represent # 'match' and 'non-match'. rand_vals = np.random.rand(2) class_prior = rand_vals / np.sum(rand_vals) # make empty array of feature log probs # dimensions ...
def _init_parameters_random(self, X_bin)
Initialise parameters for unsupervised learning.
2.933282
2.832074
1.035736
_, n_features = X_bin.shape class_prior = [.9, .1] feature_prob = np.zeros((2, n_features)) for i, bin in enumerate(self._binarizers): if bin.classes_.shape[0] != 2: raise ValueError("Only binary labels are allowed for " ...
def _init_parameters_jaro(self, X_bin)
Initialise parameters for unsupervised learning.
3.926342
3.864623
1.01597
X = check_array(X, accept_sparse='csr') # count frequencies of elements in vector space # based on https://stackoverflow.com/a/33235665 # faster than numpy.unique X_unique, X_freq = np.unique(X, axis=0, return_counts=True) X_freq = np.atleast_2d(X_freq) ...
def fit(self, X)
Fit ECM classifier according to X Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ------- self : o...
2.682482
2.753159
0.974329
concat_arrays = numpy.concatenate([array1, array2]) unique_values = numpy.unique(concat_arrays) return numpy.sort(unique_values)
def _get_sorting_key_values(self, array1, array2)
return the sorting key values as a series
3.688311
3.716073
0.992529
try: import networkx as nx except ImportError(): raise Exception("'networkx' module is needed for this operation") G = nx.Graph() G.add_edges_from(links.values) connected_components = nx.connected_component_subgraphs(G) links_result = [...
def compute(self, links)
Return the connected components. Parameters ---------- links : pandas.MultiIndex The links to apply one-to-one matching on. Returns ------- list of pandas.MultiIndex A list with pandas.MultiIndex objects. Each MultiIndex object repres...
3.726181
2.861037
1.302388
# compute the probabilities probs = self.kernel.predict_proba(features) # get the position of match probabilities classes = list(self.kernel.classes_) match_class_position = classes.index(1) return probs[:, match_class_position]
def _prob_match(self, features)
Compute match probabilities. Parameters ---------- features : numpy.ndarray The data to train the model on. Returns ------- numpy.ndarray The match probabilties.
5.287089
5.294407
0.998618
from sklearn.exceptions import NotFittedError try: prediction = self.kernel.predict_classes(features)[:, 0] except NotFittedError: raise NotFittedError( "{} is not fitted yet. Call 'fit' with appropriate " "arguments before using...
def _predict(self, features)
Predict matches and non-matches. Parameters ---------- features : numpy.ndarray The data to predict the class of. Returns ------- numpy.ndarray The predicted classes.
2.929927
2.902962
1.009289
index = df.index.to_series() keys = index.str.extract(r'rec-(\d+)', expand=True)[0] index_int = numpy.arange(len(df)) df_helper = pandas.DataFrame({ 'key': keys, 'index': index_int }) # merge the two frame and make MultiIndex. pairs_df = df_helper.merge( df_h...
def _febrl_links(df)
Get the links of a FEBRL dataset.
3.462474
3.353767
1.032413
df = _febrl_load_data('dataset1.csv') if return_links: links = _febrl_links(df) return df, links else: return df
def load_febrl1(return_links=False)
Load the FEBRL 1 dataset. The Freely Extensible Biomedical Record Linkage (Febrl) package is distributed with a dataset generator and four datasets generated with the generator. This function returns the first Febrl dataset as a :class:`pandas.DataFrame`. *"This data set contains 1000 reco...
3.420375
3.719585
0.919558
df = _febrl_load_data('dataset2.csv') if return_links: links = _febrl_links(df) return df, links else: return df
def load_febrl2(return_links=False)
Load the FEBRL 2 dataset. The Freely Extensible Biomedical Record Linkage (Febrl) package is distributed with a dataset generator and four datasets generated with the generator. This function returns the second Febrl dataset as a :class:`pandas.DataFrame`. *"This data set contains 5000 rec...
3.502085
3.759706
0.931479
df = _febrl_load_data('dataset3.csv') if return_links: links = _febrl_links(df) return df, links else: return df
def load_febrl3(return_links=False)
Load the FEBRL 3 dataset. The Freely Extensible Biomedical Record Linkage (Febrl) package is distributed with a dataset generator and four datasets generated with the generator. This function returns the third Febrl dataset as a :class:`pandas.DataFrame`. *"This data set contains 5000 reco...
3.459276
3.797715
0.910884
df_a = _febrl_load_data('dataset4a.csv') df_b = _febrl_load_data('dataset4b.csv') if return_links: links = pandas.MultiIndex.from_arrays([ ["rec-{}-org".format(i) for i in range(0, 5000)], ["rec-{}-dup-0".format(i) for i in range(0, 5000)]] ) return df_...
def load_febrl4(return_links=False)
Load the FEBRL 4 datasets. The Freely Extensible Biomedical Record Linkage (Febrl) package is distributed with a dataset generator and four datasets generated with the generator. This function returns the fourth Febrl dataset as a :class:`pandas.DataFrame`. *"Generated as one data set with...
3.108817
2.606197
1.192856
# If the data is not found, download it. for i in range(1, 11): filepath = os.path.join(os.path.dirname(__file__), 'krebsregister', 'block_{}.zip'.format(i)) if not os.path.exists(filepath): _download_krebsregister() break if i...
def load_krebsregister(block=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], missing_values=None, shuffle=True)
Load the Krebsregister dataset. This dataset of comparison patterns was obtained in a epidemiological cancer study in Germany. The comparison patterns were created by the Institute for Medical Biostatistics, Epidemiology and Informatics (IMBEI) and the University Medical Center of Johannes Gutenber...
2.808951
2.758921
1.018134
# encoding if sys.version_info[0] == 2: s = s.apply( lambda x: x.decode(encoding, decode_error) if type(x) == bytes else x) if concat: s = s.str.replace(r"[\-\_\s]", "") for alg in _phonetic_algorithms: if method in alg['argument_names']: ...
def phonetic(s, method, concat=True, encoding='utf-8', decode_error='strict')
Convert names or strings into phonetic codes. The implemented algorithms are `soundex <https://en.wikipedia.org/wiki/Soundex>`_, `nysiis <https://en.wikipedia.org/wiki/New_York_State_Identification_and_ Intelligence_System>`_, `metaphone <https://en.wikipedia.org/wiki/Metaphone>`_ or `match_rating...
3.830379
3.630778
1.054975
indexer = Block(*args, **kwargs) self.add(indexer) return self
def block(self, *args, **kwargs)
Add a block index. Shortcut of :class:`recordlinkage.index.Block`:: from recordlinkage.index import Block indexer = recordlinkage.Index() indexer.add(Block())
13.941863
10.99478
1.268044
indexer = SortedNeighbourhood(*args, **kwargs) self.add(indexer) return self
def sortedneighbourhood(self, *args, **kwargs)
Add a Sorted Neighbourhood Index. Shortcut of :class:`recordlinkage.index.SortedNeighbourhood`:: from recordlinkage.index import SortedNeighbourhood indexer = recordlinkage.Index() indexer.add(SortedNeighbourhood())
8.51985
7.518176
1.133234
indexer = Random() self.add(indexer) return self
def random(self, *args, **kwargs)
Add a random index. Shortcut of :class:`recordlinkage.index.Random`:: from recordlinkage.index import Random indexer = recordlinkage.Index() indexer.add(Random())
26.824036
17.540386
1.529273
compare = Exact(*args, **kwargs) self.add(compare) return self
def exact(self, *args, **kwargs)
Compare attributes of pairs exactly. Shortcut of :class:`recordlinkage.compare.Exact`:: from recordlinkage.compare import Exact indexer = recordlinkage.Compare() indexer.add(Exact())
10.522985
8.074376
1.303257
compare = String(*args, **kwargs) self.add(compare) return self
def string(self, *args, **kwargs)
Compare attributes of pairs with string algorithm. Shortcut of :class:`recordlinkage.compare.String`:: from recordlinkage.compare import String indexer = recordlinkage.Compare() indexer.add(String())
11.558488
8.248907
1.401214
compare = Numeric(*args, **kwargs) self.add(compare) return self
def numeric(self, *args, **kwargs)
Compare attributes of pairs with numeric algorithm. Shortcut of :class:`recordlinkage.compare.Numeric`:: from recordlinkage.compare import Numeric indexer = recordlinkage.Compare() indexer.add(Numeric())
9.589758
7.75968
1.235844
compare = Geographic(*args, **kwargs) self.add(compare) return self
def geo(self, *args, **kwargs)
Compare attributes of pairs with geo algorithm. Shortcut of :class:`recordlinkage.compare.Geographic`:: from recordlinkage.compare import Geographic indexer = recordlinkage.Compare() indexer.add(Geographic())
13.429975
7.140955
1.880697
compare = Date(*args, **kwargs) self.add(compare) return self
def date(self, *args, **kwargs)
Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date())
11.174714
8.284063
1.348941
n_max = full_index_size(*total) if isinstance(links_pred, pandas.MultiIndex): links_pred = len(links_pred) if links_pred > n_max: raise ValueError("n has to be smaller of equal n_max") return 1 - links_pred / n_max
def reduction_ratio(links_pred, *total)
Compute the reduction ratio. The reduction ratio is 1 minus the ratio candidate matches and the maximum number of pairs possible. Parameters ---------- links_pred: int, pandas.MultiIndex The number of candidate record pairs or the pandas.MultiIndex with record pairs. *total: pa...
5.68604
4.038594
1.407926
if not isinstance(shape, (tuple, list)): x = get_length(shape) n = int(x * (x - 1) / 2) elif (isinstance(shape, (tuple, list)) and len(shape) == 1): x = get_length(shape[0]) n = int(x * (x - 1) / 2) else: n = numpy.prod([get_length(xi) for xi in shape]) r...
def max_pairs(shape)
[DEPRECATED] Compute the maximum number of record pairs possible.
2.590352
2.393543
1.082225
# check if a list or tuple is passed as argument if len(args) == 1 and isinstance(args[0], (list, tuple)): args = tuple(args[0]) if len(args) == 1: n = get_length(args[0]) size = int(n * (n - 1) / 2) else: size = numpy.prod([get_length(arg) for arg in args]) r...
def full_index_size(*args)
Compute the number of records in a full index. Compute the number of records in a full index without building the index itself. The result is the maximum number of record pairs possible. This function is especially useful in measures like the `reduction_ratio`. Deduplication: Given a DataFrame A with ...
2.744424
2.857061
0.960576
links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_true & links_pred)
def true_positives(links_true, links_pred)
Count the number of True Positives. Returns the number of correctly predicted links, also called the number of True Positives (TP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.Dat...
3.0235
3.699602
0.81725
links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) if isinstance(total, pandas.MultiIndex): total = len(total) return int(total) - len(links_true | links_pred)
def true_negatives(links_true, links_pred, total)
Count the number of True Negatives. Returns the number of correctly predicted non-links, also called the number of True Negatives (TN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas...
3.719791
3.136887
1.185823
links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_pred.difference(links_true))
def false_positives(links_true, links_pred)
Count the number of False Positives. Returns the number of incorrect predictions of true non-links. (true non- links, but predicted as links). This value is known as the number of False Positives (FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series ...
3.118781
3.622824
0.86087
links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_true.difference(links_pred))
def false_negatives(links_true, links_pred)
Count the number of False Negatives. Returns the number of incorrect predictions of true links. (true links, but predicted as non-links). This value is known as the number of False Negatives (FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The ...
2.978732
3.470212
0.858372
links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) tp = true_positives(links_true, links_pred) fp = false_positives(links_true, links_pred) fn = false_negatives(links_true, links_pred) if total is None: tn = numpy.nan else: tn = true_neg...
def confusion_matrix(links_true, links_pred, total=None)
Compute the confusion matrix. The confusion matrix is of the following form: +----------------------+-----------------------+----------------------+ | | Predicted Positives | Predicted Negatives | +======================+=======================+======================+ | **T...
1.986081
2.058976
0.964596
if _isconfusionmatrix(links_true): confusion_matrix = links_true v = confusion_matrix[0, 0] \ / (confusion_matrix[0, 0] + confusion_matrix[1, 0]) else: tp = true_positives(links_true, links_pred) fp = false_positives(links_true, links_pred) v = tp / (...
def precision(links_true, links_pred=None)
precision(links_true, links_pred) Compute the precision. The precision is given by TP/(TP+FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series ...
2.983305
3.280338
0.90945
if _isconfusionmatrix(links_true): confusion_matrix = links_true v = confusion_matrix[0, 0] \ / (confusion_matrix[0, 0] + confusion_matrix[0, 1]) else: tp = true_positives(links_true, links_pred) fn = false_negatives(links_true, links_pred) v = tp / (...
def recall(links_true, links_pred=None)
recall(links_true, links_pred) Compute the recall/sensitivity. The recall is given by TP/(TP+FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Seri...
2.95214
3.224517
0.915529
if _isconfusionmatrix(links_true): confusion_matrix = links_true v = (confusion_matrix[0, 0] + confusion_matrix[1, 1]) \ / numpy.sum(confusion_matrix) else: tp = true_positives(links_true, links_pred) tn = true_negatives(links_true, links_pred, total) ...
def accuracy(links_true, links_pred=None, total=None)
accuracy(links_true, links_pred, total) Compute the accuracy. The accuracy is given by (TP+TN)/(TP+FP+TN+FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: pandas.MultiIndex, pandas.DataFrame,...
3.290188
3.465945
0.94929
if _isconfusionmatrix(links_true): confusion_matrix = links_true v = confusion_matrix[1, 1] / \ (confusion_matrix[1, 0] + confusion_matrix[1, 1]) else: fp = false_positives(links_true, links_pred) tn = true_negatives(links_true, links_pred, total) v =...
def specificity(links_true, links_pred=None, total=None)
specificity(links_true, links_pred, total) Compute the specificity. The specificity is given by TN/(FP+TN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: pandas.MultiIndex, pandas.DataFrame, p...
3.282323
3.422171
0.959135
prec = precision(links_true, links_pred) rec = recall(links_true, links_pred) return float(2 * prec * rec / (prec + rec))
def fscore(links_true, links_pred=None)
fscore(links_true, links_pred) Compute the F-score. The F-score is given by 2*(precision*recall)/(precision+recall). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: pandas.MultiIndex, pandas.Dat...
2.24964
2.948111
0.763078
df_empty = pd.DataFrame(index=pairs) return self._compute( tuple([df_empty]), tuple([df_empty]) )
def compute(self, pairs, x=None, x_link=None)
Return continuous random values for each record pair. Parameters ---------- pairs : pandas.MultiIndex A pandas MultiIndex with the record pairs to compare. The indices in the MultiIndex are indices of the DataFrame(s) to link. x : pandas.DataFrame The...
8.256994
10.683131
0.7729
return class_obj._compute(pairs, x, x_link)
def _parallel_compare_helper(class_obj, pairs, x, x_link=None)
Internal function to overcome pickling problem in python2.
5.787649
5.821461
0.994192
if not isinstance(chunksize, int): raise ValueError('argument chunksize needs to be integer type') bins = np.arange(0, len(frame_or_series), step=chunksize) for b in bins: yield frame_or_series[b:b + chunksize]
def chunk_pandas(frame_or_series, chunksize=None)
Chunk a frame into smaller, equal parts.
3.404444
3.267076
1.042046
if isinstance(model, list): self.algorithms = self.algorithms + model else: self.algorithms.append(model)
def add(self, model)
Add a index method. This method is used to add index algorithms. If multiple algorithms are added, the union of the record pairs from the algorithm is taken. Parameters ---------- model : list, class A (list of) index algorithm(s) from :mod:`recordlinkag...
3.588941
3.378699
1.062226
if not self.algorithms: raise ValueError("No algorithms given.") # start timing start_time = time.time() pairs = None for cl_alg in self.algorithms: pairs_i = cl_alg.index(x, x_link) if pairs is None: pairs = pairs_i...
def index(self, x, x_link=None)
Make an index of record pairs. Parameters ---------- x: pandas.DataFrame A pandas DataFrame. When `x_link` is None, the algorithm makes record pairs within the DataFrame. When `x_link` is not empty, the algorithm makes pairs between `x` and `x_link`. ...
2.735817
2.726147
1.003547
pairs = self._link_index(df_a, df_a) # Remove all pairs not in the lower triangular part of the matrix. # This part can be inproved by not comparing the level values, but the # level itself. pairs = pairs[pairs.labels[0] > pairs.labels[1]] return pairs
def _dedup_index(self, df_a)
Build an index for deduplicating a dataset. Parameters ---------- df_a : (tuple of) pandas.Series The data of the DataFrame to build the index with. Returns ------- pandas.MultiIndex A pandas.MultiIndex with record pairs. Each record pair ...
9.761801
9.95735
0.980361
if x is None: # error raise ValueError("provide at least one dataframe") elif x_link is not None: # linking (two arg) x = (x, x_link) elif isinstance(x, (list, tuple)): # dedup or linking (single arg) x = tuple(x) else: # dedup (single arg...
def index(self, x, x_link=None)
Make an index of record pairs. Use a custom function to make record pairs of one or two dataframes. Each function should return a pandas.MultiIndex with record pairs. Parameters ---------- x: pandas.DataFrame A pandas DataFrame. When `x_link` is None, the algorithm ...
3.742158
3.531725
1.059583
if self._f_compare_vectorized: return self._f_compare_vectorized( *(args + self.args), **self.kwargs) else: raise NotImplementedError()
def _compute_vectorized(self, *args)
Compare attributes (vectorized) Parameters ---------- *args : pandas.Series pandas.Series' as arguments. Returns ------- pandas.Series, pandas.DataFrame, numpy.ndarray The result of comparing record pairs (the features). Can be a tupl...
5.842211
5.807762
1.005932
result = self._compute_vectorized(*tuple(left_on + right_on)) return result
def _compute(self, left_on, right_on)
Compare the data on the left and right. :meth:`BaseCompareFeature._compute` and :meth:`BaseCompareFeature.compute` differ on the accepted arguments. `_compute` accepts indexed data while `compute` accepts the record pairs and the DataFrame's. Parameters ---------- ...
10.363228
15.822404
0.654972
if not is_pandas_2d_multiindex(pairs): raise ValueError( "expected pandas.MultiIndex with record pair indices " "as first argument" ) if not isinstance(x, pandas.DataFrame): raise ValueError("expected pandas.DataFrame as secon...
def compute(self, pairs, x, x_link=None)
Compare the records of each record pair. Calling this method starts the comparing of records. Parameters ---------- pairs : pandas.MultiIndex A pandas MultiIndex with the record pairs to compare. The indices in the MultiIndex are indices of the DataFrame(s) to l...
2.34195
2.2674
1.032879
label = kwargs.pop('label', None) if isinstance(labels_left, tuple): labels_left = list(labels_left) if isinstance(labels_right, tuple): labels_right = list(labels_right) feature = BaseCompareFeature( labels_left, labels_right, args, kwargs...
def compare_vectorized(self, comp_func, labels_left, labels_right, *args, **kwargs)
Compute the similarity between values with a callable. This method initialises the comparing of values with a custom function/callable. The function/callable should accept numpy.ndarray's. Example ------- >>> comp = recordlinkage.Compare() >>> comp.compare_vect...
3.073419
3.778877
0.813315
labels = [] for compare_func in self.features: labels = labels + listify(compare_func.labels_left) # check requested labels (for better error messages) if not is_label_dataframe(labels, validate): error_msg = "label is not found in the dataframe" ...
def _get_labels_left(self, validate=None)
Get all labels of the left dataframe.
9.172642
7.963761
1.151798
labels = [] for compare_func in self.features: labels = labels + listify(compare_func.labels_right) # check requested labels (for better error messages) if not is_label_dataframe(labels, validate): error_msg = "label is not found in the dataframe" ...
def _get_labels_right(self, validate=None)
Get all labels of the right dataframe.
9.448795
8.127307
1.162599
feat_conc = [] for feat, label in objs: # result is tuple of results if isinstance(feat, tuple): if label is None: label = [None] * len(feat) partial_result = self._union( zip(feat, label), column...
def _union(self, objs, index=None, column_i=0)
Make a union of the features. The term 'union' is based on the terminology of scikit-learn.
2.077422
2.060889
1.008022
if not isinstance(pairs, pandas.MultiIndex): raise ValueError( "expected pandas.MultiIndex with record pair indices " "as first argument" ) if not isinstance(x, pandas.DataFrame): raise ValueError("expected pandas.DataFrame as...
def compute(self, pairs, x, x_link=None)
Compare the records of each record pair. Calling this method starts the comparing of records. Parameters ---------- pairs : pandas.MultiIndex A pandas MultiIndex with the record pairs to compare. The indices in the MultiIndex are indices of the DataFrame(s) to l...
2.271972
2.095831
1.084044
warnings.warn("learn is deprecated, {}.fit_predict " "instead".format(self.__class__.__name__)) return self.fit_predict(*args, **kwargs)
def learn(self, *args, **kwargs)
[DEPRECATED] Use 'fit_predict'.
5.346018
3.838433
1.392761
logging.info("Classification - start training {}".format( self.__class__.__name__) ) self._initialise_classifier(comparison_vectors) # start timing start_time = time.time() if isinstance(match_index, (pandas.MultiIndex, pandas.Index)): ...
def fit(self, comparison_vectors, match_index=None)
Train the classifier. Parameters ---------- comparison_vectors : pandas.DataFrame The comparison vectors (or features) to train the model with. match_index : pandas.MultiIndex A pandas.MultiIndex object with the true matches. The MultiIndex contains o...
4.194519
4.146854
1.011494
self.fit(comparison_vectors, match_index) result = self.predict(comparison_vectors) return result
def fit_predict(self, comparison_vectors, match_index=None)
Train the classifier. Parameters ---------- comparison_vectors : pandas.DataFrame The comparison vectors. match_index : pandas.MultiIndex The true matches. return_type : str Deprecated. Use recordlinkage.options instead. Use the option ...
2.960048
4.759411
0.621936
logging.info("Classification - predict matches and non-matches") # make the predicition prediction = self._predict(comparison_vectors.values) self._post_predict(prediction) # format and return the result return self._return_result(prediction, comparison_vectors...
def predict(self, comparison_vectors)
Predict the class of the record pairs. Classify a set of record pairs based on their comparison vectors into matches, non-matches and possible matches. The classifier has to be trained to call this method. Parameters ---------- comparison_vectors : pandas.DataFrame ...
7.492128
7.896978
0.948733
if return_type is not None: warnings.warn("The argument 'return_type' is removed. " "Default value is now 'series'.", VisibleDeprecationWarning, stacklevel=2) logging.info("Classification - compute probabilities") prob_ma...
def prob(self, comparison_vectors, return_type=None)
Compute the probabilities for each record pair. For each pair of records, estimate the probability of being a match. Parameters ---------- comparison_vectors : pandas.DataFrame The dataframe with comparison vectors. return_type : str Deprecated. (default...
5.649849
4.839329
1.167486
return_type = cf.get_option('classification.return_type') if type(result) != np.ndarray: raise ValueError("numpy.ndarray expected.") # return the pandas.MultiIndex if return_type == 'index': return comparison_vectors.index[result.astype(bool)] ...
def _return_result(self, result, comparison_vectors=None)
Return different formatted classification results.
3.472426
3.235108
1.073357
if len(m) != len(u): raise ValueError("the length of 'm' is not equal the length of 'u'") if n_match >= n or n_match < 0: raise ValueError("the number of matches is bounded by [0, n]") # set the random seed np.random.seed(random_state) matches = [] nonmatches = [] s...
def binary_vectors(n, n_match, m=[0.9] * 8, u=[0.1] * 8, random_state=None, return_links=False, dtype=np.int8)
Generate random binary comparison vectors. This function is used to generate random comparison vectors. The result of each comparison is a binary value (0 or 1). Parameters ---------- n : int The total number of comparison vectors. n_match : int The number of matching record pa...
2.259429
2.340621
0.965312
# TODO: add notfitted warnings if self.kernel.classes_.shape[0] != 2: raise ValueError("Number of classes is {}, expected 2.".format( self.kernel.classes_.shape[0])) # # get the position of match probabilities # classes = list(self.kernel.classes_) ...
def _match_class_pos(self)
Return the position of the match class.
7.114592
6.35613
1.119328
# TODO: add notfitted warnings if self.kernel.classes_.shape[0] != 2: raise ValueError("Number of classes is {}, expected 2.".format( self.kernel.classes_.shape[0])) # # get the position of match probabilities # classes = list(self.kernel.classes_) ...
def _nonmatch_class_pos(self)
Return the position of the non-match class.
7.031487
6.54406
1.074484
m = self.kernel.feature_log_prob_[self._match_class_pos()] return self._prob_inverse_transform(m)
def log_m_probs(self)
Log probability P(x_i==1|Match) as described in the FS framework.
21.882383
16.934679
1.292164
u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(u)
def log_u_probs(self)
Log probability P(x_i==1|Non-match) as described in the FS framework.
26.623386
16.505678
1.612983
m = self.kernel.feature_log_prob_[self._match_class_pos()] u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(m - u)
def log_weights(self)
Log weights as described in the FS framework.
9.573521
8.837487
1.083285
log_m = self.kernel.feature_log_prob_[self._match_class_pos()] return self._prob_inverse_transform(numpy.exp(log_m))
def m_probs(self)
Probability P(x_i==1|Match) as described in the FS framework.
17.686941
12.97456
1.363202
log_u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(numpy.exp(log_u))
def u_probs(self)
Probability P(x_i==1|Non-match) as described in the FS framework.
20.090752
13.323194
1.507953
m = self.kernel.feature_log_prob_[self._match_class_pos()] u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(numpy.exp(m - u))
def weights(self)
Weights as described in the FS framework.
9.195189
8.426649
1.091203
# Set the start point of the classifier. self.kernel.init = numpy.array( [[0.05] * len(list(comparison_vectors)), [0.95] * len(list(comparison_vectors))])
def _initialise_classifier(self, comparison_vectors)
Set the centers of the clusters.
6.327798
5.771084
1.096466
setdiff = set(label) - set(df.columns.tolist()) if len(setdiff) == 0: return True else: return False
def is_label_dataframe(label, df)
check column label existance
3.685113
3.333835
1.105367
if isinstance(x, list): return x elif isinstance(x, tuple): return list(x) elif x is None: return none_value else: return [x]
def listify(x, none_value=[])
Make a list of the argument if it is not a list.
1.947791
1.743411
1.11723
return pandas.DataFrame(index.tolist(), index=index, columns=index.names)
def multi_index_to_frame(index)
Replicates MultiIndex.to_frame, which was introduced in pandas 0.21, for the sake of backwards compatibility.
6.642571
5.902788
1.125328
Ntotal = index.shape[0] Nsections = int(chunks) if Nsections <= 0: raise ValueError('number sections must be larger than 0.') Neach_section, extras = divmod(Ntotal, Nsections) section_sizes = ([0] + extras * [Neach_section + 1] + (Nsections - extras) * [Neach_secti...
def index_split(index, chunks)
Function to split pandas.Index and pandas.MultiIndex objects. Split :class:`pandas.Index` and :class:`pandas.MultiIndex` objects into chunks. This function is based on :func:`numpy.array_split`. Parameters ---------- index : pandas.Index, pandas.MultiIndex A pandas.Index or pandas.MultiInd...
3.336728
3.526477
0.946193
if indexing_type == "label": data = frame.loc[multi_index.get_level_values(level_i)] data.index = multi_index elif indexing_type == "position": data = frame.iloc[multi_index.get_level_values(level_i)] data.index = multi_index else: raise ValueError("indexing_typ...
def frame_indexing(frame, multi_index, level_i, indexing_type='label')
Index dataframe based on one level of MultiIndex. Arguments --------- frame : pandas.DataFrame The datafrme to select records from. multi_index : pandas.MultiIndex A pandas multiindex were one fo the levels is used to sample the dataframe with. level_i : int, str The...
1.992462
2.023763
0.984533
if pandas.notnull(missing_value): if isinstance(series_or_arr, (numpy.ndarray)): series_or_arr[numpy.isnan(series_or_arr)] = missing_value else: series_or_arr.fillna(missing_value, inplace=True) return series_or_arr
def fillna(series_or_arr, missing_value=0.0)
Fill missing values in pandas objects and numpy arrays. Arguments --------- series_or_arr : pandas.Series, numpy.ndarray The numpy array or pandas series for which the missing values need to be replaced. missing_value : float, int, str The value to replace the missing value with...
2.00923
2.558303
0.785376
model = None if hasattr(field, 'related_model') and field.related_model: # pragma: no cover model = field.related_model # Django<1.8 doesn't have the related_model API, so we need to use rel, # which was removed in Django 2.0 elif hasattr(field, 'rel') and field.rel: # pragma: no c...
def get_related_model(field)
Gets the related model from a related field
3.518676
3.350489
1.050198
df = self.to_dataframe(fieldnames, verbose=verbose, coerce_float=coerce_float) return df.pivot_table(values=values, fill_value=fill_value, index=rows, columns=cols, aggfunc=aggfunc, margins=margins, drop...
def to_pivot_table(self, fieldnames=(), verbose=True, values=None, rows=None, cols=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, coerce_float=True)
A convenience method for creating a spread sheet style pivot table as a DataFrame Parameters ---------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in the usual Django ORM way by ...
2.073924
2.743435
0.755959
return read_frame(self, fieldnames=fieldnames, verbose=verbose, index_col=index, coerce_float=coerce_float, datetime_index=datetime_index)
def to_dataframe(self, fieldnames=(), verbose=True, index=None, coerce_float=False, datetime_index=False)
Returns a DataFrame from the queryset Paramaters ----------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in the usual Django ORM way by using the foreign key field name ...
2.364197
3.486945
0.678014
if fieldnames: fieldnames = pd.unique(fieldnames) if index_col is not None and index_col not in fieldnames: # Add it to the field names if not already there fieldnames = tuple(fieldnames) + (index_col,) fields = to_fields(qs, fieldnames) elif is_values_query...
def read_frame(qs, fieldnames=(), index_col=None, coerce_float=False, verbose=True, datetime_index=False)
Returns a dataframe from a QuerySet Optionally specify the field names/columns to utilize and a field as the index Parameters ---------- qs: The Django QuerySet. fieldnames: The model field names to use in creating the frame. You can span a relationship in the usual Django way ...
2.371132
2.379661
0.996416
if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1
def _is_balanced(root)
Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int
1.681112
1.710255
0.98296
if root is None: return True return ( min_value < root.value < max_value and _is_bst(root.left, min_value, root.value) and _is_bst(root.right, root.value, max_value) )
def _is_bst(root, min_value=float('-inf'), max_value=float('inf'))
Check if the binary tree is a BST (binary search tree). :param root: Root node of the binary tree. :type root: binarytree.Node | None :param min_value: Minimum node value seen. :type min_value: int | float :param max_value: Maximum node value seen. :type max_value: int | float :return: True...
1.630854
1.749774
0.932037
max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) return _build_bst_from_sorted_values(node_values)
def _generate_perfect_bst(height)
Generate a perfect BST (binary search tree) and return its root. :param height: Height of the BST. :type height: int :return: Root node of the BST. :rtype: binarytree.Node
3.131277
4.007696
0.781316
if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root
def _build_bst_from_sorted_values(sorted_values)
Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node
1.407208
1.428107
0.985366
max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count
def _generate_random_leaf_count(height)
Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int
3.187394
3.350447
0.951334
max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values
def _generate_random_node_values(height)
Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int]
2.451054
2.615164
0.937247
is_descending = True is_ascending = True min_node_value = root.value max_node_value = root.value size = 0 leaf_count = 0 min_leaf_depth = 0 max_leaf_depth = -1 is_strict = True is_complete = True current_nodes = [root] non_full_node_seen = False while len(curren...
def _get_tree_properties(root)
Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict
1.861789
1.892175
0.983941
nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( ...
def build(values)
Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node...
2.614406
2.656133
0.98429
_validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserte...
def tree(height=3, is_perfect=False)
Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary t...
2.776908
3.475352
0.799029
_validate_tree_height(height) if is_perfect: return _generate_perfect_bst(height) values = _generate_random_node_values(height) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = ...
def bst(height=3, is_perfect=False)
Generate a random BST (binary search tree) and return its root node. :param height: Height of the BST (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect BST with all levels filled is returned. If set to False, a perfect BST may stil...
2.559216
3.032848
0.843833
_validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] ...
def heap(height=3, is_max=True, is_perfect=False)
Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is consi...
3.804042
5.266496
0.72231
lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines)))
def pprint(self, index=False, delimiter='-')
Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). ...
5.663034
8.855404
0.6395
has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None))...
def validate(self)
Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.ex...
2.550714
2.310689
1.103876
current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next...
def values(self)
Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current nod...
2.289678
2.631479
0.870111