text stringlengths 81 112k |
|---|
Draws the feature importances as a bar chart; called from fit.
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):
... |
Finalize the drawing setting labels and title.
def finalize(self, **kwargs):
"""
Finalize the drawing setting labels and title.
"""
# Set the title
self.set_title('Feature Importances of {} Features using {}'.format(
len(self.features_), self.name))
# Se... |
Searches the wrapped model for the classes_ parameter.
def _find_classes_param(self):
"""
Searches the wrapped model for the classes_ parameter.
"""
for attr in ["classes_"]:
try:
return getattr(self.estimator, attr)
except AttributeError:
... |
Determines the xlabel based on the underlying data structure
def _get_xlabel(self):
"""
Determines the xlabel based on the underlying data structure
"""
# Return user-specified label
if self.xlabel:
return self.xlabel
# Label for coefficients
if hasa... |
Determines the type of color space that will best represent the target
variable y, e.g. either a discrete (categorical) color space or a
continuous color space that requires a colormap. This function can handle
both 1D or column vectors as well as multi-output targets.
Parameters
----------
y :... |
Creates the grid layout for the joint plot, adding new axes for the histograms
if necessary and modifying the aspect ratio. Does not modify the axes or the
layout if self.hist is False or None.
def _layout(self):
"""
Creates the grid layout for the joint plot, adding new axes for the hi... |
Fits the JointPlot, creating a correlative visualization between the columns
specified during initialization and the data and target passed into fit:
- If self.columns is None then X and y must both be specified as 1D arrays
or X must be a 2D array with only 2 columns.
- I... |
Draw the joint plot for the data in x and y.
Parameters
----------
x, y : 1D array-like
The data to plot for the x axis and the y axis
xlabel, ylabel : str
The labels for the x and y axes.
def draw(self, x, y, xlabel=None, ylabel=None):
"""
Draw... |
Finalize executes any remaining image modifications making it ready to show.
def finalize(self, **kwargs):
"""
Finalize executes any remaining image modifications making it ready to show.
"""
# Set the aspect ratio to make the visualization square
# TODO: still unable to make pl... |
Attempts to get the column from the data using the specified index, raises an
exception if this is not possible from this point in the stack.
def _index_into(self, idx, data):
"""
Attempts to get the column from the data using the specified index, raises an
exception if this is not poss... |
The fit method is the primary drawing input for the
visualization since it has both the X and y data required for the
viz and the transform method does not.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
... |
Test various estimators.
def visualize_model(X, y, estimator, path, **kwargs):
"""
Test various estimators.
"""
y = LabelEncoder().fit_transform(y)
model = Pipeline([
('one_hot_encoder', OneHotEncoder()),
('estimator', estimator)
])
_, ax = plt.subplots()
# Instant... |
Displays cross validation scores as a bar chart and the
average of the scores as a horizontal line
This helper function is a quick wrapper to utilize the
CVScores visualizer for one-off analysis.
Parameters
----------
model : a scikit-learn estimator
An object that implements ``fit`` ... |
Fits the learning curve with the wrapped model to the specified data.
Draws training and test score curves and saves the scores to the
estimator.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of sam... |
Creates the bar chart of the cross-validated scores generated from the
fit method and places a dashed horizontal line that represents the
average value of the scores.
def draw(self, **kwargs):
"""
Creates the bar chart of the cross-validated scores generated from the
fit method ... |
Add the title, legend, and other visual final touches to the plot.
def finalize(self, **kwargs):
"""
Add the title, legend, and other visual final touches to the plot.
"""
# Set the title of the figure
self.set_title('Cross Validation Scores for {}'.format(self.name))
... |
Accepts a matrix X and returns a correlation matrix so that each column
is the variable and each row is the observations.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
def kendalltau(X):
"""
Accepts a matrix X and returns a correl... |
Scores each feature with the algorithm and ranks them in a bar plot.
This helper function is a quick wrapper to utilize the Rank1D Visualizer
(Transformer) for one-off analysis.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : n... |
Displays pairwise comparisons of features with the algorithm and ranks
them in a lower-left triangle heatmap plot.
This helper function is a quick wrapper to utilize the Rank2D Visualizer
(Transformer) for one-off analysis.
Parameters
----------
X : ndarray or DataFrame of shape n x m
... |
The transform method is the primary drawing hook for ranking classes.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
kwargs : dict
Pass generic arguments to the drawing method
Returns
------... |
Returns the feature ranking.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
algorithm : str or None
The ranking mechanism to use, or None for the default
Returns
-------
ranks : ndar... |
Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: dict
generic keyword arguments
def finalize(self, **kwargs):
"""
Finalize executes any subclass-specific axes finaliza... |
Draws the bar plot of the ranking array of features.
def draw(self, **kwargs):
"""
Draws the bar plot of the ranking array of features.
"""
if self.orientation_ == 'h':
# Make the plot
self.ax.barh(np.arange(len(self.ranks_)), self.ranks_, color='b')
... |
Draws the heatmap of the ranking matrix of variables.
def draw(self, **kwargs):
"""
Draws the heatmap of the ranking matrix of variables.
"""
# Set the axes aspect to be equal
self.ax.set_aspect("equal")
# Generate a mask for the upper triangle
mask = np.zeros_l... |
Quick method:
Divides the dataset X and y into train and test splits, fits the model on
the train split, then scores the model on the test split. The visualizer
displays the support for each class in the fitted classification model
displayed as a stacked bar plot Each bar is segmented to show the
di... |
Generates a 2D array where each row is the count of the
predicted classes and each column is the true class
Parameters
----------
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 o... |
Renders the class prediction error across the axis.
def draw(self):
"""
Renders the class prediction error across the axis.
"""
indices = np.arange(len(self.classes_))
prev = np.zeros(len(self.classes_))
colors = resolve_colors(
colors=self.colors,
... |
Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
def finalize(self, **kwargs):
"""
Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
"""
indices = np... |
The MissingValues Bar visualizer creates a bar graph that lists the total
count of missing values for each selected feature column.
When y targets are supplied to fit, the output is a stacked bar chart where
each color corresponds to the total NaNs for the feature in that column.
Parameters
------... |
Called from the fit method, this method generated a horizontal bar plot.
If y is none, then draws a simple horizontal bar chart.
If y is not none, then draws a stacked horizontal bar chart for each nan count per
target values.
def draw(self, X, y, **kwargs):
"""Called from the fit meth... |
Draws a horizontal stacked bar chart with different colors
for each count of nan values per label.
def draw_stacked_bar(self, nan_col_counts):
"""Draws a horizontal stacked bar chart with different colors
for each count of nan values per label.
"""
for index, nan_values in enume... |
Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments.
def finalize(self, **kwargs):
"""
Finalize executes any subclass-specific axes finalization steps.
... |
Displays the correlation between features and dependent variables.
This visualizer can be used side-by-side with
yellowbrick.features.JointPlotVisualizer that plots a feature
against the target and shows the distribution of each via a
histogram on each axis.
Parameters
----------
X : ndarr... |
Fits the estimator to calculate feature correlation to
dependent variable.
Parameters
----------
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 value... |
Draws the feature correlation to dependent variable, called from fit.
def draw(self):
"""
Draws the feature correlation to dependent variable, called from fit.
"""
pos = np.arange(self.scores_.shape[0]) + 0.5
self.ax.barh(pos, self.scores_)
# Set the labels for the bar... |
Finalize the drawing setting labels and title.
def finalize(self):
"""
Finalize the drawing setting labels and title.
"""
self.set_title('Features correlation with dependent variable')
self.ax.set_xlabel(self.correlation_labels[self.method])
self.ax.grid(False, axis='y... |
Create labels for the features
NOTE: this code is duplicated from MultiFeatureVisualizer
def _create_labels_for_features(self, X):
"""
Create labels for the features
NOTE: this code is duplicated from MultiFeatureVisualizer
"""
if self.labels is None:
# Use... |
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.
def _select_features_to_plot(self, X):
"""
Select features to plot.
feature_index is always used as the filter and
... |
Create figures for feature analysis
def feature_analysis(fname="feature_analysis.png"):
"""
Create figures for feature analysis
"""
# Create side-by-side axes grid
_, axes = plt.subplots(ncols=2, figsize=(18,6))
# Draw RadViz on the left
data = load_occupancy(split=False)
oz = RadViz(... |
Create figures for regression models
def regression(fname="regression.png"):
"""
Create figures for regression models
"""
_, axes = plt.subplots(ncols=2, figsize=(18, 6))
alphas = np.logspace(-10, 1, 300)
data = load_concrete(split=True)
# Plot prediction error in the middle
oz = Predi... |
The matplotlib axes that the visualizer draws upon (can also be a grid
of multiple axes objects). The visualizer automatically creates an
axes for the user if one has not been specified.
def ax(self):
"""
The matplotlib axes that the visualizer draws upon (can also be a grid
of ... |
Returns the actual size in pixels as set by matplotlib, or
the user provided size if available.
def size(self):
"""
Returns the actual size in pixels as set by matplotlib, or
the user provided size if available.
"""
if not hasattr(self, "_size") or self._size is None:
... |
Poof makes the magic happen and a visualizer appear! You can pass in
a path to save the figure to disk with various backends, or you can
call it with no arguments to show the figure either in a notebook or
in a GUI window that pops up on screen.
Parameters
----------
out... |
Sets the title on the current axes.
Parameters
----------
title: string, default: None
Add title to figure or if None leave untitled.
def set_title(self, title=None):
"""
Sets the title on the current axes.
Parameters
----------
title: strin... |
Generates the subplots for the number of given models.
def generate_subplots(self):
"""
Generates the subplots for the number of given models.
"""
_, axes = plt.subplots(len(self.models), sharex=True, sharey=True)
return axes |
Returns a generator containing the predictions for each of the
internal models (using cross_val_predict and a CV=12).
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
... |
Loads and wrangles the passed in text corpus by path.
def load_corpus(path):
"""
Loads and wrangles the passed in text corpus by path.
"""
# Check if the data exists, otherwise download or raise
if not os.path.exists(path):
raise ValueError((
"'{}' dataset has not been download... |
Return the path of the Yellowbrick data directory. This folder is used by
dataset loaders to avoid downloading data several times.
By default, this folder is colocated with the code in the install directory
so that data shipped with the package can be easily located. Alternatively
it can be set by the ... |
Looks up the path to the dataset specified in the data home directory,
which is found using the ``get_data_home`` function. By default data home
is colocated with the code, but can be modified with the YELLOWBRICK_DATA
environment variable, or passing in a different directory.
The file returned will be... |
Checks to see if a directory with the name of the specified dataset exists
in the data home directory, found with ``get_data_home``.
Parameters
----------
dataset : str
The name of the dataset; should either be a folder in data home or
specified in the yellowbrick.datasets.DATASETS vari... |
Checks to see if the dataset archive file exists in the data home directory,
found with ``get_data_home``. By specifying the signature, this function
also checks to see if the archive is the latest version by comparing the
sha256sum of the local archive with the specified signature.
Parameters
----... |
Removes the dataset directory and archive file from the data home directory.
Parameters
----------
dataset : str
The name of the dataset; should either be a folder in data home or
specified in the yellowbrick.datasets.DATASETS variable.
data_home : str, optional
The path on dis... |
Fit to data, transform it, then visualize it.
Fits the visualizer to X and y with opetional parameters by passing in
all of kwargs, then calls poof with the same kwargs. This method must
return the result of the transform method.
def fit_transform_poof(self, X, y=None, **kwargs):
"""
... |
This method performs preliminary computations in order to set up the
figure or perform other analyses. It can also call drawing methods in
order to set up various non-instance related figure elements.
This method must return self.
def fit(self, X, y=None, **fit_params):
"""
Thi... |
The fit method is the primary drawing input for the
visualization since it has both the X and y data required for the
viz and the transform method does not.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
... |
Return a color palette object with color definition and handling.
Calling this function with ``palette=None`` will return the current
matplotlib color cycle.
This function can also be used in a ``with`` statement to temporarily
set the color cycle for a plot or set of plots.
Parameters
------... |
Change how matplotlib color shorthands are interpreted.
Calling this will change how shorthand codes like "b" or "g"
are interpreted by matplotlib in subsequent plots.
Parameters
----------
palette : str
Named yellowbrick palette to use as the source of colors.
See Also
--------
... |
Return a `ListedColormap` object from a named sequence palette. Useful
for continuous color scheme values and color maps.
Calling this function with ``palette=None`` will return the default
color sequence: Color Brewer RdBu.
Parameters
----------
palette : None or str or sequence
Name... |
Return a color palette with hex codes instead of RGB values.
def as_hex(self):
"""
Return a color palette with hex codes instead of RGB values.
"""
hex = [mpl.colors.rgb2hex(rgb) for rgb in self]
return ColorPalette(hex) |
Return a color palette with RGB values instead of hex codes.
def as_rgb(self):
"""
Return a color palette with RGB values instead of hex codes.
"""
rgb = [mpl.colors.colorConverter.to_rgb(hex) for hex in self]
return ColorPalette(rgb) |
Plot the values in the color palette as a horizontal array.
See Seaborn's palplot function for inspiration.
Parameters
----------
size : int
scaling factor for size of the plot
def plot(self, size=1):
"""
Plot the values in the color palette as a horizontal ... |
Makes directories as needed
def _make_path(self, path, name):
"""
Makes directories as needed
"""
if not os.path.exists(path):
os.mkdirs(path)
if os.path.isdir(path) :
return os.path.join(path, name)
return path |
Draw the manifold embedding for the specified algorithm
def plot_manifold_embedding(self, algorithm="lle", path="images"):
"""
Draw the manifold embedding for the specified algorithm
"""
_, ax = plt.subplots(figsize=(9,6))
path = self._make_path(path, "s_curve_{}_manifold.png".f... |
Downloads the zipped data set specified at the given URL, saving it to
the data directory specified by ``get_data_home``. This function verifies
the download with the given signature and extracts the archive.
Parameters
----------
url : str
The URL of the dataset on the Internet to GET
... |
Set aesthetic parameters in one step.
Each set of parameters can be set directly or temporarily, see the
referenced functions below for more information.
Parameters
----------
palette : string or sequence
Color palette, see :func:`color_palette`
font : string
Font family, see m... |
Return a parameter dict for the aesthetic style of the plots.
NOTE: This is an internal method from Seaborn that is simply used to
create a default aesthetic in yellowbrick. If you'd like to use these
styles then import Seaborn!
This affects things like the color of the axes, whether a grid is
ena... |
Set the aesthetic style of the plots.
This affects things like the color of the axes, whether a grid is
enabled by default, and other aesthetic elements.
Parameters
----------
style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks}
A dictionary of parameters or the name of ... |
Set the plotting context parameters.
NOTE: This is an internal method from Seaborn that is simply used to
create a default aesthetic in yellowbrick. If you'd like to use these
styles then import Seaborn!
This affects things like the size of the labels, lines, and other
elements of the plot, but no... |
Set the matplotlib color cycle using a seaborn palette.
Parameters
----------
palette : yellowbrick color palette | seaborn color palette (with ``sns_`` prepended)
Palette definition. Should be something that :func:`color_palette`
can process.
n_colors : int
Number of colors in ... |
Displays lexical dispersion plot for words in a corpus
This helper function is a quick wrapper to utilize the DisperstionPlot
Visualizer for one-off analysis
Parameters
----------
words : list
A list of words whose dispersion will be examined within a corpus
y : ndarray or Series of ... |
The fit method is the primary drawing input for the dispersion
visualization.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
that yields a list of documents that contain a list of
words in the ord... |
Called from the fit method, this method creates the canvas and
draws the plot on it.
Parameters
----------
kwargs: generic keyword arguments.
def draw(self, points, target=None, **kwargs):
"""
Called from the fit method, this method creates the canvas and
draws t... |
The finalize method executes any subclass-specific axes
finalization steps. The user calls poof & poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments.
def finalize(self, **kwargs):
"""
The finalize method executes any subclass-specific axes
... |
Quick method for Manifold visualizer.
The Manifold visualizer provides high dimensional visualization for feature
analysis by embedding data into 2 dimensions using the sklearn.manifold
package for manifold learning. In brief, manifold learning algorithms are
unsuperivsed approaches to non-linear dimen... |
Creates the manifold estimator if a string value is passed in,
validates other objects passed in.
def manifold(self, transformer):
"""
Creates the manifold estimator if a string value is passed in,
validates other objects passed in.
"""
if not is_estimator(transformer):
... |
Fits the manifold on X and transforms the data to plot it on the axes.
The optional y specified can be used to declare discrete colors. If
the target is set to 'auto', this method also determines the target
type, and therefore what colors will be used.
Note also that fit records the amo... |
Returns the transformed data points from the manifold embedding.
Parameters
----------
X : array-like of shape (n, m)
A matrix or data frame with n instances and m features
Returns
-------
Xprime : array-like of shape (n, 2)
Returns the 2-dimensi... |
Draws the points described by X and colored by the points in y. Can be
called multiple times before finalize to add more scatter plots to the
axes, however ``fit()`` must be called before use.
Parameters
----------
X : array-like of shape (n, 2)
The matrix produced b... |
Add title and modify axes to make the image ready for display.
def finalize(self):
"""
Add title and modify axes to make the image ready for display.
"""
self.set_title(
'{} Manifold (fit in {:0.2f} seconds)'.format(
self._name, self.fit_time_.interval
... |
Determines the target color type from the vector y as follows:
- if y is None: only a single color is used
- if target is auto: determine if y is continuous or discrete
- otherwise specify supplied target type
This property will be used to compute the colors for each point.... |
Performs recursive feature elimination with cross-validation to determine
an optimal number of features for a model. Visualizes the feature subsets
with respect to the cross-validation score.
This helper function is a quick wrapper to utilize the RFECV visualizer
for one-off analysis.
Parameters
... |
Fits the RFECV with the wrapped model to the specified data and draws
the rfecv curve with the optimal number of features found.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_fe... |
Renders the rfecv curve.
def draw(self, **kwargs):
"""
Renders the rfecv curve.
"""
# Compute the curves
x = self.n_feature_subsets_
means = self.cv_scores_.mean(axis=1)
sigmas = self.cv_scores_.std(axis=1)
# Plot one standard deviation above and below ... |
Displays a bivariate scatter plot.
This helper function is a quick wrapper to utilize the ScatterVisualizer
(Transformer) for one-off analysis.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n, def... |
The fit method is the primary drawing input for the parallel coords
visualization since it has both the X and y data required for the
viz and the transform method does not.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with 2 f... |
Called from the fit method, this method creates a scatter plot that
draws each instance as a class or target colored point, whose location
is determined by the feature data set.
def draw(self, X, y, **kwargs):
"""Called from the fit method, this method creates a scatter plot that
draws ... |
Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments.
def finalize(self, **kwargs):
"""
Finalize executes any subclass-specific axes finalization steps.
... |
Quick method:
Create a color plot showing the best grid search scores across two
parameters.
This helper function is a quick wrapper to utilize GridSearchColorPlot
for one-off analysis.
If no `X` data is passed, the model is assumed to be fit already. This
allows quick exploration without wait... |
Removes rows that contain np.nan values in data. If y is given,
X and y will be filtered together so that their shape remains identical.
For example, rows in X with nans will also remove rows in y, or rows in y
with np.nans will also remove corresponding rows in X.
Parameters
------------
X : a... |
Remove rows from X and y where either contains nans.
def filter_missing_X_and_y(X, y):
"""Remove rows from X and y where either contains nans."""
y_nans = np.isnan(y)
x_nans = np.isnan(X).any(axis=1)
unioned_nans = np.logical_or(x_nans, y_nans)
return X[~unioned_nans], y[~unioned_nans] |
Warn if nans exist in a numpy array.
def warn_if_nans_exist(X):
"""Warn if nans exist in a numpy array."""
null_count = count_rows_with_nans(X)
total = len(X)
percent = 100 * null_count / total
if null_count > 0:
warning_message = \
'Warning! Found {} rows of {} ({:0.2f}%) with... |
Count the number of rows in 2D arrays that contain any nan values.
def count_rows_with_nans(X):
"""Count the number of rows in 2D arrays that contain any nan values."""
if X.ndim == 2:
return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum() |
Pretend to be a sklearn estimator, fit is called on creation
def fit(self, X, y):
"""
Pretend to be a sklearn estimator, fit is called on creation
"""
# note that GLM takes endog (y) and then exog (X):
# this is the reverse of sklearn's methods
self.glm_model = self.glm... |
The Missing Values Dispersion visualizer shows the locations of missing (nan)
values in the feature dataset by the order of the index.
When y targets are supplied to fit, the output dispersion plot is color
coded according to the target y that the element refers to.
Parameters
----------
alpha... |
Gets the locations of nans in feature data and returns
the coordinates in the matrix
def get_nan_locs(self, **kwargs):
"""Gets the locations of nans in feature data and returns
the coordinates in the matrix
"""
if np.issubdtype(self.X.dtype, np.string_) or np.issubdtype(self.X.d... |
Called from the fit method, this method creates a scatter plot that
draws each instance as a class or target colored point, whose location
is determined by the feature data set.
If y is not None, then it draws a scatter plot where each class is in a
different color.
def draw(self, X, y... |
Draws a multi dimensional dispersion chart, each color corresponds
to a different target variable.
def draw_multi_dispersion_chart(self, nan_locs):
"""Draws a multi dimensional dispersion chart, each color corresponds
to a different target variable.
"""
for index, nan_values in ... |
Projects the grid search results onto 2 dimensions.
The display value is taken as the max over the non-displayed dimensions.
Parameters
----------
cv_results : dict
A dictionary of results from the `GridSearchCV` object's `cv_results_`
attribute.
x_param : string
The name ... |
Projects the grid search results onto 2 dimensions.
The wrapped GridSearch object is assumed to be fit already.
The display value is taken as the max over the non-displayed dimensions.
Parameters
----------
x_param : string
The name of the parameter to be visualized... |
Calculates the difference threshold for a
given difference local maximum.
Parameters
-----------
ymx_i : float
The normalized y value of a local maximum.
def __threshold(self, ymx_i):
"""
Calculates the difference threshold for a
given difference loc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.