How to use the yellowbrick.exceptions.YellowbrickValueError 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_regressor / test_residuals.py View on Github external
def test_no_hist_matplotlib_version(self, mock_toolkit):
        """
        No error is raised when matplotlib version is incorrect and hist=False
        """
        with pytest.raises(ImportError):
            from mpl_toolkits.axes_grid1 import make_axes_locatable

            assert not make_axes_locatable

        try:
            ResidualsPlot(LinearRegression(), hist=False)
        except YellowbrickValueError as e:
            self.fail(e)
github DistrictDataLabs / yellowbrick / tests / test_cluster / test_icdm.py View on Github external
def test_only_valid_embeddings(self):
        """
        Should raise an exception on invalid embedding
        """
        # On init
        with pytest.raises(YellowbrickValueError, match="unknown embedding 'foo'"):
            InterclusterDistance(KMeans(), embedding='foo')

        # After init
        icdm = InterclusterDistance(KMeans())
        icdm.embedding = 'foo'
        with pytest.raises(YellowbrickValueError, match="unknown embedding 'foo'"):
            icdm.transformer
github DistrictDataLabs / yellowbrick / tests / test_cluster / test_elbow.py View on Github external
def test_invalid_k(self):
        """
        Assert that invalid values of K raise exceptions
        """

        with pytest.raises(YellowbrickValueError):
            KElbowVisualizer(KMeans(), k=(1, 2, 3, "foo", 5))

        with pytest.raises(YellowbrickValueError):
            KElbowVisualizer(KMeans(), k="foo")
github DistrictDataLabs / yellowbrick / yellowbrick / classifier / prcurve.py View on Github external
if required, it is recommended to use the base class.
    """

    if (X_test is None) and (y_test is None):
        # Create train and test splits to validate the model
        X_train, X_test, y_train, y_test = tts(
            X, y, train_size=train_size, random_state=random_state, shuffle=shuffle
        )
    elif any(
        [
            ((X_test is not None) and (y_test is None)),
            ((X_test is None) and (y_test is not None)),
        ]
    ):
        # exception handling in case of missing X_test or y_test
        raise YellowbrickValueError(
            "both X_test and y_test are required if one is specified"
        )

    else:
        X_train, y_train = X, y

    # Instantiate the visualizer
    viz = PRCurve(model, ax=ax, **kwargs)

    # Fit and transform the visualizer
    viz.fit(X_train, y_train)
    viz.score(X_test, y_test)
    viz.finalize()

    # Return the visualizer
    return viz
github DistrictDataLabs / yellowbrick / yellowbrick / contrib / classifier / boundaries.py View on Github external
# Handle the feature names if they're None.
        elif self.features_ is not None and is_dataframe(X):
            X_two_cols = X[self.features_].as_matrix()

        # handle numpy named/ structured array
        elif self.features_ is not None and is_structured_array(X):
            X_selected = X[self.features_]
            X_two_cols = X_selected.copy().view(np.float64).reshape(len(X_selected), -1)

        # handle features that are numeric columns in ndarray matrix
        elif self.features_ is not None and has_ndarray_int_columns(self.features_, X):
            f_one, f_two = self.features_
            X_two_cols = X[:, [int(f_one), int(f_two)]]

        else:
            raise YellowbrickValueError("""
                ScatterVisualizer only accepts two features, please
                explicitly set these two features in the init kwargs or
                pass a matrix/ dataframe in with only two columns.""")

        return X_two_cols
github DistrictDataLabs / yellowbrick / yellowbrick / cluster / icdm.py View on Github external
def lax(self):
        """
        Returns the legend axes, creating it only on demand by creating a 2"
        by 2" inset axes that has no grid, ticks, spines or face frame (e.g
        is mostly invisible). The legend can then be drawn on this axes.
        """
        if inset_locator is None:
            raise YellowbrickValueError(
                (
                    "intercluster distance map legend requires matplotlib 2.0.2 or "
                    "later please upgrade matplotlib or set legend=False "
                )
            )

        lax = inset_locator.inset_axes(
            self.ax,
            width=self.legend_size,
            height=self.legend_size,
            loc=self.legend_loc,
        )

        lax.set_frame_on(False)
        lax.set_facecolor("none")
        lax.grid(False)
github DistrictDataLabs / yellowbrick / yellowbrick / style / palettes.py View on Github external
)

        palette = PALETTES[palette.lower()]
        if n_colors is None:
            n_colors = len(palette)

    # Always return as many colors as we asked for
    pal_cycle = cycle(palette)
    palette = [next(pal_cycle) for _ in range(n_colors)]

    # Always return in RGB tuple format
    try:
        palette = map(mpl.colors.colorConverter.to_rgb, palette)
        palette = ColorPalette(palette)
    except ValueError:
        raise YellowbrickValueError(
            "Could not generate a palette for %s" % str(palette)
        )

    return palette
github DistrictDataLabs / yellowbrick / yellowbrick / regressor / alphas.py View on Github external
def _find_errors_param(self):
        """
        Searches for the parameter on the estimator that contains the array of
        errors that was used to determine the optimal alpha. If it cannot find
        the parameter then a YellowbrickValueError is raised.
        """

        # NOTE: The order of the search is very important!
        if hasattr(self.estimator, "mse_path_"):
            return self.estimator.mse_path_.mean(1)

        if hasattr(self.estimator, "cv_values_"):
            return self.estimator.cv_values_.mean(0)

        raise YellowbrickValueError(
            "could not find errors param on {} estimator".format(
                self.estimator.__class__.__name__
            )
github DistrictDataLabs / yellowbrick / yellowbrick / features / pca.py View on Github external
for i in range(self.pca_components_.shape[1]):
                self.ax.plot(
                    [0, x_vector[i] * max_x],
                    [0, y_vector[i] * max_y],
                    [0, z_vector[i] * max_z],
                    color="r",
                )
                self.ax.text(
                    x_vector[i] * max_x * 1.05,
                    y_vector[i] * max_y * 1.05,
                    z_vector[i] * max_z * 1.05,
                    self.features_[i],
                    color="r",
                )
        else:
            raise YellowbrickValueError("Projection dimensions must be either 2 or 3")

        return self.ax
github DistrictDataLabs / yellowbrick / yellowbrick / draw.py View on Github external
for j in range(len(data[rdx]))
            ]
            ax.bar(idx, data[rdx], bottom=stack,
                         color=colors[rdx])
          #Updates the stack for negative side of x-axis            
            stack_arr[:, 0] += np.minimum(data[rdx],
                                         zeros)
           #Updates the stack for negative side of x-axis
            stack_arr[:, 1] += np.maximum(data[rdx],
                                             zeros)
        ax.set_xticks(idx)
        if ticks is not None:
            ax.set_xticklabels(ticks, rotation=90)

    else:
        raise YellowbrickValueError(
                "unknown orientation '{}'".format(orientation)
                )
    
    # Generates default labels is labels are not specified.
    labels = labels or np.arange(data.shape[0])

    if legend:
        legend_kws = legend_kws or {}
        manual_legend(ax, labels=labels, colors=colors, **legend_kws)
    return ax