How to use the yellowbrick.exceptions.NotFitted function in yellowbrick

To help you get started, we’ve selected a few yellowbrick examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DistrictDataLabs / yellowbrick / tests / test_model_selection / test_importances.py View on Github external
def test_draw_raises_unfitted(self):
        """
        Assert draw raises exception when not fitted
        """
        visualizer = FeatureImportances(Lasso())
        with pytest.raises(NotFitted):
            visualizer.draw()
github DistrictDataLabs / yellowbrick / yellowbrick / classifier / prcurve.py View on Github external
def score(self, X, y=None):
        """
        Generates the Precision-Recall curve on the specified test data.

        Returns
        -------
        score_ : float
            Average precision, a summary of the plot as a weighted mean of
            precision at each threshold, weighted by the increase in recall from
            the previous threshold.
        """
        # If we don't do this check, then it is possible that OneVsRestClassifier
        # has not correctly been fitted for multi-class targets.
        if not hasattr(self, "target_type_"):
            raise NotFitted.from_estimator(self, "score")

        # Compute the prediction/threshold scores
        y_scores = self._get_y_scores(X)

        # Handle binary and multiclass cases to create correct data structure
        if self.target_type_ == BINARY:
            self.precision_, self.recall_, _ = sk_precision_recall_curve(y, y_scores)
            self.score_ = average_precision_score(y, y_scores)
        else:
            # Use label_binarize to create multi-label output for OneVsRestClassifier
            Y = label_binarize(y, classes=self._target_labels)

            self.precision_, self.recall_, self.score_ = {}, {}, {}

            # Compute PRCurve for all classes
            for i, class_i in enumerate(self.classes_):
github DistrictDataLabs / yellowbrick / yellowbrick / features / base.py View on Github external
def get_target_color_type(self):
        """
        Returns the computed target color type if fitted or specified by the user.
        """
        if self._target_color_type is None:
            raise NotFitted("unknown target color type on unfitted visualizer")
        return self._target_color_type
github DistrictDataLabs / yellowbrick / yellowbrick / model_selection / importances.py View on Github external
def draw(self, **kwargs):
        """
        Draws the feature importances as a bar chart; called from fit.
        """
        # Quick validation
        for param in ("feature_importances_", "features_"):
            if not hasattr(self, param):
                raise NotFitted("missing required param '{}'".format(param))

        # Find the positions for each bar
        pos = np.arange(self.features_.shape[0]) + 0.5

        # Plot the bar chart
        if self.stack:
            colors = resolve_colors(len(self.classes_), colormap=self.colormap)
            legend_kws = {"bbox_to_anchor": (1.04, 0.5), "loc": "center left"}
            bar_stack(
                self.feature_importances_,
                ax=self.ax,
                labels=list(self.classes_),
                ticks=self.features_,
                orientation="h",
                colors=colors,
                legend_kws=legend_kws,
github DistrictDataLabs / yellowbrick / yellowbrick / classifier / base.py View on Github external
y : array-like
            y (also y_test) is the independent actual variables to score against

        Returns
        -------
        score : float
            Returns the score of the underlying model, usually accuracy for
            classification models. Refer to the specific model for more details.
        """
        # If the estimator has been passed in fitted but the visualizer was not fit
        # then we can retrieve the classes from the estimator, unfortunately we cannot
        # retrieve the class counts so we simply set them to None and warn the user.
        # NOTE: cannot test if hasattr(self, "classes_") because it will be proxied.
        if not hasattr(self, "class_counts_"):
            if not hasattr(self.estimator, "classes_"):
                raise NotFitted(
                    (
                        "could not determine required property classes_; "
                        "the visualizer must either be fit or instantiated with a "
                        "fitted classifier before calling score()"
                    )
                )

            self.class_counts_ = None
            self.classes_ = self._decode_labels(self.estimator.classes_)
            warnings.warn(
                "could not determine class_counts_ from previously fitted classifier",
                YellowbrickWarning,
            )

        # This method implements ScoreVisualizer (do not call super).
        self.score_ = self.estimator.score(X, y)
github DistrictDataLabs / yellowbrick / yellowbrick / classifier / class_prediction_error.py View on Github external
def draw(self):
        """
        Renders the class prediction error across the axis.

        Returns
        -------
        ax : Matplotlib Axes
            The axes on which the figure is plotted
        """

        if not hasattr(self, "predictions_") or not hasattr(self, "classes_"):
            raise NotFitted.from_estimator(self, "draw")

        legend_kws = {"bbox_to_anchor": (1.04, 0.5), "loc": "center left"}
        bar_stack(
            self.predictions_,
            self.ax,
            labels=list(self.classes_),
            ticks=self.classes_,
            colors=self.colors,
            legend_kws=legend_kws,
        )
        return self.ax
github DistrictDataLabs / yellowbrick / yellowbrick / features / base.py View on Github external
"""
        Returns the color for the specified value(s) of y based on the learned
        colors property for any specified target type.

        Parameters
        ----------
        y : array-like
            The values of y to get the associated colors for.

        Returns
        -------
        colors : list
            Returns a list of colors for each value in y.
        """
        if self._colors is None:
            raise NotFitted("cannot determine colors on unfitted visualizer")

        if self._target_color_type == TargetType.SINGLE:
            return [self._colors] * len(y)

        if self._target_color_type == TargetType.DISCRETE:
            try:
                # Use the label encoder to get the class name (or use the value
                # if the label is not mapped in the encoder) then use the class
                # name to get the color from the color map.
                return [self._colors[self._label_encoder.get(yi, yi)] for yi in y]
            except KeyError:
                unknown = set(y) - set(self._label_encoder.keys())
                unknown = ", ".join(["'{}'".format(uk) for uk in unknown])
                raise YellowbrickKeyError(
                    "could not determine color for classes {}".format(unknown)
                )
github DistrictDataLabs / yellowbrick / yellowbrick / features / projection.py View on Github external
try:
                scatter_kwargs["c"] = [self._colors[self.classes_[yi]] for yi in y]
            except IndexError:
                raise YellowbrickValueError("Target needs to be label encoded.")

        elif self._target_color_type == TargetType.CONTINUOUS:
            if y is None:
                raise YellowbrickValueError("y is required for continuous target")

            scatter_kwargs["c"] = y
            scatter_kwargs["cmap"] = self._colors
            self._norm = mpl.colors.Normalize(vmin=self.range_[0], vmax=self.range_[1])

        else:
            # Technically this should never be raised
            raise NotFitted("could not determine target color type")
        return scatter_kwargs
github DistrictDataLabs / yellowbrick / yellowbrick / classifier / base.py View on Github external
def colors(self):
        """
        Returns ``_colors`` if it exists, otherwise computes a categorical color
        per class based on the matplotlib color cycle. If the visualizer is not
        fitted, raises a NotFitted exception.

        If subclasses require users to choose colors or have specialized color
        handling, they should set ``_colors`` on init or during fit.

        Notes
        -----
        Because this is a property, this docstring is for developers only.
        """
        if not hasattr(self, "_colors"):
            if not hasattr(self, "classes_"):
                raise NotFitted("cannot determine colors before fit")

            # TODO: replace with resolve_colors
            self._colors = color_palette(None, len(self.classes_))
        return self._colors