INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Quick method:
def confusion_matrix(model, X, y, ax=None, classes=None, sample_weight=None, percent=False, label_encoder=None, cmap='YlOrRd', fontsize=None, random_state=None, **kwargs): """Quick method: Creates a heatmap visualization of the sklearn.metrics.confusion_matrix(). A...
Draws a confusion matrix based on the test data supplied by comparing predictions on instances X with the true values specified by the target vector y.
def score(self, X, y): """ Draws a confusion matrix based on the test data supplied by comparing predictions on instances X with the true values specified by the target vector y. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix o...
Renders the classification report ; must be called after score.
def draw(self): """ Renders the classification report; must be called after score. """ # Perform display related manipulations on the confusion matrix data cm_display = self.confusion_matrix_ # Convert confusion matrix to percent of each row, i.e. the # predicte...
Produce a two or three dimensional principal component plot of the data array X projected onto it s largest sequential principal components. It is common practice to scale the data array X before applying a PC decomposition. Variable scaling can be controlled using the scale argument.
def pca_decomposition(X, y=None, ax=None, features=None, scale=True, proj_dim=2, proj_features=False, color=None, colormap=palettes.DEFAULT_SEQUENCE, alpha=0.75, random_state=None, **kwargs): """Produce a two or three dimensional principal component ...
Fits the PCA transformer transforms the data in X then draws the decomposition in either 2D or 3D space as a scatter plot.
def fit(self, X, y=None, **kwargs): """ Fits the PCA transformer, transforms the data in X, then draws the decomposition in either 2D or 3D space as a scatter plot. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m f...
Precision - Recall Curve quick method:
def precision_recall_curve(model, X, y, X_test=None, y_test=None, ax=None, train_size=0.8, random_state=None, shuffle=True, **kwargs): """Precision-Recall Curve quick method: Parameters ---------- model : the Scikit-Learn estimator A classification model to score the ...
Fit the classification model ; if y is multi - class then the estimator is adapted with a OneVsRestClassifier strategy otherwise the estimator is fit directly.
def fit(self, X, y=None): """ Fit the classification model; if y is multi-class, then the estimator is adapted with a OneVsRestClassifier strategy, otherwise the estimator is fit directly. """ # The target determines what kind of estimator is fit ttype = type_of_t...
Generates the Precision - Recall curve on the specified test data.
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 ...
Draws the precision - recall curves computed in score on the axes.
def draw(self): """ Draws the precision-recall curves computed in score on the axes. """ if self.iso_f1_curves: for f1 in self.iso_f1_values: x = np.linspace(0.01, 1) y = f1 * x / (2 * x - f1) self.ax.plot(x[y>=0], y[y>=0], colo...
Draw the precision - recall curves in the binary case
def _draw_binary(self): """ Draw the precision-recall curves in the binary case """ self._draw_pr_curve(self.recall_, self.precision_, label="binary PR curve") self._draw_ap_score(self.score_)
Draw the precision - recall curves in the multiclass case
def _draw_multiclass(self): """ Draw the precision-recall curves in the multiclass case """ # TODO: handle colors better with a mapping and user input if self.per_class: for cls in self.classes_: precision = self.precision_[cls] recall ...
Helper function to draw a precision - recall curve with specified settings
def _draw_pr_curve(self, recall, precision, label=None): """ Helper function to draw a precision-recall curve with specified settings """ self.ax.step( recall, precision, alpha=self.line_opacity, where='post', label=label ) if self.fill_area: self....
Helper function to draw the AP score annotation
def _draw_ap_score(self, score, label=None): """ Helper function to draw the AP score annotation """ label = label or "Avg Precision={:0.2f}".format(score) if self.ap_score: self.ax.axhline( y=score, color="r", ls="--", label=label )
The precision_recall_curve metric requires target scores that can either be the probability estimates of the positive class confidence values or non - thresholded measures of decisions ( as returned by a decision function ).
def _get_y_scores(self, X): """ The ``precision_recall_curve`` metric requires target scores that can either be the probability estimates of the positive class, confidence values, or non-thresholded measures of decisions (as returned by a "decision function"). """ ...
BalancedBinningReference generates a histogram with vertical lines showing the recommended value point to bin your data so they can be evenly distributed in each bin.
def balanced_binning_reference(y, ax=None, target='Frequency', bins=4, **kwargs): """ BalancedBinningReference generates a histogram with vertical lines showing the recommended value point to bin your data so they can be evenly distributed in each bin. Parameters ---------- y : an arra...
Draws a histogram with the reference value for binning as vertical lines.
def draw(self, y, **kwargs): """ Draws a histogram with the reference value for binning as vertical lines. Parameters ---------- y : an array of one dimension or a pandas Series """ # draw the histogram hist, bin_edges = np.histogram(y, bins=self...
Sets up y for the histogram and checks to ensure that y is of the correct data type. Fit calls draw.
def fit(self, y, **kwargs): """ Sets up y for the histogram and checks to ensure that ``y`` is of the correct data type. Fit calls draw. Parameters ---------- y : an array of one dimension or a pandas Series kwargs : dict keyword arguments pa...
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. Parameters ---------- kwargs: generic keyword arguments. """ self.ax.set_xlabel(self.target) for tk in...
Downloads all the example datasets to the data directory specified by get_data_home. This function ensures that all datasets are available for use with the examples.
def download_all(data_home=None, replace=False): """ Downloads all the example datasets to the data directory specified by ``get_data_home``. This function ensures that all datasets are available for use with the examples. """ for _, meta in DATASETS.items(): download_data( m...
Cleans up all the example datasets in the data directory specified by get_data_home either to clear up disk space or start from fresh.
def cleanup_all(data_home=None): """ Cleans up all the example datasets in the data directory specified by ``get_data_home`` either to clear up disk space or start from fresh. """ removed = 0 for name, meta in DATASETS.items(): _, ext = os.path.splitext(meta['url']) removed += cl...
Quick method:
def class_balance(y_train, y_test=None, ax=None, labels=None, **kwargs): """Quick method: One of the biggest challenges for classification models is an imbalance of classes in the training data. This function vizualizes the relationship of the support for each class in both the training and test data b...
Fit the visualizer to the the target variables which must be 1D vectors containing discrete ( classification ) data. Fit has two modes:
def fit(self, y_train, y_test=None): """ Fit the visualizer to the the target variables, which must be 1D vectors containing discrete (classification) data. Fit has two modes: 1. Balance mode: if only y_train is specified 2. Compare mode: if both train and test are specified ...
Renders the class balance chart on the specified axes from support.
def draw(self): """ Renders the class balance chart on the specified axes from support. """ # Number of colors is either number of classes or 2 colors = resolve_colors(len(self.support_)) if self._mode == BALANCE: self.ax.bar( np.arange(len(se...
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. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title self.set_title( ...
Raises a value error if the target is not a classification target.
def _validate_target(self, y): """ Raises a value error if the target is not a classification target. """ # Ignore None values if y is None: return y_type = type_of_target(y) if y_type not in ("binary", "multiclass"): raise YellowbrickValu...
Detects the model name for a Scikit - Learn model or pipeline.
def get_model_name(model): """ Detects the model name for a Scikit-Learn model or pipeline. Parameters ---------- model: class or instance The object to determine the name for. If the model is an estimator it returns the class name; if it is a Pipeline it returns the class name ...
Checks if numeric feature columns exist in ndarray
def has_ndarray_int_columns(features, X): """ Checks if numeric feature columns exist in ndarray """ _, ncols = X.shape if not all(d.isdigit() for d in features if isinstance(d, str)) or not isinstance(X, np.ndarray): return False ndarray_columns = np.arange(0, ncols) feature_cols = np.uniqu...
Tests whether a vector a has monotonicity.
def is_monotonic(a, increasing=True): """ Tests whether a vector a has monotonicity. Parameters ---------- a : array-like Array that should be tested for monotonicity increasing : bool, default: True Test if the array is montonically increasing, otherwise test if the ar...
Ufunc - extension that returns 0 instead of nan when dividing numpy arrays
def div_safe( numerator, denominator ): """ Ufunc-extension that returns 0 instead of nan when dividing numpy arrays Parameters ---------- numerator: array-like denominator: scalar or array-like that can be validly divided by the numerator returns a numpy array example: div_safe( [-1...
Converts an array of property values ( e. g. a metric or score ) to values that are more useful for marker sizes line widths or other visual sizes. The new sizes are computed as:
def prop_to_size(vals, mi=0.0, ma=5.0, power=0.5, log=False): """ Converts an array of property values (e.g. a metric or score) to values that are more useful for marker sizes, line widths, or other visual sizes. The new sizes are computed as: y = mi + (ma -mi)(\frac{x_i - min(x){max(x) - min(x...
Returns a slug of given text normalizing unicode data for file - safe strings. Used for deciding where to write images to disk.
def slugify(text): """ Returns a slug of given text, normalizing unicode data for file-safe strings. Used for deciding where to write images to disk. Parameters ---------- text : string The string to slugify Returns ------- slug : string A normalized slug representa...
Compute the mean distortion of all samples.
def distortion_score(X, labels, metric='euclidean'): """ Compute the mean distortion of all samples. The distortion is computed as the the sum of the squared distances between each observation and its closest centroid. Logically, this is the metric that K-Means attempts to minimize as it is fitting...
Fits n KMeans models where n is the length of self. k_values_ storing the silhouette scores in the self. k_scores_ attribute. The elbow and silhouette score corresponding to it are stored in self. elbow_value and self. elbow_score respectively. This method finishes up by calling draw to create the plot.
def fit(self, X, y=None, **kwargs): """ Fits n KMeans models where n is the length of ``self.k_values_``, storing the silhouette scores in the ``self.k_scores_`` attribute. The "elbow" and silhouette score corresponding to it are stored in ``self.elbow_value`` and ``self.elbow_sc...
Draw the elbow curve for the specified scores and values of K.
def draw(self): """ Draw the elbow curve for the specified scores and values of K. """ # Plot the silhouette score against k self.ax.plot(self.k_values_, self.k_scores_, marker="D") if self.locate_elbow and self.elbow_value_!=None: elbow_label = "$elbow\ at\ k...
Prepare the figure for rendering by setting the title as well as the X and Y axis labels and adding the legend.
def finalize(self): """ Prepare the figure for rendering by setting the title as well as the X and Y axis labels and adding the legend. """ # Get the metric name metric = self.scoring_metric.__name__.replace("_", " ").title() # Set the title self...
Saves the figure to the gallery directory
def savefig(viz, name, gallery=GALLERY): """ Saves the figure to the gallery directory """ if not path.exists(gallery): os.makedirs(gallery) # Must save as png if len(name.split(".")) > 1: raise ValueError("name should not specify extension") outpath = path.join(gallery, na...
A single entry point to rendering all visualizations in the visual pipeline. The rendering for the output depends on the backend context but for path based renderings ( e. g. saving to a file ) specify a directory and extension to compse an outpath to save each visualization ( file names will be based on the named step...
def poof(self, outdir=None, ext=".pdf", **kwargs): """ A single entry point to rendering all visualizations in the visual pipeline. The rendering for the output depends on the backend context, but for path based renderings (e.g. saving to a file), specify a directory and extensio...
Fit the model and transforms and then call poof.
def fit_transform_poof(self, X, y=None, outpath=None, **kwargs): """ Fit the model and transforms and then call poof. """ self.fit_transform(X, y, **kwargs) self.poof(outpath, **kwargs)
Display a projection of a vectorized corpus in two dimensions using UMAP ( Uniform Manifold Approximation and Projection ) a nonlinear dimensionality reduction method that is particularly well suited to embedding in two or three dimensions for visualization as a scatter plot. UMAP is a relatively new technique but is o...
def umap(X, y=None, ax=None, classes=None, colors=None, colormap=None, alpha=0.7, **kwargs): """ Display a projection of a vectorized corpus in two dimensions using UMAP (Uniform Manifold Approximation and Projection), a nonlinear dimensionality reduction method that is particularly well ...
Creates an internal transformer pipeline to project the data set into 2D space using UMAP. This method will reset the transformer on the class.
def make_transformer(self, umap_kwargs={}): """ Creates an internal transformer pipeline to project the data set into 2D space using UMAP. This method will reset the transformer on the class. Parameters ---------- Returns ------- transformer : Pi...
The fit method is the primary drawing input for the UMAP projection since the visualization requires both X and an optional y value. The fit method expects an array of numeric vectors so text documents must be vectorized before passing them to this method.
def fit(self, X, y=None, **kwargs): """ The fit method is the primary drawing input for the UMAP projection since the visualization requires both X and an optional y value. The fit method expects an array of numeric vectors, so text documents must be vectorized before passing the...
Called from the fit method this method draws the UMAP scatter plot from a set of decomposed points in 2 dimensions. This method also accepts a third dimension target which is used to specify the colors of each of the points. If the target is not specified then the points are plotted as a single cloud to show similar do...
def draw(self, points, target=None, **kwargs): """ Called from the fit method, this method draws the UMAP scatter plot, from a set of decomposed points in 2 dimensions. This method also accepts a third dimension, target, which is used to specify the colors of each of the points. ...
Produce a plot of the explained variance produced by a dimensionality reduction algorithm using n = 1 to n = n_components dimensions. This is a single plot to help identify the best trade off between number of dimensions and amount of information retained within the data.
def explained_variance_visualizer(X, y=None, ax=None, scale=True, center=True, colormap=palettes.DEFAULT_SEQUENCE, **kwargs): """Produce a plot of the explained variance produced by a dimensionality reduction algorithm using n=1 to n=...
ROCAUC Quick method:
def roc_auc(model, X, y=None, ax=None, **kwargs): """ROCAUC Quick method: Receiver Operating Characteristic (ROC) curves are a measure of a classifier's predictive quality that compares and visualizes the tradeoff between the models' sensitivity and specificity. The ROC curve displays the true posi...
Generates the predicted target values using the Scikit - Learn estimator.
def score(self, X, y=None, **kwargs): """ Generates the predicted target values using the Scikit-Learn estimator. 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 ...
Renders ROC - AUC plot. Called internally by score possibly more than once
def draw(self): """ Renders ROC-AUC plot. Called internally by score, possibly more than once Returns ------- ax : the axis with the plotted figure """ colors = self.colors[0:len(self.classes_)] n_classes = len(colors) # If it's a binary ...
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. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title and add the legend self.s...
The roc_curve metric requires target scores that can either be the probability estimates of the positive class confidence values or non - thresholded measure of decisions ( as returned by decision_function ).
def _get_y_scores(self, X): """ The ``roc_curve`` metric requires target scores that can either be the probability estimates of the positive class, confidence values or non- thresholded measure of decisions (as returned by "decision_function"). This method computes the scores by...
Compute the micro average scores for the ROCAUC curves.
def _score_micro_average(self, y, y_pred, classes, n_classes): """ Compute the micro average scores for the ROCAUC curves. """ # Convert y to binarized array for micro and macro scores y = label_binarize(y, classes=classes) if n_classes == 2: y = np.hstack((1-...
Compute the macro average scores for the ROCAUC curves.
def _score_macro_average(self, n_classes): """ Compute the macro average scores for the ROCAUC curves. """ # Gather all FPRs all_fpr = np.unique(np.concatenate([self.fpr[i] for i in range(n_classes)])) avg_tpr = np.zeros_like(all_fpr) # Compute the averages per c...
Determines if a model is an estimator using issubclass and isinstance.
def is_estimator(model): """ Determines if a model is an estimator using issubclass and isinstance. Parameters ---------- estimator : class or instance The object to test if it is a Scikit-Learn clusterer, especially a Scikit-Learn estimator or Yellowbrick visualizer """ if ...
Returns True if the given estimator is a clusterer.
def is_gridsearch(estimator): """ Returns True if the given estimator is a clusterer. Parameters ---------- estimator : class or instance The object to test if it is a Scikit-Learn clusterer, especially a Scikit-Learn estimator or Yellowbrick visualizer """ from sklearn.mod...
Returns True if the given object is a Pandas Data Frame.
def is_dataframe(obj): """ Returns True if the given object is a Pandas Data Frame. Parameters ---------- obj: instance The object to test whether or not is a Pandas DataFrame. """ try: # This is the best method of type checking from pandas import DataFrame r...
Returns True if the given object is a Pandas Series.
def is_series(obj): """ Returns True if the given object is a Pandas Series. Parameters ---------- obj: instance The object to test whether or not is a Pandas Series. """ try: # This is the best method of type checking from pandas import Series return isinsta...
Returns True if the given object is a Numpy Structured Array.
def is_structured_array(obj): """ Returns True if the given object is a Numpy Structured Array. Parameters ---------- obj: instance The object to test whether or not is a Numpy Structured Array. """ if isinstance(obj, np.ndarray) and hasattr(obj, 'dtype'): if obj.dtype.names...
Quick method:
def prediction_error(model, X, y=None, ax=None, alpha=0.75, **kwargs): """ Quick method: Plot the actual targets from the dataset against the predicted values generated by our model(s). This helper function is a quick wrapper to utilize the PredictionError ScoreVisualizer for one-off analysis....
Quick method:
def residuals_plot(model, X, y, ax=None, hist=True, test_size=0.25, train_color='b', test_color='g', line_color=LINE_COLOR, random_state=None, ...
The score function is the hook for visual interaction. Pass in test data and the visualizer will create predictions on the data and evaluate them with respect to the test values. The evaluation will then be passed to draw () and the result of the estimator score will be returned.
def score(self, X, y=None, **kwargs): """ The score function is the hook for visual interaction. Pass in test data and the visualizer will create predictions on the data and evaluate them with respect to the test values. The evaluation will then be passed to draw() and the result...
Parameters ---------- y: ndarray or Series of length n An array or series of target or class values
def draw(self, y, y_pred): """ Parameters ---------- y : ndarray or Series of length n An array or series of target or class values y_pred : ndarray or Series of length n An array or series of predicted target values Returns ----...
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. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title on the plot self.set_title...
Returns the histogram axes creating it only on demand.
def hax(self): """ Returns the histogram axes, creating it only on demand. """ if make_axes_locatable is None: raise YellowbrickValueError(( "residuals histogram requires matplotlib 2.0.2 or greater " "please upgrade matplotlib or set hist=Fals...
Parameters ---------- X: ndarray or DataFrame of shape n x m A matrix of n instances with m features
def fit(self, X, y, **kwargs): """ 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 values kwargs: keyword arguments passed to Sci...
Generates predicted target values using the Scikit - Learn estimator.
def score(self, X, y=None, train=False, **kwargs): """ Generates predicted target values using the Scikit-Learn estimator. Parameters ---------- X : array-like X (also X_test) are the dependent variables of test set to predict y : array-like ...
Draw the residuals against the predicted value for the specified split. It is best to draw the training split first then the test split so that the test split ( usually smaller ) is above the training split ; particularly if the histogram is turned on.
def draw(self, y_pred, residuals, train=False, **kwargs): """ Draw the residuals against the predicted value for the specified split. It is best to draw the training split first, then the test split so that the test split (usually smaller) is above the training split; particularl...
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. Parameters ---------- kwargs: generic keyword arguments. """ # Add the title to the plot self.set_title...
Quick method for DiscriminationThreshold.
def discrimination_threshold(model, X, y, ax=None, n_trials=50, cv=0.1, fbeta=1.0, argmax='fscore', exclude=None, quantiles=QUANTILES_MEDIAN_80, random_state=None, **kwargs): """Quick method for DiscriminationThreshold. Visu...
Fit is the entry point for the visualizer. Given instances described by X and binary classes described in the target y fit performs n trials by shuffling and splitting the dataset then computing the precision recall f1 and queue rate scores for each trial. The scores are aggregated by the quantiles expressed then drawn...
def fit(self, X, y, **kwargs): """ Fit is the entry point for the visualizer. Given instances described by X and binary classes described in the target y, fit performs n trials by shuffling and splitting the dataset then computing the precision, recall, f1, and queue rate scores ...
Splits the dataset fits a clone of the estimator then scores it according to the required metrics.
def _split_fit_score_trial(self, X, y, idx=0): """ Splits the dataset, fits a clone of the estimator, then scores it according to the required metrics. The index of the split is added to the random_state if the random_state is not None; this ensures that every split is shuffled ...
Draws the cv scores as a line chart on the current axes.
def draw(self): """ Draws the cv scores as a line chart on the current axes. """ # Set the colors from the supplied values or reasonable defaults color_values = resolve_colors(n_colors=4, colors=self.color) for idx, metric in enumerate(METRICS): # Skip any ex...
Validate the quantiles passed in. Returns the np array if valid.
def _check_quantiles(self, val): """ Validate the quantiles passed in. Returns the np array if valid. """ if len(val) != 3 or not is_monotonic(val) or not np.all(val < 1): raise YellowbrickValueError( "quantiles must be a sequence of three " "m...
Validate the cv method passed in. Returns the split strategy if no validation exception is raised.
def _check_cv(self, val, random_state=None): """ Validate the cv method passed in. Returns the split strategy if no validation exception is raised. """ # Use default splitter in this case if val is None: val = 0.1 if isinstance(val, float) and val <= 1.0: ...
Validate the excluded metrics. Returns the set of excluded params.
def _check_exclude(self, val): """ Validate the excluded metrics. Returns the set of excluded params. """ if val is None: exclude = frozenset() elif isinstance(val, str): exclude = frozenset([val.lower()]) else: exclude = frozenset(map(...
DecisionBoundariesVisualizer is a bivariate data visualization algorithm that plots the decision boundaries of each class.
def decisionviz(model, X, y, colors=None, classes=None, features=None, show_scatter=True, step_size=0.0025, markers=None, pcolormesh_alpha=0.8, scatter_alpha=1....
Takes a background color and returns the appropriate light or dark text color. Users can specify the dark and light text color or accept the defaults of black and white
def find_text_color(base_color, dark_color="black", light_color="white", coef_choice=0): """ Takes a background color and returns the appropriate light or dark text color. Users can specify the dark and light text color, or accept the defaults of 'black' and 'white' base_color: The color of the backgro...
Displays the most informative features in a model by showing a bar chart of features ranked by their importances. Although primarily a feature engineering mechanism this visualizer requires a model that has either a coef_ or feature_importances_ parameter after fit.
def feature_importances(model, X, y=None, ax=None, labels=None, relative=True, absolute=False, xlabel=None, stack=False, **kwargs): """ Displays the most informative features in a model by showing a bar chart of features ranked by their importances. Although p...
Fits the estimator to discover the feature importances described by the data then draws those importances as a bar plot.
def fit(self, X, y=None, **kwargs): """ Fits the estimator to discover the feature importances described by the data, then draws those importances as a bar plot. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m feat...
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): raise NotFitted("missing required param '{}'".format(pa...
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)) # Set the xlabel self.ax.set_xlabel(self._ge...
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: continue raise YellowbrickTypeError( ...
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.
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:
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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...