INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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 hasattr(self.estimator, "coef_"):
if self.relative:
... |
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 :... | def target_color_type(y):
"""
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.
... |
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 histograms
if necessary and modifying the aspect ratio. Does not modify the axes or the
layout if self.hist is False or None.
"""
# Ensure the axes are created if not hist, then ret... |
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... | def fit(self, X, y=None):
"""
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... |
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 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.
... |
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 plot square using make_axes_locatable
# x0,x1 = self.ax.get_xlim()
... |
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 possible from this point in the stack.
"""
try:
if is_dataframe(data):
# Assume column indexing
... |
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
... | def fit(self, X, y=None, **kwargs):
"""
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
... |
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()
# Instantiate the classification mo... |
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`` ... | def cv_scores(model, X, y, ax=None, cv=None, scoring=None, **kwargs):
"""
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
---------... |
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... | def fit(self, X, y, **kwargs):
"""
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)
Tr... |
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 and places a dashed horizontal line that represents the
average value of the scores.
"""
color = kwargs.pop("color", "b")
width = kwargs.pop("width", 0... |
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))
# Add the legend
loc = kwargs.pop("loc", "best")
edg... |
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 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
"""
corrs = np.zeros((X.shape[1... |
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... | def rank1d(X, y=None, ax=None, algorithm='shapiro', features=None,
orient='h', show_feature_names=True, **kwargs):
"""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.
... |
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
... | def rank2d(X, y=None, ax=None, algorithm='pearson', features=None,
show_feature_names=True, colormap='RdBu_r', **kwargs):
"""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 R... |
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
------... | def transform(self, X, **kwargs):
"""
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... |
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... | def rank(self, X, algorithm=None):
"""
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 defaul... |
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 finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: dict
generic keyword arguments
"""
# Set the title
self.set_... |
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')
# Add ticks and tick labels
self.ax.set_y... |
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_like(self.ranks_, dtype=np.bool)
mask[np.triu_in... |
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... | def class_prediction_error(
model,
X,
y=None,
ax=None,
classes=None,
test_size=0.2,
random_state=None,
**kwargs):
"""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 visualize... |
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... | def score(self, X, y, **kwargs):
"""
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 :... |
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,
n_colors=len(self.classes_))
for idx, ro... |
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.arange(len(self.classes_))
# Set the title
self.set_title("Class Prediction Error for {}".format(self... |
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
------... | def missing_bar(X, y=None, ax=None, classes=None, width=0.5, color='black', **kwargs):
"""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 ... |
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 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.
"""
nan_c... |
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 enumerate(nan_col_counts):
label, nan_col_counts = nan_values
if index == 0:
... |
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.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Set the title
self.set_title(
... |
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... | def feature_correlation(X, y, ax=None, method='pearson',
labels=None, sort=False, feature_index=None,
feature_names=None, **kwargs):
"""
Displays the correlation between features and dependent variables.
This visualizer can be used side-by-side with
yello... |
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... | def fit(self, X, y, **kwargs):
"""
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
... |
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 bars
self.ax.set_yticks(pos)
self.ax.set_yticklabels(self.... |
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 column names if a dataframe
if is_dataframe(X):
self.features_ = np.ar... |
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
if filter_names is supplied, a new feature_index
is computed from those names.
"""
if self.feature_index:
if self.feature_names:
... |
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(ax=axes[0], classes=["unoccupied", "o... |
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 = PredictionError(LassoCV(alphas=alphas), ax=... |
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 multiple axes objects). The visualizer automatically creates an
axes for the user if one has not been specified.
"""
if not hasattr(self, "_ax") or self._ax is None:
se... |
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:
fig = plt.gcf()
self._size = fig.get_size_inches()*fig.dpi
return self._siz... |
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... | def poof(self, outpath=None, clear_figure=False, **kwargs):
"""
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 w... |
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: string, default: None
Add title to figure or if None leave untitled.
"""
title = self.title or title
if title is not None:
self.a... |
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
... | def predict(self, X, y):
"""
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
... |
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 downloaded, "
"use the yellowbrick.download module ... |
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 ... | def get_data_home(path=None):
"""
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 locate... |
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... | def find_dataset_path(dataset, data_home=None, fname=None, ext=".csv.gz", raises=True):
"""
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 YELLOWBRIC... |
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... | def dataset_exists(dataset, data_home=None):
"""
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
... |
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
----... | def dataset_archive(dataset, signature, data_home=None, ext=".zip"):
"""
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
sha2... |
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... | def cleanup_dataset(dataset, data_home=None, ext=".zip"):
"""
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.DAT... |
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):
"""
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 me... |
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):
"""
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.
... |
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
... | def fit(self, X, y=None, **kwargs):
"""
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
... |
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
--------
... | def set_color_codes(palette="accent"):
"""
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... |
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... | def color_sequence(palette=None, n_colors=None):
"""
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
-... |
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 array.
See Seaborn's palplot function for inspiration.
Parameters
----------
size : int
scaling factor for size of the plot
"""
n = len(self)
fig, ax = p... |
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".format(algorithm))
oz = Manifold(
ax=... |
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
... | def download_data(url, signature, data_home=None, replace=False, extract=True):
"""
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.
Parame... |
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... | def set_aesthetic(palette="yellowbrick", font="sans-serif", font_scale=1,
color_codes=True, rc=None):
"""
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
-----... |
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... | def _axes_style(style=None, rc=None):
"""
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 lik... |
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 ... | def set_style(style=None, rc=None):
"""
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}
... |
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... | def _set_context(context=None, font_scale=1, rc=None):
"""
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 si... |
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 ... | def set_palette(palette, n_colors=None, color_codes=False):
"""
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_palet... |
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 ... | def dispersion(words, corpus, y=None, ax=None, colors=None, colormap=None,
labels=None, annotate_docs=False, ignore_case=False, **kwargs):
""" Displays lexical dispersion plot for words in a corpus
This helper function is a quick wrapper to utilize the DisperstionPlot
Visualizer for one-off ... |
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... | def fit(self, X, y=None, **kwargs):
"""
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 docume... |
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 the plot on it.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Resolve the labels with the classes
labels = sel... |
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
finalization steps. The user calls poof & poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments.
"""
self.ax.set_ylim(-1, len(self.indexed_wor... |
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... | def manifold_embedding(
X,
y=None,
ax=None,
manifold="lle",
n_neighbors=10,
colors=None,
target=AUTO,
alpha=0.7,
random_state=None,
**kwargs):
"""Quick method for Manifold visualizer.
The Manifold visualizer provides high dimensional visualization for feature
analysi... |
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):
if transformer not in self.ALGORITHMS:
raise YellowbrickValueError(
... |
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... | def fit_transform(self, X, y=None):
"""
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 w... |
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... | def transform(self, X):
"""
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 sh... |
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... | def draw(self, X, y=None):
"""
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... |
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
)
)
self.ax.set_xticklabels([])
se... |
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. | def _determine_target_color_type(self, y):
"""
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
T... |
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
... | def rfecv(model, X, y, ax=None, step=1, groups=None, cv=None,
scoring=None, **kwargs):
"""
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 h... |
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... | def fit(self, X, y=None):
"""
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... |
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 the mean
self.ax.f... |
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... | def scatterviz(X,
y=None,
ax=None,
features=None,
classes=None,
color=None,
colormap=None,
markers=None,
alpha=1.0,
**kwargs):
"""Displays a bivariate scatter plot.
This helper... |
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... | def fit(self, X, y=None, **kwargs):
"""
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 ... |
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 each instance as a class or target colored point, whose location
is determined by the feature data set.
"""
# Set the axes limits
self.ax.set_xlim([-1,1])
... |
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.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Divide out the two features
feature_one... |
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... | def gridsearch_color_plot(model, x_param, y_param, X=None, y=None, ax=None,
**kwargs):
"""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 analysi... |
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... | def filter_missing(X, y=None):
"""
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.... |
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 nan values. Only ' \
'com... |
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_partial(y, X)
self.glm_results = self.glm_model.fit()... |
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... | def missing_dispersion(X, y=None, ax=None, classes=None, alpha=0.5, marker="|", **kwargs):
"""
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
... |
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.dtype, np.unicode_):
mask = np.where( self.X == '' )
nan_matrix = np.ze... |
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, **kwargs):
"""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
... |
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 enumerate(nan_locs):
label, nan_locations = nan_values
# if features passed in then... |
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 ... | def param_projection(cv_results, x_param, y_param, metric='mean_test_score'):
"""
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 `GridS... |
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... | def param_projection(self, x_param, y_param, metric):
"""
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
----------
... |
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 local maximum.
Parameters
-----------
ymx_i : float
The normalized y value of a local maximum.
"""
return ymx_i - (self.S * np.diff(self.xsn).mean()) |
Finds and returns the "knee"or "elbow" value, the normalized knee
value, and the x value where the knee is located. | def find_knee(self, ):
"""
Finds and returns the "knee"or "elbow" value, the normalized knee
value, and the x value where the knee is located.
"""
if not self.xmx_idx.size:
warning_message = \
'No "knee" or "elbow point" detected ' \
'... |
Plots the normalized curve, the distance curve (xd, ysn) and the
knee, if it exists. | def plot_knee_normalized(self, ):
"""
Plots the normalized curve, the distance curve (xd, ysn) and the
knee, if it exists.
"""
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 8))
plt.plot(self.xsn, self.ysn)
plt.plot(self.xd, self.yd, 'r')
... |
Plot the curve and the knee, if it exists | def plot_knee(self, ):
"""
Plot the curve and the knee, if it exists
"""
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 8))
plt.plot(self.x, self.y)
plt.vlines(self.knee, plt.ylim()[0], plt.ylim()[1]) |
A simple pass-through method; calls fit on the estimator and then
draws the alpha-error plot. | def fit(self, X, y, **kwargs):
"""
A simple pass-through method; calls fit on the estimator and then
draws the alpha-error plot.
"""
self.estimator.fit(X, y, **kwargs)
self.draw()
return self |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.