query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
confusion matrix | python | def plot_confusion_matrix(self, normalised=True):
"""
Plots the confusion matrix.
"""
conf_matrix = self.confusion_matrix()
if normalised:
sns.heatmap(conf_matrix,
annot=True, annot_kws={"size": 12}, fmt='2.1f', cmap='YlGnBu', vmin=0.0,
vmax=100.0,
xticklabels=list(self.class_dictionary.keys()),
yticklabels=self.truth_classes)
else:
sns.heatmap(self.pixel_classification_counts,
annot=True, annot_kws={"size": 12}, fmt='2.1f', cmap='YlGnBu', vmin=0.0,
vmax=np.max(self.pixel_classification_counts),
xticklabels=list(self.class_dictionary.keys()),
yticklabels=self.truth_classes) | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/ml_tools/eolearn/ml_tools/validator.py#L210-L227 |
confusion matrix | python | def plot_confusion_matrix(self, normalize:bool=False, title:str='Confusion matrix', cmap:Any="Blues", slice_size:int=1,
norm_dec:int=2, plot_txt:bool=True, return_fig:bool=None, **kwargs)->Optional[plt.Figure]:
"Plot the confusion matrix, with `title` and using `cmap`."
# This function is mainly copied from the sklearn docs
cm = self.confusion_matrix(slice_size=slice_size)
if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fig = plt.figure(**kwargs)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
tick_marks = np.arange(self.data.c)
plt.xticks(tick_marks, self.data.y.classes, rotation=90)
plt.yticks(tick_marks, self.data.y.classes, rotation=0)
if plot_txt:
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
coeff = f'{cm[i, j]:.{norm_dec}f}' if normalize else f'{cm[i, j]}'
plt.text(j, i, coeff, horizontalalignment="center", verticalalignment="center", color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.grid(False)
if ifnone(return_fig, defaults.return_fig): return fig | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L161-L184 |
confusion matrix | python | def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label') | https://github.com/openmednlp/bedrock/blob/15796bd7837ddfe7ad5235fd188e5d7af8c0be49/bedrock/viz.py#L12-L44 |
confusion matrix | python | def confusion_matrix(self):
"""Confusion matrix plot
"""
return plot.confusion_matrix(self.y_true, self.y_pred,
self.target_names, ax=_gen_ax()) | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/evaluator.py#L85-L89 |
confusion matrix | python | def confusion_matrix(predicted_essential, expected_essential,
predicted_nonessential, expected_nonessential):
"""
Compute a representation of the confusion matrix.
Parameters
----------
predicted_essential : set
expected_essential : set
predicted_nonessential : set
expected_nonessential : set
Returns
-------
dict
Confusion matrix as different keys of a dictionary. The abbreviated
keys correspond to the ones used in [1]_.
References
----------
.. [1] `Wikipedia entry for the Confusion matrix
<https://en.wikipedia.org/wiki/Confusion_matrix>`_
"""
true_positive = predicted_essential & expected_essential
tp = len(true_positive)
true_negative = predicted_nonessential & expected_nonessential
tn = len(true_negative)
false_positive = predicted_essential - expected_essential
fp = len(false_positive)
false_negative = predicted_nonessential - expected_nonessential
fn = len(false_negative)
# sensitivity or true positive rate
try:
tpr = tp / (tp + fn)
except ZeroDivisionError:
tpr = None
# specificity or true negative rate
try:
tnr = tn / (tn + fp)
except ZeroDivisionError:
tnr = None
# precision or positive predictive value
try:
ppv = tp / (tp + fp)
except ZeroDivisionError:
ppv = None
# false discovery rate
fdr = 1 - ppv
# accuracy
try:
acc = (tp + tn) / (tp + tn + fp + fn)
except ZeroDivisionError:
acc = None
# Compute Matthews correlation coefficient.
try:
mcc = (tp * tn - fp * fn) /\
sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
except ZeroDivisionError:
mcc = None
return {
"TP": list(true_positive),
"TN": list(true_negative),
"FP": list(false_positive),
"FN": list(false_negative),
"TPR": tpr,
"TNR": tnr,
"PPV": ppv,
"FDR": fdr,
"ACC": acc,
"MCC": mcc
} | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/essentiality.py#L29-L100 |
confusion matrix | python | def do_confusion_matrix(sorting1, sorting2, unit_map12, labels_st1, labels_st2):
"""
Compute the confusion matrix between two sorting.
Parameters
----------
sorting1: SortingExtractor instance
The ground truth sorting.
sorting2: SortingExtractor instance
The tested sorting.
unit_map12: dict
Dict of matching from sorting1 to sorting2.
Output
----------
confusion_matrix: the confusion matrix
st1_idxs: order of units1 in confusion matrix
st2_idxs: order of units2 in confusion matrix
"""
unit1_ids = np.array(sorting1.get_unit_ids())
unit2_ids = np.array(sorting2.get_unit_ids())
N1 = len(unit1_ids)
N2 = len(unit2_ids)
conf_matrix = np.zeros((N1 + 1, N2 + 1), dtype=int)
mapped_units = np.array(list(unit_map12.values()))
idxs_matched, = np.where(mapped_units != -1)
idxs_unmatched, = np.where(mapped_units == -1)
unit_map_matched = mapped_units[idxs_matched]
st1_idxs =np.hstack([unit1_ids[idxs_matched], unit1_ids[idxs_unmatched]])
st2_matched = unit_map_matched
st2_unmatched = []
for u_i, u1 in enumerate(unit1_ids[idxs_matched]):
lab_st1 = labels_st1[u1]
tp = len(np.where('TP' == lab_st1)[0])
conf_matrix[u_i, u_i] = int(tp)
for u_j, u2 in enumerate(unit2_ids):
lab_st2 = labels_st2[u2]
cl_str = str(u1) + '_' + str(u2)
cl = len([i for i, v in enumerate(lab_st1) if 'CL' in v and cl_str in v])
if cl != 0:
st_p, = np.where(u2 == unit_map_matched)
conf_matrix[u_i, st_p] = int(cl)
fn = len(np.where('FN' == lab_st1)[0])
conf_matrix[u_i, -1] = int(fn)
for u_i, u1 in enumerate(unit1_ids[idxs_unmatched]):
lab_st1 = labels_st1[u1]
fn = len(np.where('FN' == lab_st1)[0])
conf_matrix[u_i + len(idxs_matched), -1] = int(fn)
for u_j, u2 in enumerate(unit2_ids):
lab_st2 = labels_st2[u2]
fp = len(np.where('FP' == lab_st2)[0])
st_p, = np.where(u2 == unit_map_matched)
if len(st_p) != 0:
conf_matrix[-1, st_p] = int(fp)
else:
st2_unmatched.append(int(u2))
conf_matrix[-1, len(idxs_matched) + len(st2_unmatched) - 1] = int(fp)
st2_idxs = np.hstack([st2_matched, st2_unmatched]).astype('int64')
return conf_matrix, st1_idxs, st2_idxs | https://github.com/SpikeInterface/spiketoolkit/blob/f7c054383d1ebca640966b057c087fa187955d13/spiketoolkit/comparison/comparisontools.py#L319-L395 |
confusion matrix | python | def plot_confusion_matrix(cm, title="Confusion Matrix"):
"""Plots a confusion matrix for each subject
"""
import matplotlib.pyplot as plt
import math
plt.figure()
subjects = len(cm)
root_subjects = math.sqrt(subjects)
cols = math.ceil(root_subjects)
rows = math.ceil(subjects/cols)
classes = cm[0].shape[0]
for subject in range(subjects):
plt.subplot(rows, cols, subject+1)
plt.imshow(cm[subject], interpolation='nearest', cmap=plt.cm.bone)
plt.xticks(np.arange(classes), range(1, classes+1))
plt.yticks(np.arange(classes), range(1, classes+1))
cbar = plt.colorbar(ticks=[0.0, 1.0], shrink=0.6)
cbar.set_clim(0.0, 1.0)
plt.xlabel("Predicted")
plt.ylabel("True label")
plt.title("{0:d}".format(subject + 1))
plt.suptitle(title)
plt.tight_layout()
plt.show() | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/examples/funcalign/srm_image_prediction_example_distributed.py#L52-L75 |
confusion matrix | python | def calc_confusion_matrix(self, printout = False):
"""
Calculates number of TP, FP, TN, FN
"""
if self.labels is None:
raise DataError("Cannot calculate confusion matrix before data "
"has been read.")
if self.preds is None:
raise DataError("Predictions not available. Please run "
"`scores_to_preds` before calculating confusion "
"matrix")
self.TP = np.sum(np.logical_and(self.preds == 1, self.labels == 1))
self.TN = np.sum(np.logical_and(self.preds == 0, self.labels == 0))
self.FP = np.sum(np.logical_and(self.preds == 1, self.labels == 0))
self.FN = np.sum(np.logical_and(self.preds == 0, self.labels == 1))
if printout:
print("Contingency matrix is:")
print("----------------------")
print("TP: {} \t FN: {}".format(self.TP,self.FN))
print("FP: {} \t TN: {}".format(self.FP,self.TN))
print("\n") | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L216-L239 |
confusion matrix | python | def confusion_matrix(self, slice_size:int=1):
"Confusion matrix as an `np.ndarray`."
x=torch.arange(0,self.data.c)
if slice_size is None: cm = ((self.pred_class==x[:,None]) & (self.y_true==x[:,None,None])).sum(2)
else:
cm = torch.zeros(self.data.c, self.data.c, dtype=x.dtype)
for i in range(0, self.y_true.shape[0], slice_size):
cm_slice = ((self.pred_class[i:i+slice_size]==x[:,None])
& (self.y_true[i:i+slice_size]==x[:,None,None])).sum(2)
torch.add(cm, cm_slice, out=cm)
return to_np(cm) | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L149-L159 |
confusion matrix | python | def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
text_fontsize="medium"):
"""Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset
of labels. If none is given, those that appear at least once in
``y_true`` or ``y_pred`` are used in sorted order. (new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if `normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the curve. If None, the plot is drawn on a new set of axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> rf = rf.fit(X_train, y_train)
>>> y_pred = rf.predict(X_test)
>>> skplt.plot_confusion_matrix(y_test, y_pred, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=figsize)
cm = confusion_matrix(y_true, y_pred, labels=labels)
if labels is None:
classes = unique_labels(y_true, y_pred)
else:
classes = np.asarray(labels)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm = np.around(cm, decimals=2)
cm[np.isnan(cm)] = 0.0
if true_labels is None:
true_classes = classes
else:
validate_labels(classes, true_labels, "true_labels")
true_label_indexes = np.in1d(classes, true_labels)
true_classes = classes[true_label_indexes]
cm = cm[true_label_indexes]
if pred_labels is None:
pred_classes = classes
else:
validate_labels(classes, pred_labels, "pred_labels")
pred_label_indexes = np.in1d(classes, pred_labels)
pred_classes = classes[pred_label_indexes]
cm = cm[:, pred_label_indexes]
if title:
ax.set_title(title, fontsize=title_fontsize)
elif normalize:
ax.set_title('Normalized Confusion Matrix', fontsize=title_fontsize)
else:
ax.set_title('Confusion Matrix', fontsize=title_fontsize)
image = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.get_cmap(cmap))
plt.colorbar(mappable=image)
x_tick_marks = np.arange(len(pred_classes))
y_tick_marks = np.arange(len(true_classes))
ax.set_xticks(x_tick_marks)
ax.set_xticklabels(pred_classes, fontsize=text_fontsize,
rotation=x_tick_rotation)
ax.set_yticks(y_tick_marks)
ax.set_yticklabels(true_classes, fontsize=text_fontsize)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
if not (hide_zeros and cm[i, j] == 0):
ax.text(j, i, cm[i, j],
horizontalalignment="center",
verticalalignment="center",
fontsize=text_fontsize,
color="white" if cm[i, j] > thresh else "black")
ax.set_ylabel('True label', fontsize=text_fontsize)
ax.set_xlabel('Predicted label', fontsize=text_fontsize)
ax.grid('off')
return ax | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L42-L181 |
confusion matrix | python | def plot(self, figsize=None, rotation=45):
"""Plot the confusion matrix.
Args:
figsize: tuple (x, y) of ints. Sets the size of the figure
rotation: the rotation angle of the labels on the x-axis.
"""
fig, ax = plt.subplots(figsize=figsize)
plt.imshow(self._cm, interpolation='nearest', cmap=plt.cm.Blues, aspect='auto')
plt.title('Confusion matrix')
plt.colorbar()
tick_marks = np.arange(len(self._labels))
plt.xticks(tick_marks, self._labels, rotation=rotation)
plt.yticks(tick_marks, self._labels)
if isinstance(self._cm, list):
# If cm is created from BigQuery then it is a list.
thresh = max(max(self._cm)) / 2.
for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):
plt.text(j, i, self._cm[i][j], horizontalalignment="center",
color="white" if self._cm[i][j] > thresh else "black")
else:
# If cm is created from csv then it is a sklearn's confusion_matrix.
thresh = self._cm.max() / 2.
for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):
plt.text(j, i, self._cm[i, j], horizontalalignment="center",
color="white" if self._cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label') | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L129-L159 |
confusion matrix | python | def fmt_confusion_matrix(hyps: Sequence[Sequence[str]],
refs: Sequence[Sequence[str]],
label_set: Set[str] = None,
max_width: int = 25) -> str:
""" Formats a confusion matrix over substitutions, ignoring insertions
and deletions. """
if not label_set:
# Then determine the label set by reading
raise NotImplementedError()
alignments = [min_edit_distance_align(ref, hyp)
for hyp, ref in zip(hyps, refs)]
arrow_counter = Counter() # type: Dict[Tuple[str, str], int]
for alignment in alignments:
arrow_counter.update(alignment)
ref_total = Counter() # type: Dict[str, int]
for alignment in alignments:
ref_total.update([arrow[0] for arrow in alignment])
labels = [label for label, count
in sorted(ref_total.items(), key=lambda x: x[1], reverse=True)
if label != ""][:max_width]
format_pieces = []
fmt = "{:3} "*(len(labels)+1)
format_pieces.append(fmt.format(" ", *labels))
fmt = "{:3} " + ("{:<3} " * (len(labels)))
for ref in labels:
# TODO
ref_results = [arrow_counter[(ref, hyp)] for hyp in labels]
format_pieces.append(fmt.format(ref, *ref_results))
return "\n".join(format_pieces) | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/results.py#L132-L167 |
confusion matrix | python | def confusion(a, p):
"""Confusion Matrix
- confusion matrix, error matrix, matching matrix (unsupervised)
- is a special case: 2x2 contingency table (xtab, RxC table)
- both dimensions are variables with the same classes/labels,
i.e. actual and predicted variables are binary [0,1]
Parameters:
-----------
a : ndarray
Actual values, binary [0,1]
p : ndarray
Predicted values, binary [0,1]
Returns:
--------
cm : ndarray
Confusion matrix
predicted=0 predicted=1
actual=0 tn fp
actual=1 fn tp
Example:
--------
import korr
cm = korr.confusion(a, p)
tn, fp, fn, tp = cm.ravel()
Alternatives:
-------------
import pandas as pd
cm = pd.crosstab(a, p)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(a, p)
"""
m = a == p # matches (a=1, p=1) and (a=0, p=0)
f = np.logical_not(m) # xor (a=1, p=0) and (a=0, p=1)
tp = np.sum(np.logical_and(m, a)) # 11
tn = np.sum(np.logical_and(m, np.logical_not(a))) # 00
fn = np.sum(np.logical_and(f, a)) # 10
fp = np.sum(np.logical_and(f, p)) # 01
return np.array([[tn, fp], [fn, tp]]) | https://github.com/kmedian/korr/blob/4eb86fc14b1fc1b69204069b7753d115b327c937/korr/confusion.py#L4-L49 |
confusion matrix | python | def plot_confusion_matrix_with_cv(clf, X, y, labels=None, true_labels=None,
pred_labels=None, title=None,
normalize=False, hide_zeros=False,
x_tick_rotation=0, do_cv=True, cv=None,
shuffle=True, random_state=None, ax=None,
figsize=None, cmap='Blues',
title_fontsize="large",
text_fontsize="medium"):
"""Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y (array-like, shape (n_samples) or (n_samples, n_features)):
Target relative to X for classification.
labels (array-like, shape (n_classes), optional): List of labels to
index the matrix. This may be used to reorder or select a subset of
labels. If none is given, those that appear at least once in ``y``
are used in sorted order.
(new in v0.2.5)
true_labels (array-like, optional): The true labels to display.
If none is given, then all of the labels are used.
pred_labels (array-like, optional): The predicted labels to display.
If none is given, then all of the labels are used.
title (string, optional): Title of the generated plot. Defaults to
"Confusion Matrix" if normalize` is True. Else, defaults to
"Normalized Confusion Matrix.
normalize (bool, optional): If True, normalizes the confusion matrix
before plotting. Defaults to False.
hide_zeros (bool, optional): If True, does not plot cells containing a
value of zero. Defaults to False.
x_tick_rotation (int, optional): Rotates x-axis tick labels by the
specified angle. This is useful in cases where there are numerous
categories and the labels overlap each other.
do_cv (bool, optional): If True, the classifier is cross-validated on
the dataset using the cross-validation strategy in `cv` to generate
the confusion matrix. If False, the confusion matrix is generated
without training or cross-validating the classifier. This assumes
that the classifier has already been called with its `fit` method
beforehand.
cv (int, cross-validation generator, iterable, optional): Determines
the cross-validation strategy to be used for splitting.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is
used.
shuffle (bool, optional): Used when do_cv is set to True. Determines
whether to shuffle the training data before splitting using
cross-validation. Default set to True.
random_state (int :class:`RandomState`): Pseudo-random number generator
state used for random sampling.
ax (:class:`matplotlib.axes.Axes`, optional): The axes upon which to
plot the learning curve. If None, the plot is drawn on a new set of
axes.
figsize (2-tuple, optional): Tuple denoting figure size of the plot
e.g. (6, 6). Defaults to ``None``.
cmap (string or :class:`matplotlib.colors.Colormap` instance, optional):
Colormap used for plotting the projection. View Matplotlib Colormap
documentation for available options.
https://matplotlib.org/users/colormaps.html
title_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"large".
text_fontsize (string or int, optional): Matplotlib-style fontsizes.
Use e.g. "small", "medium", "large" or integer-values. Defaults to
"medium".
Returns:
ax (:class:`matplotlib.axes.Axes`): The axes on which the plot was
drawn.
Example:
>>> rf = classifier_factory(RandomForestClassifier())
>>> rf.plot_confusion_matrix(X, y, normalize=True)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_confusion_matrix.png
:align: center
:alt: Confusion matrix
"""
y = np.array(y)
if not do_cv:
y_pred = clf.predict(X)
y_true = y
else:
if cv is None:
cv = StratifiedKFold(shuffle=shuffle, random_state=random_state)
elif isinstance(cv, int):
cv = StratifiedKFold(n_splits=cv, shuffle=shuffle,
random_state=random_state)
else:
pass
clf_clone = clone(clf)
preds_list = []
trues_list = []
for train_index, test_index in cv.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf_clone.fit(X_train, y_train)
preds = clf_clone.predict(X_test)
preds_list.append(preds)
trues_list.append(y_test)
y_pred = np.concatenate(preds_list)
y_true = np.concatenate(trues_list)
ax = plotters.plot_confusion_matrix(y_true=y_true, y_pred=y_pred,
labels=labels, true_labels=true_labels,
pred_labels=pred_labels,
title=title, normalize=normalize,
hide_zeros=hide_zeros,
x_tick_rotation=x_tick_rotation, ax=ax,
figsize=figsize, cmap=cmap,
title_fontsize=title_fontsize,
text_fontsize=text_fontsize)
return ax | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L70-L219 |
confusion matrix | python | def confusion_matrix(
gold, pred, null_pred=False, null_gold=False, normalize=False, pretty_print=True
):
"""A shortcut method for building a confusion matrix all at once.
Args:
gold: an array-like of gold labels (ints)
pred: an array-like of predictions (ints)
null_pred: If True, include the row corresponding to null predictions
null_gold: If True, include the col corresponding to null gold labels
normalize: if True, divide counts by the total number of items
pretty_print: if True, pretty-print the matrix before returning
"""
conf = ConfusionMatrix(null_pred=null_pred, null_gold=null_gold)
gold = arraylike_to_numpy(gold)
pred = arraylike_to_numpy(pred)
conf.add(gold, pred)
mat = conf.compile()
if normalize:
mat = mat / len(gold)
if pretty_print:
conf.display(normalize=normalize)
return mat | https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/analysis.py#L217-L242 |
confusion matrix | python | def draw_confusion_matrix(matrix):
'''Draw confusion matrix for MNIST.'''
fig = tfmpl.create_figure(figsize=(7,7))
ax = fig.add_subplot(111)
ax.set_title('Confusion matrix for MNIST classification')
tfmpl.plots.confusion_matrix.draw(
ax, matrix,
axis_labels=['Digit ' + str(x) for x in range(10)],
normalize=True
)
return fig | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/samples/mnist.py#L24-L36 |
confusion matrix | python | def confusion_matrix(self, metrics=None, thresholds=None):
"""
Get the confusion matrix for the specified metric
:param metrics: A string (or list of strings) among metrics listed in :const:`max_metrics`. Defaults to 'f1'.
:param thresholds: A value (or list of values) between 0 and 1.
:returns: a list of ConfusionMatrix objects (if there are more than one to return), or a single ConfusionMatrix
(if there is only one).
"""
# make lists out of metrics and thresholds arguments
if metrics is None and thresholds is None:
metrics = ['f1']
if isinstance(metrics, list):
metrics_list = metrics
elif metrics is None:
metrics_list = []
else:
metrics_list = [metrics]
if isinstance(thresholds, list):
thresholds_list = thresholds
elif thresholds is None:
thresholds_list = []
else:
thresholds_list = [thresholds]
# error check the metrics_list and thresholds_list
assert_is_type(thresholds_list, [numeric])
assert_satisfies(thresholds_list, all(0 <= t <= 1 for t in thresholds_list))
if not all(m.lower() in H2OBinomialModelMetrics.max_metrics for m in metrics_list):
raise ValueError("The only allowable metrics are {}", ', '.join(H2OBinomialModelMetrics.max_metrics))
# make one big list that combines the thresholds and metric-thresholds
metrics_thresholds = [self.find_threshold_by_max_metric(m) for m in metrics_list]
for mt in metrics_thresholds:
thresholds_list.append(mt)
first_metrics_thresholds_offset = len(thresholds_list) - len(metrics_thresholds)
thresh2d = self._metric_json['thresholds_and_metric_scores']
actual_thresholds = [float(e[0]) for i, e in enumerate(thresh2d.cell_values)]
cms = []
for i, t in enumerate(thresholds_list):
idx = self.find_idx_by_threshold(t)
row = thresh2d.cell_values[idx]
tns = row[11]
fns = row[12]
fps = row[13]
tps = row[14]
p = tps + fns
n = tns + fps
c0 = n - fps
c1 = p - tps
if t in metrics_thresholds:
m = metrics_list[i - first_metrics_thresholds_offset]
table_header = "Confusion Matrix (Act/Pred) for max {} @ threshold = {}".format(m, actual_thresholds[idx])
else:
table_header = "Confusion Matrix (Act/Pred) @ threshold = {}".format(actual_thresholds[idx])
cms.append(ConfusionMatrix(cm=[[c0, fps], [c1, tps]], domains=self._metric_json['domain'],
table_header=table_header))
if len(cms) == 1:
return cms[0]
else:
return cms | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/metrics_base.py#L588-L653 |
confusion matrix | python | def confusion_matrix(self):
"""
Returns the normalised confusion matrix
"""
confusion_matrix = self.pixel_classification_sum.astype(np.float)
confusion_matrix = np.divide(confusion_matrix.T, self.pixel_truth_sum.T).T
return confusion_matrix * 100.0 | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/ml_tools/eolearn/ml_tools/validator.py#L201-L208 |
confusion matrix | python | 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 |
+======================+=======================+======================+
| **True Positives** | True Positives (TP) | False Negatives (FN) |
+----------------------+-----------------------+----------------------+
| **True Negatives** | False Positives (FP) | True Negatives (TN) |
+----------------------+-----------------------+----------------------+
The confusion matrix is an informative way to analyse a prediction. The
matrix can used to compute measures like precision and recall. The count
of true prositives is [0,0], false negatives is [0,1], true negatives
is [1,1] and false positives is [1,0].
Parameters
----------
links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series
The true (or actual) links.
links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series
The predicted links.
total: int, pandas.MultiIndex
The count of all record pairs (both links and non-links). When the
argument is a pandas.MultiIndex, the length of the index is used. If
the total is None, the number of True Negatives is not computed.
Default None.
Returns
-------
numpy.array
The confusion matrix with TP, TN, FN, FP values.
Note
----
The number of True Negatives is computed based on the total argument.
This argument is the number of record pairs of the entire matrix.
"""
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_negatives(links_true, links_pred, total)
return numpy.array([[tp, fn], [fp, tn]]) | https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/measures.py#L238-L292 |
confusion matrix | python | def confusion_matrix(exp, obs):
"""Create a confusion matrix
In each axis of the resulting confusion matrix the negative case is
0-index and the positive case 1-index. The labels get sorted, in a
True/False scenario true positives will occur at (1,1). The first dimension
(rows) of the resulting matrix is the expected class and the second
dimension (columns) is the observed class.
:param exp: expected values
:type exp: list of float
:param obs: observed values
:type obs: list of float
:rtype: tuple of square matrix and sorted labels
"""
assert len(exp) == len(obs)
# Expected in the first dimension (0;rows), observed in the second (1;cols)
lbls = sorted(set(exp))
res = numpy.zeros(shape=(len(lbls), len(lbls)))
for i in range(len(exp)):
res[lbls.index(exp[i]), lbls.index(obs[i])] += 1
return res, lbls | https://github.com/childsish/lhc-python/blob/0a669f46a40a39f24d28665e8b5b606dc7e86beb/lhc/misc/performance_measures.py#L152-L173 |
confusion matrix | python | def _make_diffusion_matrix(K, weight1=None, weight2=None):
"""Builds the general diffusion matrix with dimension nxn.
.. note::
:math:`n` = number of points of diffusion axis
:math:`n+1` = number of bounts of diffusion axis
**Function-all argument** \n
:param array K: dimensionless diffusivities at cell boundaries
*(size: 1xn+1)*
:param array weight1: weight_1 *(size: 1xn+1)*
:param array weight2: weight_2 *(size: 1xn)*
:returns: completely listed tridiagonal diffusion matrix *(size: nxn)*
:rtype: array
.. note::
The elements of array K are acutally dimensionless:
.. math::
K[i] = K_{\\textrm{physical}} \\frac{\\Delta t}{(\\Delta y)^2}
where :math:`K_{\\textrm{physical}}` is in unit :math:`\\frac{\\textrm{length}^2}{\\textrm{time}}`
The diffusion matrix is build like the following
.. math::
\\textrm{diffTriDiag}=
\\left[ \\begin{array}{cccccc}
1+\\frac{s_1 }{w_{2,0}} & -\\frac{s_1}{w_{2,0}} & 0 & & ... & 0 \\\\
-\\frac{s_1}{w_{2,1}} & 1+\\frac{s_1 + s_2}{w_{2,1}} & -\\frac{s_2}{w_{2,1}} & 0 & ... & 0 \\\\
0 & -\\frac{s_2}{w_{2,2}} & 1+\\frac{s_2 + s_3}{w_{2,2}} & -\\frac{s_3}{w_{2,2}} &... & 0 \\\\
& & \\ddots & \\ddots & \\ddots & \\\\
0 & 0 & ... & -\\frac{s_{n-2}}{w_{2,n-2}} & 1+\\frac{s_{n-2} + s_{n-1}}{w_{2,{n-2}}} & -\\frac{s_{n-1}}{w_{2,{n-2}}} \\\\
0 & 0 & ... & 0 & -\\frac{s_{n-1}}{w_{2,n-1}} & 1+\\frac{s_{n-1}}{w_{2,n-1}} \\\\
\\end{array} \\right]
where
.. math::
\\begin{array}{lllllll}
K &= [K_0, &K_1, &K_2, &...,&K_{n-1}, &K_{n}] \\\\
w_1 &= [w_{1,0}, &w_{1,1},&w_{1,2},&...,&w_{1,n-1},&w_{1,n}] \\\\
w_2 &= [w_{2,0}, &w_{2,1},&w_{2,2},&...,&w_{2,n-1}]
\\end{array}
and following subsitute:
.. math::
s_i = w_{1,i} K_i
"""
# \\begin{eqnarray}
# y & = & ax^2 + bx + c \\\\
# f(x) & = & x^2 + 2xy + y^2
# \\end{eqnarray}
# .. math::
#
# K &= [K_0, &K_1, &K_2, &... , &K_{n-1}, &K_{n}] \\\\
# w_1 &= [w_{1,0}, &w_{1,1}, &w_{1,2}, &... , &w_{1,n-1}, \\ &w_{1,n}] \\\\
# w_2 &= [w_{2,0}, \\ &w_{2,1}, \\ &w_{2,2}, \\ &... \\ , \\ &w_{2,n-1}] &o \\\\
#
# """
J = K.size - 1
if weight1 is None:
weight1 = np.ones_like(K)
if weight2 is None:
weight2 = np.ones(J)
weightedK = weight1 * K
Ka1 = weightedK[0:J] / weight2
Ka3 = weightedK[1:J+1] / weight2
Ka2 = np.insert(Ka1[1:J], 0, 0) + np.append(Ka3[0:J-1], 0)
# Atmosphere tridiagonal matrix
# this code makes a 3xN matrix, suitable for use with solve_banded
#diag = np.empty((3, J))
#diag[0, 1:] = -Ka3[0:J-1]
#diag[1, :] = 1 + Ka2
#diag[2, 0:J-1] = -Ka1[1:J]
# Build the full banded matrix instead
A = (np.diag(1 + Ka2, k=0) +
np.diag(-Ka3[0:J-1], k=1) +
np.diag(-Ka1[1:J], k=-1))
return A | https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/dynamics/diffusion.py#L208-L300 |
confusion matrix | python | def most_confused(self, min_val:int=1, slice_size:int=1)->Collection[Tuple[str,str,int]]:
"Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences."
cm = self.confusion_matrix(slice_size=slice_size)
np.fill_diagonal(cm, 0)
res = [(self.data.classes[i],self.data.classes[j],cm[i,j])
for i,j in zip(*np.where(cm>=min_val))]
return sorted(res, key=itemgetter(2), reverse=True) | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L186-L192 |
confusion matrix | python | def load_audit_confusion_matrices(filename):
"""
Loads a confusion matrix in a two-level dictionary format.
For example, the confusion matrix of a 75%-accurate model
that predicted 15 values (and mis-classified 5) may look like:
{"A": {"A":10, "B": 5}, "B": {"B":5}}
Note that raw boolean values are translated into strings, such that
a value that was the boolean True will be returned as the string "True".
"""
with open(filename) as audit_file:
audit_file.next() # Skip the first line.
# Extract the confusion matrices and repair levels from the audit file.
confusion_matrices = []
for line in audit_file:
separator = ":"
separator_index = line.index(separator)
comma_index = line.index(',')
repair_level = float(line[separator_index+2:comma_index])
raw_confusion_matrix = line[comma_index+2:-2]
confusion_matrix = json.loads( raw_confusion_matrix.replace("'","\"") )
confusion_matrices.append( (repair_level, confusion_matrix) )
# Sort the repair levels in case they are out of order for whatever reason.
confusion_matrices.sort(key = lambda pair: pair[0])
return confusion_matrices | https://github.com/algofairness/BlackBoxAuditing/blob/b06c4faed5591cd7088475b2a203127bc5820483/python2_source/BlackBoxAuditing/audit_reading.py#L11-L40 |
confusion matrix | python | def confusion_matrix(self, data):
"""
Returns a confusion matrix based of H2O's default prediction threshold for a dataset.
:param data: metric for which the confusion matrix will be calculated.
"""
return {model.model_id: model.confusion_matrix(data) for model in self.models} | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/grid/metrics.py#L609-L615 |
confusion matrix | python | def confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None):
"""
Generates a confusion matrix between rater_a and rater_b
A confusion matrix shows how often 2 values agree and disagree
See quadratic_weighted_kappa for argument descriptions
"""
assert(len(rater_a) == len(rater_b))
rater_a = [int(a) for a in rater_a]
rater_b = [int(b) for b in rater_b]
min_rating = int(min_rating)
max_rating = int(max_rating)
if min_rating is None:
min_rating = min(rater_a)
if max_rating is None:
max_rating = max(rater_a)
num_ratings = int(max_rating - min_rating + 1)
conf_mat = [[0 for i in range(num_ratings)]
for j in range(num_ratings)]
for a, b in zip(rater_a, rater_b):
conf_mat[int(a - min_rating)][int(b - min_rating)] += 1
return conf_mat | https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L387-L407 |
confusion matrix | python | def matrix(self, title=None):
"""
Generates the confusion matrix.
:param title: optional title
:type title: str
:return: the matrix
:rtype: str
"""
if title is None:
return javabridge.call(self.jobject, "toMatrixString", "()Ljava/lang/String;")
else:
return javabridge.call(self.jobject, "toMatrixString", "(Ljava/lang/String;)Ljava/lang/String;", title) | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/classifiers.py#L1255-L1267 |
confusion matrix | python | def from_bigquery(sql):
"""Create a ConfusionMatrix from a BigQuery table or query.
Args:
sql: Can be one of:
A SQL query string.
A Bigquery table string.
A Query object defined with '%%bq query --name [query_name]'.
The query results or table must include "target", "predicted" columns.
Returns:
A ConfusionMatrix that can be plotted.
Raises:
ValueError if query results or table does not include 'target' or 'predicted' columns.
"""
if isinstance(sql, bq.Query):
sql = sql._expanded_sql()
parts = sql.split('.')
if len(parts) == 1 or len(parts) > 3 or any(' ' in x for x in parts):
sql = '(' + sql + ')' # query, not a table name
else:
sql = '`' + sql + '`' # table name
query = bq.Query(
'SELECT target, predicted, count(*) as count FROM %s group by target, predicted' % sql)
df = query.execute().result().to_dataframe()
labels = sorted(set(df['target']) | set(df['predicted']))
labels_count = len(labels)
df['target'] = [labels.index(x) for x in df['target']]
df['predicted'] = [labels.index(x) for x in df['predicted']]
cm = [[0] * labels_count for i in range(labels_count)]
for index, row in df.iterrows():
cm[row['target']][row['predicted']] = row['count']
return ConfusionMatrix(cm, labels) | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L80-L113 |
confusion matrix | python | def confusion_matrix(df, col_true=None, col_pred=None):
"""
Compute confusion matrix of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true label
:type col_true: str
:param col_true: column name of predicted label, 'prediction_result' by default.
:type col_pred: str
:return: Confusion matrix and mapping list for classes
:Example:
>>> predicted = model.predict(input_data)
>>> cm, mapping = confusion_matrix(predicted, 'category')
"""
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_CLASS)
return _run_cm_node(df, col_true, col_pred)[0] | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/ml/metrics/classification.py#L76-L97 |
confusion matrix | python | def diff_aff(self):
"""Symmetric diffusion affinity matrix
Return or calculate the symmetric diffusion affinity matrix
.. math:: A(x,y) = K(x,y) (d(x) d(y))^{-1/2}
where :math:`d` is the degrees (row sums of the kernel.)
Returns
-------
diff_aff : array-like, shape=[n_samples, n_samples]
symmetric diffusion affinity matrix defined as a
doubly-stochastic form of the kernel matrix
"""
row_degrees = np.array(self.kernel.sum(axis=1)).reshape(-1, 1)
col_degrees = np.array(self.kernel.sum(axis=0)).reshape(1, -1)
if sparse.issparse(self.kernel):
return self.kernel.multiply(1 / np.sqrt(row_degrees)).multiply(
1 / np.sqrt(col_degrees))
else:
return (self.kernel / np.sqrt(row_degrees)) / np.sqrt(col_degrees) | https://github.com/KrishnaswamyLab/graphtools/blob/44685352be7df2005d44722903092207967457f2/graphtools/base.py#L513-L535 |
confusion matrix | python | def from_existing(cls, confusion, *args, **kwargs):
"""Creates a confusion matrix from a DataFrame that already contains confusion counts (but not meta stats)
>>> df = pd.DataFrame(np.matrix([[0,1,2,0,1,2,1,2,2,1],[0,1,2,1,2,0,0,1,2,0]]).T, columns=['True', 'Pred'])
>>> c = Confusion(df)
>>> c2 = pd.DataFrame(c)
>>> hasattr(c2, '_binary_sensitivity')
False
>>> c3 = Confusion.from_existing(c2)
>>> hasattr(c3, '_binary_sensitivity')
True
>>> (c3 == c).all().all()
True
>>> c3
Pred 0 1 2
True
0 1 1 0
1 2 1 1
2 1 1 2
"""
# Extremely brute-force to recreate data from a confusion matrix!
df = []
for t, p in product(confusion.index.values, confusion.columns.values):
df += [[t, p]] * confusion[p][t]
if confusion.index.name is not None and confusion.columns.name is not None:
return Confusion(pd.DataFrame(df, columns=[confusion.index.name, confusion.columns.name]))
return Confusion(pd.DataFrame(df)) | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L536-L562 |
confusion matrix | python | def _make_meridional_diffusion_matrix(K, lataxis):
"""Calls :func:`_make_diffusion_matrix` with appropriate weights for
the meridional diffusion case.
:param array K: dimensionless diffusivities at cell boundaries
of diffusion axis ``lataxis``
:param axis lataxis: latitude axis where diffusion is occuring
Weights are computed as the following:
.. math::
\\begin{array}{ll}
w_1 &= \\cos(\\textrm{bounds}) \\\\
&= \\left[ \\cos(b_0), \\cos(b_1), \\cos(b_2), \\ ... \\ , \\cos(b_{n-1}), \\cos(b_n) \\right] \\\\
w_2 &= \\cos(\\textrm{points}) \\\\
&= \\left[ \\cos(p_0), \\cos(p_1), \\cos(p_2), \\ ... \\ , \\cos(p_{n-1}) \\right]
\\end{array}
when bounds and points from ``lataxis`` are written as
.. math::
\\begin{array}{ll}
\\textrm{bounds} &= [b_0, b_1, b_2, \\ ... \\ , b_{n-1}, b_{n}] \\\\
\\textrm{points} &= [p_0, p_1, p_2, \\ ... \\ , p_{n-1}]
\\end{array}
Giving this input to :func:`_make_diffusion_matrix` results in a matrix like:
.. math::
\\textrm{diffTriDiag}=
\\left[ \\begin{array}{cccccc}
1+\\frac{u_1 }{\\cos(p_0)} & -\\frac{u_1}{\\cos(p_0)} & 0 & & ... & 0 \\\\
-\\frac{u_1}{\\cos(p_1)} & 1+\\frac{u_1 + u_2}{\\cos(p_1)} & -\\frac{u_2}{\\cos(b_1)} & 0 & ... & 0 \\\\
0 & -\\frac{u_2}{\\cos(p_2)} & 1+\\frac{u_2 + u_3}{\\cos(p_2)} & -\\frac{u_3}{\\cos(p_2)} &... & 0 \\\\
& & \\ddots & \\ddots & \\ddots & \\\\
0 & 0 & ... & -\\frac{u_{n-2}}{\\cos(p_{n-2})} & 1+\\frac{u_{n-2} + u_{n-1}}{\\cos(p_{n-2})} & -\\frac{u_{n-1}}{\\cos(p_{n-2})} \\\\
0 & 0 & ... & 0 & -\\frac{u_{n-1}}{\\cos(p_{n-1})} & 1+\\frac{u_{n-1}}{\\cos(p_{n-1})} \\\\
\\end{array} \\right]
with the substitue of:
.. math::
u_i = \\cos(b_i) K_i
"""
phi_stag = np.deg2rad(lataxis.bounds)
phi = np.deg2rad(lataxis.points)
weight1 = np.cos(phi_stag)
weight2 = np.cos(phi)
diag = _make_diffusion_matrix(K, weight1, weight2)
return diag, weight1, weight2 | https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/dynamics/diffusion.py#L303-L357 |
confusion matrix | python | def confusion_matrix(self, metrics=None, thresholds=None, train=False, valid=False, xval=False):
"""
Get the confusion matrix for the specified metrics/thresholds.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
"valid", and "xval".
:param metrics: A list of metrics or a single metric among ``"min_per_class_accuracy"``, ``"absolute_mcc"``,
``"tnr"``, ``"fnr"``, ``"fpr"``, ``"tpr"``, ``"precision"``, ``"accuracy"``, ``"f0point5"``, ``"f2"``,
``"f1"``.
:param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds
in this set of metrics will be used.
:param bool train: If train is True, then return the confusion matrix value for the training data.
:param bool valid: If valid is True, then return the confusion matrix value for the validation data.
:param bool xval: If xval is True, then return the confusion matrix value for the cross validation data.
:returns: The confusion matrix for this binomial model.
"""
return {model.model_id: model.confusion_matrix(metrics, thresholds, train, valid, xval) for model in
self.models} | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/grid/metrics.py#L388-L407 |
confusion matrix | python | def cublasZgbmv(handle, trans, m, n, kl, ku, alpha, A, lda,
x, incx, beta, y, incy):
"""
Matrix-vector product for complex general banded matrix.
"""
status = _libcublas.cublasZgbmv_v2(handle,
trans, m, n, kl, ku,
ctypes.byref(cuda.cuDoubleComplex(alpha.real,
alpha.imag)),
int(A), lda, int(x), incx,
ctypes.byref(cuda.cuDoubleComplex(beta.real,
beta.imag)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2163-L2178 |
confusion matrix | python | def confusion_to_mcc(*args):
"""Convert the confusion matrix to the Matthews correlation coefficient
Parameters:
-----------
cm : ndarray
2x2 confusion matrix with np.array([[tn, fp], [fn, tp]])
tn, fp, fn, tp : float
four scalar variables
- tn : number of true negatives
- fp : number of false positives
- fn : number of false negatives
- tp : number of true positives
Return:
-------
r : float
Matthews correlation coefficient
"""
if len(args) is 1:
tn, fp, fn, tp = args[0].ravel().astype(float)
elif len(args) is 4:
tn, fp, fn, tp = [float(a) for a in args]
else:
raise Exception((
"Input argument is not an 2x2 matrix, "
"nor 4 elements tn, fp, fn, tp."))
return (tp * tn - fp * fn) / np.sqrt(
(tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) | https://github.com/kmedian/korr/blob/4eb86fc14b1fc1b69204069b7753d115b327c937/korr/mcc.py#L6-L36 |
confusion matrix | python | def matrix_directed_unweighted(user):
"""
Returns a directed, unweighted matrix where an edge exists if there is at
least one call or text.
"""
matrix = _interaction_matrix(user, interaction=None)
for a in range(len(matrix)):
for b in range(len(matrix)):
if matrix[a][b] is not None and matrix[a][b] > 0:
matrix[a][b] = 1
return matrix | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L124-L135 |
confusion matrix | python | def cublasZsymv(handle, uplo, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for complex symmetric matrix.
"""
status = _libcublas.cublasZsymv_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctypes.byref(cuda.cuDoubleComplex(alpha.real,
alpha.imag)),
int(A), lda, int(x), incx,
ctypes.byref(cuda.cuDoubleComplex(beta.real,
beta.imag)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2788-L2802 |
confusion matrix | python | def confusion_matrix(self, data):
"""
Returns a confusion matrix based of H2O's default prediction threshold for a dataset.
:param H2OFrame data: the frame with the prediction results for which the confusion matrix should be extracted.
"""
assert_is_type(data, H2OFrame)
j = h2o.api("POST /3/Predictions/models/%s/frames/%s" % (self._id, data.frame_id))
return j["model_metrics"][0]["cm"]["table"] | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/multinomial.py#L18-L26 |
confusion matrix | python | def cublasZgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for complex general matrix.
"""
status = _libcublas.cublasZgemv_v2(handle,
_CUBLAS_OP[trans], m, n,
ctypes.byref(cuda.cuDoubleComplex(alpha.real,
alpha.imag)),
int(A), lda, int(x), incx,
ctypes.byref(cuda.cuDoubleComplex(beta.real,
beta.imag)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2335-L2349 |
confusion matrix | python | def from_csv(input_csv, headers=None, schema_file=None):
"""Create a ConfusionMatrix from a csv file.
Args:
input_csv: Path to a Csv file (with no header). Can be local or GCS path.
headers: Csv headers. If present, it must include 'target' and 'predicted'.
schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None.
If present, it must include 'target' and 'predicted' columns.
Returns:
A ConfusionMatrix that can be plotted.
Raises:
ValueError if both headers and schema_file are None, or it does not include 'target'
or 'predicted' columns.
"""
if headers is not None:
names = headers
elif schema_file is not None:
with _util.open_local_or_gcs(schema_file, mode='r') as f:
schema = json.load(f)
names = [x['name'] for x in schema]
else:
raise ValueError('Either headers or schema_file is needed')
all_files = _util.glob_files(input_csv)
all_df = []
for file_name in all_files:
with _util.open_local_or_gcs(file_name, mode='r') as f:
all_df.append(pd.read_csv(f, names=names))
df = pd.concat(all_df, ignore_index=True)
if 'target' not in df or 'predicted' not in df:
raise ValueError('Cannot find "target" or "predicted" column')
labels = sorted(set(df['target']) | set(df['predicted']))
cm = confusion_matrix(df['target'], df['predicted'], labels=labels)
return ConfusionMatrix(cm, labels) | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_confusion_matrix.py#L41-L77 |
confusion matrix | python | def cublasZgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for complex general matrix.
"""
status = _libcublas.cublasZgemm_v2(handle,
_CUBLAS_OP[transa],
_CUBLAS_OP[transb], m, n, k,
ctypes.byref(cuda.cuDoubleComplex(alpha.real,
alpha.imag)),
int(A), lda, int(B), ldb,
ctypes.byref(cuda.cuDoubleComplex(beta.real,
beta.imag)),
int(C), ldc)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L4010-L4025 |
confusion matrix | python | def flux_matrix(T, pi, qminus, qplus, netflux=True):
r"""Compute the flux.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix
pi : (M,) ndarray
Stationary distribution corresponding to T
qminus : (M,) ndarray
Backward comittor
qplus : (M,) ndarray
Forward committor
netflux : boolean
True: net flux matrix will be computed
False: gross flux matrix will be computed
Returns
-------
flux : (M, M) scipy.sparse matrix
Matrix of flux values between pairs of states.
"""
D1 = diags((pi * qminus,), (0,))
D2 = diags((qplus,), (0,))
flux = D1.dot(T.dot(D2))
"""Remove self-fluxes"""
flux = flux - diags(flux.diagonal(), 0)
"""Return net or gross flux"""
if netflux:
return to_netflux(flux)
else:
return flux | https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/flux/sparse/tpt.py#L70-L105 |
confusion matrix | python | def cublasZtpmv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Matrix-vector product for complex triangular-packed matrix.
"""
status = _libcublas.cublasZtpmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
n, int(AP), int(x), incx)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3260-L3271 |
confusion matrix | python | def matrix(
m, n, lst,
m_text: list=None,
n_text: list=None):
"""
m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x|
"""
fmt = ""
if n_text:
fmt += " {}\n".format(" ".join(n_text))
for i in range(1, m+1):
if m_text:
fmt += "{:<4.4} ".format(m_text[i-1])
fmt += "|"
for j in range(1, n+1):
if (i, j) in lst:
fmt += "x|"
else:
fmt += " |"
fmt += "\n"
return fmt | https://github.com/PhilippeFerreiraDeSousa/bitext-matching/blob/195c3e98775cfa5e63e4bb0bb1da6f741880d980/lib/enpc_aligner/IBM2_func.py#L104-L131 |
confusion matrix | python | def diagonalize_collision_matrix(collision_matrices,
i_sigma=None,
i_temp=None,
pinv_solver=0,
log_level=0):
"""Diagonalize collision matrices.
Note
----
collision_matricies is overwritten by eigenvectors.
Parameters
----------
collision_matricies : ndarray, optional
Collision matrix. This ndarray has to have the following size and
flags.
shapes:
(sigmas, temperatures, prod(mesh), num_band, prod(mesh), num_band)
(sigmas, temperatures, ir_grid_points, num_band, 3,
ir_grid_points, num_band, 3)
(size, size)
dtype='double', order='C'
i_sigma : int, optional
Index of BZ integration methods, tetrahedron method and smearing
method with widths. Default is None.
i_temp : int, optional
Index of temperature. Default is None.
pinv_solver : int, optional
Diagnalization solver choice.
log_level : int, optional
Verbosity level. Smaller is more quiet. Default is 0.
Returns
-------
w : ndarray, optional
Eigenvalues.
shape=(size_of_collision_matrix,), dtype='double'
"""
start = time.time()
# Matrix size of collision matrix to be diagonalized.
# The following value is expected:
# ir-colmat: num_ir_grid_points * num_band * 3
# red-colmat: num_mesh_points * num_band
shape = collision_matrices.shape
if len(shape) == 6:
size = shape[2] * shape[3]
assert size == shape[4] * shape[5]
elif len(shape) == 8:
size = np.prod(shape[2:5])
assert size == np.prod(shape[5:8])
elif len(shape) == 2:
size = shape[0]
assert size == shape[1]
solver = _select_solver(pinv_solver)
# [1] dsyev: safer and slower than dsyevd and smallest memory usage
# [2] dsyevd: faster than dsyev and largest memory usage
if solver in [1, 2]:
if log_level:
routine = ['dsyev', 'dsyevd'][solver - 1]
sys.stdout.write("Diagonalizing by lapacke %s... " % routine)
sys.stdout.flush()
import phono3py._phono3py as phono3c
w = np.zeros(size, dtype='double')
if i_sigma is None:
_i_sigma = 0
else:
_i_sigma = i_sigma
if i_temp is None:
_i_temp = 0
else:
_i_temp = i_temp
phono3c.diagonalize_collision_matrix(collision_matrices,
w,
_i_sigma,
_i_temp,
0.0,
(solver + 1) % 2,
0) # only diagonalization
elif solver == 3: # np.linalg.eigh depends on dsyevd.
if log_level:
sys.stdout.write("Diagonalizing by np.linalg.eigh... ")
sys.stdout.flush()
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, col_mat[:] = np.linalg.eigh(col_mat)
elif solver == 4: # fully scipy dsyev
if log_level:
sys.stdout.write("Diagonalizing by "
"scipy.linalg.lapack.dsyev... ")
sys.stdout.flush()
import scipy.linalg
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, _, info = scipy.linalg.lapack.dsyev(col_mat.T, overwrite_a=1)
elif solver == 5: # fully scipy dsyevd
if log_level:
sys.stdout.write("Diagonalizing by "
"scipy.linalg.lapack.dsyevd... ")
sys.stdout.flush()
import scipy.linalg
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, _, info = scipy.linalg.lapack.dsyevd(col_mat.T, overwrite_a=1)
if log_level:
print("[%.3fs]" % (time.time() - start))
sys.stdout.flush()
return w | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/conductivity_LBTE.py#L609-L724 |
confusion matrix | python | def transitions(self):
"""Transition matrix (sparse matrix).
Is conjugate to the symmetrized transition matrix via::
self.transitions = self.Z * self.transitions_sym / self.Z
where ``self.Z`` is the diagonal matrix storing the normalization of the
underlying kernel matrix.
Notes
-----
This has not been tested, in contrast to `transitions_sym`.
"""
if issparse(self.Z):
Zinv = self.Z.power(-1)
else:
Zinv = np.diag(1./np.diag(self.Z))
return self.Z.dot(self.transitions_sym).dot(Zinv) | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/neighbors/__init__.py#L512-L530 |
confusion matrix | python | def cublasCgbmv(handle, trans, m, n, kl, ku, alpha, A, lda,
x, incx, beta, y, incy):
"""
Matrix-vector product for complex general banded matrix.
"""
status = _libcublas.cublasCgbmv_v2(handle,
trans, m, n, kl, ku,
ctypes.byref(cuda.cuFloatComplex(alpha.real,
alpha.imag)),
int(A), lda, int(x), incx,
ctypes.byref(cuda.cuFloatComplex(beta.real,
beta.imag)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2132-L2147 |
confusion matrix | python | def confusion_matrix(y_true, y_pred, target_names=None, normalize=False,
cmap=None, ax=None):
"""
Plot confustion matrix.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_pred : array-like, shape = [n_samples]
Target predicted classes (estimator predictions).
target_names : list
List containing the names of the target classes. List must be in order
e.g. ``['Label for class 0', 'Label for class 1']``. If ``None``,
generic labels will be generated e.g. ``['Class 0', 'Class 1']``
ax: matplotlib Axes
Axes object to draw the plot onto, otherwise uses current Axes
normalize : bool
Normalize the confusion matrix
cmap : matplotlib Colormap
If ``None`` uses a modified version of matplotlib's OrRd colormap.
Returns
-------
ax: matplotlib Axes
Axes containing the plot
Examples
--------
.. plot:: ../../examples/confusion_matrix.py
"""
if any((val is None for val in (y_true, y_pred))):
raise ValueError("y_true and y_pred are needed to plot confusion "
"matrix")
# calculate how many names you expect
values = set(y_true).union(set(y_pred))
expected_len = len(values)
if target_names and (expected_len != len(target_names)):
raise ValueError(('Data cointains {} different values, but target'
' names contains {} values.'.format(expected_len,
len(target_names)
)))
# if the user didn't pass target_names, create generic ones
if not target_names:
values = list(values)
values.sort()
target_names = ['Class {}'.format(v) for v in values]
cm = sk_confusion_matrix(y_true, y_pred)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
np.set_printoptions(precision=2)
if ax is None:
ax = plt.gca()
# this (y, x) may sound counterintuitive. The reason is that
# in a matrix cell (i, j) is in row=i and col=j, translating that
# to an x, y plane (which matplotlib uses to plot), we need to use
# i as the y coordinate (how many steps down) and j as the x coordinate
# how many steps to the right.
for (y, x), v in np.ndenumerate(cm):
try:
label = '{:.2}'.format(v)
except:
label = v
ax.text(x, y, label, horizontalalignment='center',
verticalalignment='center')
if cmap is None:
cmap = default_heatmap()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
plt.colorbar(im, ax=ax)
tick_marks = np.arange(len(target_names))
ax.set_xticks(tick_marks)
ax.set_xticklabels(target_names)
ax.set_yticks(tick_marks)
ax.set_yticklabels(target_names)
title = 'Confusion matrix'
if normalize:
title += ' (normalized)'
ax.set_title(title)
ax.set_ylabel('True label')
ax.set_xlabel('Predicted label')
return ax | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/plot/classification.py#L13-L105 |
confusion matrix | python | def cublasZgerc(handle, m, n, alpha, x, incx, y, incy, A, lda):
"""
Rank-1 operation on complex general matrix.
"""
status = _libcublas.cublasZgerc_v2(handle,
m, n, ctypes.byref(cuda.cuDoubleComplex(alpha.real,
alpha.imag)),
int(x), incx, int(y), incy, int(A), lda)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2457-L2467 |
confusion matrix | python | def confusion_matrix(expected: np.ndarray, predicted: np.ndarray, num_classes: int) -> np.ndarray:
"""
Calculate and return confusion matrix for the predicted and expected labels
:param expected: array of expected classes (integers) with shape `[num_of_data]`
:param predicted: array of predicted classes (integers) with shape `[num_of_data]`
:param num_classes: number of classification classes
:return: confusion matrix (cm) with absolute values
"""
assert np.issubclass_(expected.dtype.type, np.integer), " Classes' indices must be integers"
assert np.issubclass_(predicted.dtype.type, np.integer), " Classes' indices must be integers"
assert expected.shape == predicted.shape, "Predicted and expected data must be the same length"
assert num_classes > np.max([predicted, expected]), \
"Number of classes must be at least the number of indices in predicted/expected data"
assert np.min([predicted, expected]) >= 0, " Classes' indices must be positive integers"
cm_abs = np.zeros((num_classes, num_classes), dtype=np.int32)
for pred, exp in zip(predicted, expected):
cm_abs[exp, pred] += 1
return cm_abs | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/confusion_matrix.py#L4-L22 |
confusion matrix | python | def cublasCtpmv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Matrix-vector product for complex triangular-packed matrix.
"""
status = _libcublas.cublasCtpmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
n, int(AP), int(x), incx)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3216-L3227 |
confusion matrix | python | def confusion_matrix_and_correct_series(self, y_info):
''' Generate confusion matrix from y_info '''
a = deepcopy(y_info['true'])
true_count = dict((i, a.count(i)) for i in set(a))
a = deepcopy(y_info['pred'])
pred_count = dict((i, a.count(i)) for i in set(a))
sorted_cats = sorted(list(set(y_info['true'] + y_info['pred'])))
conf_mat = confusion_matrix(y_info['true'], y_info['pred'], sorted_cats)
df_conf = pd.DataFrame(conf_mat, index=sorted_cats, columns=sorted_cats)
total_correct = np.trace(df_conf)
total_pred = df_conf.sum().sum()
fraction_correct = total_correct/float(total_pred)
# calculate ser_correct
correct_list = []
cat_counts = df_conf.sum(axis=1)
all_cols = df_conf.columns.tolist()
for inst_cat in all_cols:
inst_correct = df_conf[inst_cat].loc[inst_cat] / cat_counts[inst_cat]
correct_list.append(inst_correct)
ser_correct = pd.Series(data=correct_list, index=all_cols)
populations = {}
populations['true'] = true_count
populations['pred'] = pred_count
return df_conf, populations, ser_correct, fraction_correct | https://github.com/ismms-himc/clustergrammer2/blob/5acea9bff7eda546cf0647b9e3647f631eb6f5f5/clustergrammer2/clustergrammer_fun/__init__.py#L793-L825 |
confusion matrix | python | def cublasCsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for complex symmetric matrix.
"""
status = _libcublas.cublasCsymm_v2(handle,
_CUBLAS_SIDE_MODE[side],
_CUBLAS_FILL_MODE[uplo],
m, n, ctypes.byref(cuda.cuFloatComplex(alpha.real,
alpha.imag)),
int(A), lda, int(B), ldb,
ctypes.byref(cuda.cuFloatComplex(beta.real,
beta.imag)),
int(C), ldc)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L4101-L4116 |
confusion matrix | python | def matrix_undirected_weighted(user, interaction=None):
"""
Returns an undirected, weighted matrix for call, text and call duration
where an edge exists if the relationship is reciprocated.
"""
matrix = _interaction_matrix(user, interaction=interaction)
result = [[0 for _ in range(len(matrix))] for _ in range(len(matrix))]
for a in range(len(matrix)):
for b in range(len(matrix)):
if a != b and matrix[a][b] and matrix[b][a]:
result[a][b] = matrix[a][b] + matrix[b][a]
elif matrix[a][b] is None or matrix[b][a] is None:
result[a][b] = None
else:
result[a][b] = 0
return result | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L138-L155 |
confusion matrix | python | def view_conflicts(L, normalize=True, colorbar=True):
"""Display an [m, m] matrix of conflicts"""
L = L.todense() if sparse.issparse(L) else L
C = _get_conflicts_matrix(L, normalize=normalize)
plt.imshow(C, aspect="auto")
plt.title("Conflicts")
if colorbar:
plt.colorbar()
plt.show() | https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/visualization/analysis.py#L35-L43 |
confusion matrix | python | def cublasCgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for complex general matrix.
"""
status = _libcublas.cublasCgemv_v2(handle,
_CUBLAS_OP[trans], m, n,
ctypes.byref(cuda.cuFloatComplex(alpha.real,
alpha.imag)),
int(A), lda, int(x), incx,
ctypes.byref(cuda.cuFloatComplex(beta.real,
beta.imag)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2306-L2320 |
confusion matrix | python | def confusion_performance(mat, fn):
"""Apply a performance function to a confusion matrix
:param mat: confusion matrix
:type mat: square matrix
:param function fn: performance function
"""
if mat.shape[0] != mat.shape[1] or mat.shape < (2, 2):
raise TypeError('{} is not a confusion matrix'.format(mat))
elif mat.shape == (2, 2):
return fn(mat[TP], mat[TN], mat[FP], mat[FN])
res = numpy.empty(mat.shape[0])
for i in range(len(res)):
res[i] = fn(mat[i, i], # TP
sum(mat) - sum(mat[:, i]) - sum(mat[i, :]), # TN
sum(mat[:, i]) - mat[i, i], # FP
sum(mat[i, :]) - mat[i, i]) # FN
return res | https://github.com/childsish/lhc-python/blob/0a669f46a40a39f24d28665e8b5b606dc7e86beb/lhc/misc/performance_measures.py#L176-L193 |
confusion matrix | python | def cublasCtrmv(handle, uplo, trans, diag, n, A, lda, x, incx):
"""
Matrix-vector product for complex triangular matrix.
"""
status = _libcublas.cublasCtrmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
n, int(A), lda, int(x), incx)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3397-L3408 |
confusion matrix | python | def draw(self):
"""
Renders the classification report; must be called after score.
"""
# Perform display related manipulations on the confusion matrix data
cm_display = self.confusion_matrix_
# Convert confusion matrix to percent of each row, i.e. the
# predicted as a percent of true in each class.
if self.percent == True:
# Note: div_safe function returns 0 instead of NAN.
cm_display = div_safe(self.confusion_matrix_, self.class_counts_.reshape(-1,1))
cm_display = np.round(cm_display* 100, decimals=0)
# Y axis should be sorted top to bottom in pcolormesh
cm_display = cm_display[::-1,::]
# Set up the dimensions of the pcolormesh
n_classes = len(self.classes_)
X, Y = np.arange(n_classes+1), np.arange(n_classes+1)
self.ax.set_ylim(bottom=0, top=cm_display.shape[0])
self.ax.set_xlim(left=0, right=cm_display.shape[1])
# Fetch the grid labels from the classes in correct order; set ticks.
xticklabels = self.classes_
yticklabels = self.classes_[::-1]
ticks = np.arange(n_classes) + 0.5
self.ax.set(xticks=ticks, yticks=ticks)
self.ax.set_xticklabels(xticklabels, rotation="vertical", fontsize=self.fontsize)
self.ax.set_yticklabels(yticklabels, fontsize=self.fontsize)
# Set data labels in the grid enumerating over all x,y class pairs.
# NOTE: X and Y are one element longer than the confusion matrix, so
# skip the last element in the enumeration to label grids.
for x in X[:-1]:
for y in Y[:-1]:
# Extract the value and the text label
value = cm_display[x,y]
svalue = "{:0.0f}".format(value)
if self.percent:
svalue += "%"
# Determine the grid and text colors
base_color = self.cmap(value / cm_display.max())
text_color = find_text_color(base_color)
# Make zero values more subtle
if cm_display[x,y] == 0:
text_color = CMAP_MUTEDCOLOR
# Add the label to the middle of the grid
cx, cy = x+0.5, y+0.5
self.ax.text(
cy, cx, svalue, va='center', ha='center',
color=text_color, fontsize=self.fontsize,
)
# Add a dark line on the grid with the diagonal. Note that the
# tick labels have already been reversed.
lc = 'k' if xticklabels[x] == yticklabels[y] else 'w'
self._edgecolors.append(lc)
# Draw the heatmap with colors bounded by vmin,vmax
vmin = 0.00001
vmax = 99.999 if self.percent == True else cm_display.max()
self.ax.pcolormesh(
X, Y, cm_display, vmin=vmin, vmax=vmax,
edgecolor=self._edgecolors, cmap=self.cmap, linewidth='0.01'
)
# Return the axes being drawn on
return self.ax | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/confusion_matrix.py#L196-L271 |
confusion matrix | python | def _conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False):
"""
Most efficient routine to project L independent latent gps through a mixing matrix W.
The mixing matrix is a member of the `SeparateMixedMok` and has shape P x L.
The covariance matrices used to calculate the conditional have the following shape:
- Kuu: L x M x M
- Kuf: L x M x N
- Kff: L x N or L x N x N
Further reference
-----------------
- See `gpflow.conditionals._conditional` for a detailed explanation of
conditional in the single-output case.
- See the multiouput notebook for more information about the multiouput framework.
"""
logger.debug("conditional: (MixedKernelSharedMof, MixedKernelSeparateMof), SeparateMixedMok")
with params_as_tensors_for(feat, kern):
independent_cond = conditional.dispatch(object, SeparateIndependentMof, SeparateIndependentMok, object)
gmu, gvar = independent_cond(Xnew, feat, kern, f, full_cov=full_cov, q_sqrt=q_sqrt,
full_output_cov=False, white=white) # N x L, L x N x N or N x L
return _mix_latent_gp(kern.W, gmu, gvar, full_cov, full_output_cov) | https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/multioutput/conditionals.py#L214-L236 |
confusion matrix | python | def matrix(ctx, scenario_name, subcommand): # pragma: no cover
"""
List matrix of steps used to test instances.
"""
args = ctx.obj.get('args')
command_args = {
'subcommand': subcommand,
}
s = scenarios.Scenarios(
base.get_configs(args, command_args), scenario_name)
s.print_matrix() | https://github.com/ansible/molecule/blob/766dc35b0b0ce498cd5e3a62b40f828742d0d08c/molecule/command/matrix.py#L71-L83 |
confusion matrix | python | def cublasZtrmm(handle, side, uplo, trans, diag, m, n, alpha, A, lda, B, ldb, C, ldc):
"""
Matrix-matrix product for complex triangular matrix.
"""
status = _libcublas.cublasZtrmm_v2(handle,
_CUBLAS_SIDE_MODE[side],
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
m, n, ctypes.byref(cuda.cuDoubleComplex(alpha.real,
alpha.imag)),
int(A), lda, int(B), ldb, int(C), ldc)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L4492-L4506 |
confusion matrix | python | def cublasCsymv(handle, uplo, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for complex symmetric matrix.
"""
status = _libcublas.cublasCsymv_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctypes.byref(cuda.cuFloatComplex(alpha.real,
alpha.imag)),
int(A), lda, int(x), incx,
ctypes.byref(cuda.cuFloatComplex(beta.real,
beta.imag)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2760-L2774 |
confusion matrix | python | def _implicit_solver(self):
"""Invertes and solves the matrix problem for diffusion matrix
and temperature T.
The method is called by the
:func:`~climlab.process.implicit.ImplicitProcess._compute()` function
of the :class:`~climlab.process.implicit.ImplicitProcess` class and
solves the matrix problem
.. math::
A \\cdot T_{\\textrm{new}} = T_{\\textrm{old}}
for diffusion matrix A and corresponding temperatures.
:math:`T_{\\textrm{old}}` is in this case the current state variable
which already has been adjusted by the explicit processes.
:math:`T_{\\textrm{new}}` is the new state of the variable. To
derive the temperature tendency of the diffusion process the adjustment
has to be calculated and muliplied with the timestep which is done by
the :func:`~climlab.process.implicit.ImplicitProcess._compute()`
function of the :class:`~climlab.process.implicit.ImplicitProcess`
class.
This method calculates the matrix inversion for every state variable
and calling either :func:`solve_implicit_banded()` or
:py:func:`numpy.linalg.solve()` dependent on the flag
``self.use_banded_solver``.
:ivar dict state: method uses current state variables
but does not modify them
:ivar bool use_banded_solver: input flag whether to use
:func:`_solve_implicit_banded()` or
:py:func:`numpy.linalg.solve()` to do
the matrix inversion
:ivar array _diffTriDiag: the diffusion matrix which is given
with the current state variable to
the method solving the matrix problem
"""
#if self.update_diffusivity:
# Time-stepping the diffusion is just inverting this matrix problem:
newstate = {}
for varname, value in self.state.items():
if self.use_banded_solver:
newvar = _solve_implicit_banded(value, self._diffTriDiag)
else:
newvar = np.linalg.solve(self._diffTriDiag, value)
newstate[varname] = newvar
return newstate | https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/dynamics/diffusion.py#L143-L192 |
confusion matrix | python | def confusion_matrix(model, X, y, ax=None, classes=None, sample_weight=None,
percent=False, label_encoder=None, cmap='YlOrRd',
fontsize=None, random_state=None, **kwargs):
"""Quick method:
Creates a heatmap visualization of the sklearn.metrics.confusion_matrix().
A confusion matrix shows each combination of the true and predicted
classes for a test data set.
The default color map uses a yellow/orange/red color scale. The user can
choose between displaying values as the percent of true (cell value
divided by sum of row) or as direct counts. If percent of true mode is
selected, 100% accurate predictions are highlighted in green.
Requires a classification model.
Parameters
----------
model : estimator
Must be a classifier, otherwise raises YellowbrickTypeError
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features.
y : ndarray or Series of length n
An array or series of target or class values.
ax : matplotlib Axes, default: None
The axes to plot the figure on. If None is passed in the current axes
will be used (or generated if required).
sample_weight: array-like of shape = [n_samples], optional
Passed to ``confusion_matrix`` to weight the samples.
percent: bool, default: False
Determines whether or not the confusion_matrix is displayed as counts
or as a percent of true predictions. Note, if specifying a subset of
classes, percent should be set to False or inaccurate figures will be
displayed.
classes : list, default: None
a list of class names to use in the confusion_matrix.
This is passed to the ``labels`` parameter of
``sklearn.metrics.confusion_matrix()``, and follows the behaviour
indicated by that function. It may be used to reorder or select a
subset of labels. If None, classes that appear at least once in
``y_true`` or ``y_pred`` are used in sorted order.
label_encoder : dict or LabelEncoder, default: None
When specifying the ``classes`` argument, the input to ``fit()``
and ``score()`` must match the expected labels. If the ``X`` and ``y``
datasets have been encoded prior to training and the labels must be
preserved for the visualization, use this argument to provide a
mapping from the encoded class to the correct label. Because typically
a Scikit-Learn ``LabelEncoder`` is used to perform this operation, you
may provide it directly to the class to utilize its fitted encoding.
cmap : string, default: ``'YlOrRd'``
Specify a colormap to define the heatmap of the predicted class
against the actual class in the confusion matrix.
fontsize : int, default: None
Specify the fontsize of the text in the grid and labels to make the
matrix a bit easier to read. Uses rcParams font size by default.
random_state : int, RandomState instance or None, optional (default=None)
Passes a random state parameter to the train_test_split function.
Returns
-------
ax : matplotlib axes
Returns the axes that the classification report was drawn on.
"""
# Instantiate the visualizer
visualizer = ConfusionMatrix(
model, ax, classes, sample_weight, percent,
label_encoder, cmap, fontsize, **kwargs
)
# Create the train and test splits
# TODO: determine how to use quick methods that require train and test data.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=random_state
)
# Fit and transform the visualizer (calls draw)
visualizer.fit(X_train, y_train, **kwargs)
visualizer.score(X_test, y_test)
# Return the axes object on the visualizer
return visualizer.ax | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/confusion_matrix.py#L284-L374 |
confusion matrix | python | def concat(mats):
"""Concatenate Matrix objects. Tries either axis.
Parameters
----------
mats: list
list of Matrix objects
Returns
-------
Matrix : Matrix
"""
for mat in mats:
if mat.isdiagonal:
raise NotImplementedError("concat not supported for diagonal mats")
row_match = True
col_match = True
for mat in mats[1:]:
if sorted(mats[0].row_names) != sorted(mat.row_names):
row_match = False
if sorted(mats[0].col_names) != sorted(mat.col_names):
col_match = False
if not row_match and not col_match:
raise Exception("mat_handler.concat(): all Matrix objects"+\
"must share either rows or cols")
if row_match and col_match:
raise Exception("mat_handler.concat(): all Matrix objects"+\
"share both rows and cols")
if row_match:
row_names = copy.deepcopy(mats[0].row_names)
col_names = []
for mat in mats:
col_names.extend(copy.deepcopy(mat.col_names))
x = mats[0].newx.copy()
for mat in mats[1:]:
mat.align(mats[0].row_names, axis=0)
other_x = mat.newx
x = np.append(x, other_x, axis=1)
else:
col_names = copy.deepcopy(mats[0].col_names)
row_names = []
for mat in mats:
row_names.extend(copy.deepcopy(mat.row_names))
x = mats[0].newx.copy()
for mat in mats[1:]:
mat.align(mats[0].col_names, axis=1)
other_x = mat.newx
x = np.append(x, other_x, axis=0)
return Matrix(x=x, row_names=row_names, col_names=col_names) | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/mat/mat_handler.py#L67-L119 |
confusion matrix | python | def matrix(self):
"""The current calibration matrix for this device.
Returns:
(bool, (float, float, float, float, float, float)): :obj:`False` if
no calibration is set and
the returned matrix is the identity matrix, :obj:`True`
otherwise. :obj:`tuple` representing the first two rows of
a 3x3 matrix as described in :meth:`set_matrix`.
"""
matrix = (c_float * 6)()
rc = self._libinput.libinput_device_config_calibration_get_matrix(
self._handle, matrix)
return rc, tuple(matrix) | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L540-L554 |
confusion matrix | python | def cublasDtpmv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Matrix-vector product for real triangular-packed matrix.
"""
status = _libcublas.cublasDtpmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
n, int(AP), int(x), incx)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3238-L3249 |
confusion matrix | python | def s2dctmat(nfilt,ncep,freqstep):
"""Return the 'legacy' not-quite-DCT matrix used by Sphinx"""
melcos = numpy.empty((ncep, nfilt), 'double')
for i in range(0,ncep):
freq = numpy.pi * float(i) / nfilt
melcos[i] = numpy.cos(freq * numpy.arange(0.5, float(nfilt)+0.5, 1.0, 'double'))
melcos[:,0] = melcos[:,0] * 0.5
return melcos | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L146-L153 |
confusion matrix | python | def matrix(matrix, xlabel=None, ylabel=None, xticks=None, yticks=None,
title=None, colorbar_shrink=0.5, color_map=None, show=None,
save=None, ax=None):
"""Plot a matrix."""
if ax is None: ax = pl.gca()
img = ax.imshow(matrix, cmap=color_map)
if xlabel is not None: ax.set_xlabel(xlabel)
if ylabel is not None: ax.set_ylabel(ylabel)
if title is not None: ax.set_title(title)
if xticks is not None:
ax.set_xticks(range(len(xticks)), xticks, rotation='vertical')
if yticks is not None:
ax.set_yticks(range(len(yticks)), yticks)
pl.colorbar(img, shrink=colorbar_shrink, ax=ax) # need a figure instance for colorbar
savefig_or_show('matrix', show=show, save=save) | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_utils.py#L27-L41 |
confusion matrix | python | def freivalds(A, B, C):
"""Tests matrix product AB=C by Freivalds
:param A: n by n numerical matrix
:param B: same
:param C: same
:returns: False with high probability if AB != C
:complexity:
:math:`O(n^2)`
"""
n = len(A)
x = [randint(0, 1000000) for j in range(n)]
return mult(A, mult(B, x)) == mult(C, x) | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/freivalds.py#L36-L49 |
confusion matrix | python | def conjugate(self):
"""The element-wise conjugate matrix
This is defined only if all the entries in the matrix have a defined
conjugate (i.e., they have a `conjugate` method). This is *not* the
case for a matrix of operators. In such a case, only an
:meth:`elementwise` :func:`adjoint` would be applicable, but this is
mathematically different from a complex conjugate.
Raises:
NoConjugateMatrix: if any entries have no `conjugate` method
"""
try:
return Matrix(np_conjugate(self.matrix))
except AttributeError:
raise NoConjugateMatrix(
"Matrix %s contains entries that have no defined "
"conjugate" % str(self)) | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/matrix_algebra.py#L167-L184 |
confusion matrix | python | def refresh_meta(self):
"""Calculations that only depend on aggregate counts in Confusion Matrix go here"""
# these calcs are duplicated in __init__()
setattr(self, '_num_classes', len(self.index))
setattr(self, '_colnums', np.arange(0, self._num_classes))
try:
setattr(self, '_neg_label',
next(label for label in self.columns if str(label).strip().lower()[0] in ('-nh0')))
except StopIteration:
setattr(self, '_neg_label', self.columns[-1])
try:
setattr(self, '_pos_label', next(label for label in self.columns if label != self._neg_label))
except StopIteration:
setattr(self, '_pos_label', infer_pos_label(self._neg_label))
# TODO: reorder columns with newly guessed pos and neg class labels first
# TODO: gather up additional meta calculations here so
# a Confusion matrix can be build from an existing DataFrame that contains confusion counts
# rather than just two columns of labels.
self.__setattr__('_hist_labels', self.sum().astype(int))
self.__setattr__('_num_total', self._hist_labels.sum())
assert(self._num_total == self.sum().sum())
setattr(self, '_num_pos_labels', self._hist_labels.get(self._pos_label, 0))
# everything that isn't positive is negative
setattr(self, '_num_neg_labels', self._num_total - self._num_pos_labels)
setattr(self, '_hist_classes', self.T.sum())
setattr(self, '_num_pos', self._hist_classes.get(self._pos_label, 0))
setattr(self, '_num_neg', self._hist_classes.sum() - self._num_pos) # everything that isn't positive is negative
setattr(self, '_tp', self.get(self._pos_label, pd.Series()).get(self._pos_label, 0))
setattr(self, '_tpr', safe_div(float(self._tp), self._num_pos))
setattr(self, '_tn', np.diag(self).sum() - self._tp)
setattr(self, '_tnr', safe_div(float(self._tn), self._num_neg))
setattr(self, '_fp', self.get(self._pos_label, pd.Series()).sum() - self._tp)
setattr(self, '_fpr', safe_div(float(self._fp), self._num_neg))
setattr(self, '_fn', self._num_neg_labels - self._tn)
setattr(self, '_fnr', safe_div(float(self._fn), self._num_pos))
setattr(self, '_plr', safe_div(float(self._tpr), self._fpr))
setattr(self, '_nlr', safe_div(float(self._fnr), self._tnr))
setattr(self, '_binary_accuracy', safe_div(self._tp + self._tn, self._num_samples))
setattr(self, '_binary_sensitivity', safe_div(self._tp, self._tp + self._fn))
setattr(self, '_binary_specificity', safe_div(self._tn, self._tn + self._fp)) | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L487-L529 |
confusion matrix | python | def _q_to_dcm(self, q):
"""
Create DCM (Matrix3) from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: Matrix3
"""
assert(len(q) == 4)
arr = super(Quaternion, self)._q_to_dcm(q)
return self._dcm_array_to_matrix3(arr) | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/quaternion.py#L574-L582 |
confusion matrix | python | def _fusion_legacy_handler(_, __, tokens):
"""Handle a legacy fusion."""
if RANGE_5P not in tokens:
tokens[RANGE_5P] = {FUSION_MISSING: '?'}
if RANGE_3P not in tokens:
tokens[RANGE_3P] = {FUSION_MISSING: '?'}
return tokens | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/modifiers/fusion.py#L109-L115 |
confusion matrix | python | def cublasStpmv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Matrix-vector product for real triangular-packed matrix.
"""
status = _libcublas.cublasStpmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
n, int(AP), int(x), incx)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3194-L3205 |
confusion matrix | python | def cublasDtrmv(handle, uplo, trans, diag, n, A, lda, x, inx):
"""
Matrix-vector product for real triangular matrix.
"""
status = _libcublas.cublasDtrmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
n, int(A), lda, int(x), inx)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3420-L3431 |
confusion matrix | python | def converged(matrix1, matrix2):
"""
Check for convergence by determining if
matrix1 and matrix2 are approximately equal.
:param matrix1: The matrix to compare with matrix2
:param matrix2: The matrix to compare with matrix1
:returns: True if matrix1 and matrix2 approximately equal
"""
if isspmatrix(matrix1) or isspmatrix(matrix2):
return sparse_allclose(matrix1, matrix2)
return np.allclose(matrix1, matrix2) | https://github.com/GuyAllard/markov_clustering/blob/28787cf64ef06bf024ff915246008c767ea830cf/markov_clustering/mcl.py#L108-L120 |
confusion matrix | python | def decomposed_diffusion_program(qubits: List[int]) -> Program:
"""
Constructs the diffusion operator used in Grover's Algorithm, acted on both sides by an
a Hadamard gate on each qubit. Note that this means that the matrix representation of this
operator is diag(1, -1, ..., -1). In particular, this decomposes the diffusion operator, which
is a :math:`2**{len(qubits)}\times2**{len(qubits)}` sparse matrix, into
:math:`\mathcal{O}(len(qubits)**2) single and two qubit gates.
See C. Lavor, L.R.U. Manssur, and R. Portugal (2003) `Grover's Algorithm: Quantum Database
Search`_ for more information.
.. _`Grover's Algorithm: Quantum Database Search`: https://arxiv.org/abs/quant-ph/0301079
:param qubits: A list of ints corresponding to the qubits to operate on.
The operator operates on bistrings of the form
``|qubits[0], ..., qubits[-1]>``.
"""
program = Program()
if len(qubits) == 1:
program.inst(Z(qubits[0]))
else:
program.inst([X(q) for q in qubits])
program.inst(H(qubits[-1]))
program.inst(RZ(-np.pi, qubits[0]))
program += (ControlledProgramBuilder()
.with_controls(qubits[:-1])
.with_target(qubits[-1])
.with_operation(X_GATE)
.with_gate_name(X_GATE_LABEL).build())
program.inst(RZ(-np.pi, qubits[0]))
program.inst(H(qubits[-1]))
program.inst([X(q) for q in qubits])
return program | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/amplification/amplification.py#L86-L118 |
confusion matrix | python | def matrix_undirected_unweighted(user):
"""
Returns an undirected, unweighted matrix where an edge exists if the
relationship is reciprocated.
"""
matrix = matrix_undirected_weighted(user, interaction=None)
for a, b in combinations(range(len(matrix)), 2):
if matrix[a][b] is None or matrix[b][a] is None:
continue
if matrix[a][b] > 0 and matrix[b][a] > 0:
matrix[a][b], matrix[b][a] = 1, 1
return matrix | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L158-L171 |
confusion matrix | python | def cublasDgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for real general matrix.
"""
status = _libcublas.cublasDgemm_v2(handle,
_CUBLAS_OP[transa],
_CUBLAS_OP[transb], m, n, k,
ctypes.byref(ctypes.c_double(alpha)),
int(A), lda, int(B), ldb,
ctypes.byref(ctypes.c_double(beta)),
int(C), ldc)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3980-L3993 |
confusion matrix | python | def matrix_str(p, decimal_places=2, print_zero=True, label_columns=False):
'''Pretty-print the matrix.'''
return '[{0}]'.format("\n ".join([(str(i) if label_columns else '') + vector_str(a, decimal_places, print_zero) for i, a in enumerate(p)])) | https://github.com/tansey/gfl/blob/ae0f078bab57aba9e827ed6162f247ff9dc2aa19/pygfl/utils.py#L156-L158 |
confusion matrix | python | def cublasSdgmm(handle, mode, m, n, A, lda, x, incx, C, ldc):
"""
Matrix-diagonal matrix product for real general matrix.
"""
status = _libcublas.cublasSdgmm(handle,
_CUBLAS_SIDE[mode],
m, n,
int(A), lda,
int(x), incx,
int(C), ldc)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L4819-L4831 |
confusion matrix | python | def cublasCgeru(handle, m, n, alpha, x, incx, y, incy, A, lda):
"""
Rank-1 operation on complex general matrix.
"""
status = _libcublas.cublasCgeru_v2(handle,
m, n, ctypes.byref(cuda.cuFloatComplex(alpha.real,
alpha.imag)),
int(x), incx, int(y), incy, int(A), lda)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2434-L2444 |
confusion matrix | python | def _matrix3_to_dcm_array(self, m):
"""
Converts Matrix3 in an array
:param m: Matrix3
:returns: 3x3 array
"""
assert(isinstance(m, Matrix3))
return np.array([[m.a.x, m.a.y, m.a.z],
[m.b.x, m.b.y, m.b.z],
[m.c.x, m.c.y, m.c.z]]) | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/quaternion.py#L563-L572 |
confusion matrix | python | def cublasDspmv(handle, uplo, n, alpha, AP, x, incx, beta, y, incy):
"""
Matrix-vector product for real symmetric-packed matrix.
"""
status = _libcublas.cublasDspmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
n,
ctypes.byref(ctypes.c_double(alpha)),
ctypes.byref(ctypes.c_double(AP)),
int(x),
incx,
ctypes.byref(ctypes.c_double(beta)),
int(y),
incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2589-L2605 |
confusion matrix | python | def cublasDsymv(handle, uplo, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for real symmetric matrix.
"""
status = _libcublas.cublasDsymv_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctypes.byref(ctypes.c_double(alpha)),
int(A), lda, int(x), incx,
ctypes.byref(ctypes.c_double(beta)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2734-L2746 |
confusion matrix | python | def cublasDsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for real symmetric matrix.
"""
status = _libcublas.cublasDsymm_v2(handle,
_CUBLAS_SIDE_MODE[side],
_CUBLAS_FILL_MODE[uplo],
m, n, ctypes.byref(ctypes.c_double(alpha)),
int(A), lda, int(B), ldb,
ctypes.byref(ctypes.c_double(beta)),
int(C), ldc)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L4072-L4085 |
confusion matrix | python | def matrix_coords(rows, cols, rowh, colw, ox=0, oy=0):
"Generate coords for a matrix of rects"
for i, f, c in rowmajor(rows, cols):
x = ox + c * colw
y = oy + f * rowh
x1 = x + colw
y1 = y + rowh
yield (i, x, y, x1, y1) | https://github.com/alejandroautalan/pygubu/blob/41c8fb37ef973736ec5d68cbe1cd4ecb78712e40/pygubu/widgets/calendarframe.py#L40-L47 |
confusion matrix | python | def equation(self):
"""Mix-in class that returns matrix rows for zero normal flux condition.
Using the control point on the outside
Returns matrix part (nunknowns,neq)
Returns rhs part nunknowns
"""
mat = np.empty((self.nunknowns, self.model.neq))
rhs = np.zeros(self.nunknowns) # Needs to be initialized to zero
for icp in range(self.ncp):
istart = icp * self.nlayers
ieq = 0
for e in self.model.elementlist:
if e.nunknowns > 0:
qx, qy = e.disvecinflayers(self.xcout[icp], self.ycout[icp], self.layers)
mat[istart:istart + self.nlayers, ieq:ieq + e.nunknowns] = \
qx * self.cosnorm[icp] + qy * self.sinnorm[icp]
ieq += e.nunknowns
else:
qx, qy = e.disveclayers(self.xcout[icp], self.ycout[icp], self.layers)
rhs[istart:istart + self.nlayers] -= qx * self.cosnorm[icp] + qy * self.sinnorm[icp]
return mat, rhs | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/equation.py#L134-L154 |
confusion matrix | python | def matrix_exponent(M):
"""
The function computes matrix exponent and handles some special cases
"""
if (M.shape[0] == 1): # 1*1 matrix
Mexp = np.array( ((np.exp(M[0,0]) ,),) )
else: # matrix is larger
method = None
try:
Mexp = linalg.expm(M)
method = 1
except (Exception,) as e:
Mexp = linalg.expm3(M)
method = 2
finally:
if np.any(np.isnan(Mexp)):
if method == 2:
raise ValueError("Matrix Exponent is not computed 1")
else:
Mexp = linalg.expm3(M)
method = 2
if np.any(np.isnan(Mexp)):
raise ValueError("Matrix Exponent is not computed 2")
return Mexp | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/models/state_space_main.py#L3448-L3474 |
confusion matrix | python | def cublasZsyrk(handle, uplo, trans, n, k, alpha, A, lda, beta, C, ldc):
"""
Rank-k operation on complex symmetric matrix.
"""
status = _libcublas.cublasZsyrk_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
n, k, ctypes.byref(cuda.cuDoubleComplex(alpha.real,
alpha.imag)),
int(A), lda,
ctypes.byref(cuda.cuDoubleComplex(beta.real,
beta.imag)),
int(C), ldc)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L4247-L4262 |
confusion matrix | python | def mixed_density(qubits: Union[int, Qubits]) -> Density:
"""Returns the completely mixed density matrix"""
N, qubits = qubits_count_tuple(qubits)
matrix = np.eye(2**N) / 2**N
return Density(matrix, qubits) | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L322-L326 |
confusion matrix | python | def cublasDgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for real general matrix.
"""
status = _libcublas.cublasDgemv_v2(handle,
_CUBLAS_OP[trans], m, n,
ctypes.byref(ctypes.c_double(alpha)),
int(A), lda, int(x), incx,
ctypes.byref(ctypes.c_double(beta)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2279-L2291 |
confusion matrix | python | def _dcm_array_to_matrix3(self, dcm):
"""
Converts dcm array into Matrix3
:param dcm: 3x3 dcm array
:returns: Matrix3
"""
assert(dcm.shape == (3, 3))
a = Vector3(dcm[0][0], dcm[0][1], dcm[0][2])
b = Vector3(dcm[1][0], dcm[1][1], dcm[1][2])
c = Vector3(dcm[2][0], dcm[2][1], dcm[2][2])
return Matrix3(a, b, c) | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/quaternion.py#L551-L561 |
confusion matrix | python | def multiply(self, matrix):
"""
Multiply this matrix by a local dense matrix on the right.
:param matrix: a local dense matrix whose number of rows must match the number of columns
of this matrix
:returns: :py:class:`RowMatrix`
>>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]]))
>>> rm.multiply(DenseMatrix(2, 2, [0, 2, 1, 3])).rows.collect()
[DenseVector([2.0, 3.0]), DenseVector([6.0, 11.0])]
"""
if not isinstance(matrix, DenseMatrix):
raise ValueError("Only multiplication with DenseMatrix "
"is supported.")
j_model = self._java_matrix_wrapper.call("multiply", matrix)
return RowMatrix(j_model) | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/linalg/distributed.py#L373-L389 |
confusion matrix | python | def matrix_from_basis_coefficients(expansion: value.LinearDict[str],
basis: Dict[str, np.ndarray]) -> np.ndarray:
"""Computes linear combination of basis vectors with given coefficients."""
some_element = next(iter(basis.values()))
result = np.zeros_like(some_element, dtype=np.complex128)
for name, coefficient in expansion.items():
result += coefficient * basis[name]
return result | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/operator_spaces.py#L69-L76 |
confusion matrix | python | def cublasDsbmv(handle, uplo, n, k, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for real symmetric-banded matrix.
"""
status = _libcublas.cublasDsbmv_v2(handle,
_CUBLAS_FILL_MODE[uplo], n, k,
ctypes.byref(ctypes.c_double(alpha)),
int(A), lda, int(x), incx,
ctypes.byref(ctypes.c_double(beta)),
int(y), incy)
cublasCheckStatus(status) | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L2534-L2546 |
confusion matrix | python | def matrix(self) -> np.ndarray:
"""Reconstructs matrix of self using unitaries of underlying gates.
Raises:
TypeError: if any of the gates in self does not provide a unitary.
"""
num_qubits = self.num_qubits()
if num_qubits is None:
raise ValueError('Unknown number of qubits')
num_dim = 2 ** num_qubits
result = np.zeros((num_dim, num_dim), dtype=np.complex128)
for gate, coefficient in self.items():
result += protocols.unitary(gate) * coefficient
return result | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/linear_combinations.py#L94-L107 |
confusion matrix | python | def generate_mediation_matrix(dsm):
"""
Generate the mediation matrix of the given matrix.
Rules for mediation matrix generation:
Set -1 for items NOT to be considered
Set 0 for items which MUST NOT be present
Set 1 for items which MUST be present
Each module has optional dependencies to itself.
- Framework has optional dependency to all framework items (-1),
and to nothing else.
- Core libraries have dependencies to framework.
Dependencies to other core libraries are tolerated.
- Application libraries have dependencies to framework.
Dependencies to other core or application libraries are tolerated.
No dependencies to application modules.
- Application modules have dependencies to framework and libraries.
Dependencies to other application modules
should be mediated over a broker.
Dependencies to data are tolerated.
- Data have no dependencies at all
(but framework/libraries would be tolerated).
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to generate
the mediation matrix for.
"""
cat = dsm.categories
ent = dsm.entities
size = dsm.size[0]
if not cat:
cat = ['appmodule'] * size
packages = [e.split('.')[0] for e in ent]
# define and initialize the mediation matrix
mediation_matrix = [[0 for _ in range(size)]
for _ in range(size)]
for i in range(0, size):
for j in range(0, size):
if cat[i] == 'framework':
if cat[j] == 'framework':
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'corelib':
if (cat[j] in ('framework', 'corelib') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'applib':
if (cat[j] in ('framework', 'corelib', 'applib') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'appmodule':
# we cannot force an app module to import things from
# the broker if the broker itself did not import anything
if (cat[j] in ('framework', 'corelib',
'applib', 'broker', 'data') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'broker':
# we cannot force the broker to import things from
# app modules if there is nothing to be imported.
# also broker should be authorized to use third apps
if (cat[j] in (
'appmodule', 'corelib', 'framework') or
ent[i].startswith(packages[j] + '.') or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
elif cat[i] == 'data':
if (cat[j] == 'framework' or
i == j):
mediation_matrix[i][j] = -1
else:
mediation_matrix[i][j] = 0
else:
# mediation_matrix[i][j] = -2 # errors in the generation
raise DesignStructureMatrixError(
'Mediation matrix value NOT generated for %s:%s' % (
i, j))
return mediation_matrix | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/checkers.py#L30-L127 |
confusion matrix | python | def cofactor_n(x, i, j):
'''Return the cofactor of n matrices x[n,i,j] at position i,j
The cofactor is the determinant of the matrix formed by removing
row i and column j.
'''
m = x.shape[1]
mr = np.arange(m)
i_idx = mr[mr != i]
j_idx = mr[mr != j]
return det_n(x[:, i_idx[:, np.newaxis],
j_idx[np.newaxis, :]]) | https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/filter.py#L1374-L1385 |