Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_show_warns(self, mock_plt):
"""
Test show issues a warning when no axes has been modified
"""
class CustomVisualizer(Visualizer):
pass
with pytest.warns(YellowbrickWarning):
viz = CustomVisualizer()
assert viz.show() is not None
"""
pass
##########################################################################
## Warnings
##########################################################################
class YellowbrickWarning(UserWarning):
"""
Warning class used to notify users of Yellowbrick-specific issues.
"""
pass
class DataWarning(YellowbrickWarning):
"""
The supplied data has an issue that may produce unexpected visualizations.
"""
pass
def find_knee(self,):
"""This function finds and sets the knee value and the normalized knee value. """
if not self.maxima_inidices.size:
warning_message = (
'No "knee" or "elbow point" detected '
"This could be due to bad clustering, no "
"actual clusters being formed etc."
)
warnings.warn(warning_message, YellowbrickWarning)
return None, None
# artificially place a local max at the last item in the x_distance array
self.maxima_inidices = np.append(self.maxima_inidices, len(self.x_distance) - 1)
self.minima_indices = np.append(self.minima_indices, len(self.x_distance) - 1)
# placeholder for which threshold region i is located in.
maxima_threshold_index = 0
minima_threshold_index = 0
# traverse the distance curve
for idx, i in enumerate(self.x_distance):
# reached the end of the curve
if i == 1.0:
break
# values in distance curve are at or after a local maximum
if idx >= self.maxima_inidices[maxima_threshold_index]:
def _select_features_to_plot(self, X):
"""
Select features to plot.
feature_index is always used as the filter and
if filter_names is supplied, a new feature_index
is computed from those names.
"""
if self.feature_index:
if self.feature_names:
raise YellowbrickWarning(
'Both feature_index and feature_names '
'are specified. feature_names is ignored'
)
if (min(self.feature_index) < 0
or max(self.feature_index) >= X.shape[1]):
raise YellowbrickValueError('Feature index is out of range')
elif self.feature_names:
self.feature_index = []
features_list = self.features_.tolist()
for feature_name in self.feature_names:
try:
self.feature_index.append(
features_list.index(feature_name)
)
except ValueError:
raise YellowbrickValueError(
"calinski_harabasz": {
"curve_nature": "concave",
"curve_direction": "increasing",
},
}.get(self.metric, {})
elbow_locator = KneeLocator(
self.k_values_, self.k_scores_, **locator_kwargs
)
if elbow_locator.knee is None:
self.elbow_value_ = None
self.elbow_score_ = 0
warning_message = (
"No 'knee' or 'elbow' point detected, "
"pass `locate_elbow=False` to remove the warning"
)
warnings.warn(warning_message, YellowbrickWarning)
else:
self.elbow_value_ = elbow_locator.knee
self.elbow_score_ = self.k_scores_[
self.k_values_.index(self.elbow_value_)
]
self.draw()
return self
)
# Convert string to integer
if isinstance(projection, str):
if projection in {"2D", "2d"}:
projection = 2
if projection in {"3D", "3d"}:
projection = 3
if projection not in {2, 3}:
raise YellowbrickValueError("Projection dimensions must be either 2 or 3")
self.projection = projection
if self.ax.name != "3d" and self.projection == 3:
warnings.warn(
"data projection to 3 dimensions requires a 3d axes to draw on.",
YellowbrickWarning,
)
self.alpha = alpha
self.colorbar = colorbar
self._cax = None
def _decode_labels(self, y):
"""
An internal helper function that uses either the classes or encoder
properties to correctly decode y as user-readable string labels.
If both classes and encoder are set, a warning is issued and encoder is
used instead of classes. If neither encoder nor classes is set then the
original array is returned unmodified.
"""
if self.classes is not None and self.encoder is not None:
warnings.warn(
"both classes and encoder specified, using encoder", YellowbrickWarning
)
if self.encoder is not None:
# Use the label encoder or other transformer
if hasattr(self.encoder, "inverse_transform"):
try:
return self.encoder.inverse_transform(y)
except ValueError:
y_labels = np.unique(y)
raise ModelError(
"could not decode {} y values to {} labels".format(
y_labels, self._labels()
)
)
# Otherwise, treat as a dictionary
def _labels(self):
"""
Returns the human specified labels in either the classes list or from the
encoder. Returns None if no human labels have been specified, but issues a
warning if a transformer has been passed that does not specify labels.
"""
if self.classes is not None and self.encoder is not None:
warnings.warn(
"both classes and encoder specified, using encoder", YellowbrickWarning
)
if self.encoder is not None:
# Use label encoder or other transformer
if hasattr(self.encoder, "transform"):
if hasattr(self.encoder, "classes_"):
return self.encoder.classes_
# This is not a label encoder
msg = "could not determine class labels from {}".format(
self.encoder.__class__.__name__
)
warnings.warn(msg, YellowbrickWarning)
return None
# Otherwise, treat as dictionary and ensure sorted by key
kwargs: dict
generic keyword arguments.
Notes
-----
Developers of visualizers don't usually override poof, as it is
primarily called by the user to render the visualization.
"""
# Ensure that draw has been called
if self._ax is None:
warn_message = (
"{} does not have a reference to a matplotlib.Axes "
"the figure may not render as expected!"
)
warnings.warn(
warn_message.format(self.__class__.__name__), YellowbrickWarning
)
# Finalize the figure
self.finalize()
if outpath is not None:
plt.savefig(outpath, **kwargs)
else:
plt.show()
if clear_figure:
self.fig.clear()
# Return ax to ensure display in notebooks
return self.ax