text
stringlengths
81
112k
Normalize tags contents and type: - append `device_name` as `device:` tag - normalize tags type - doesn't mutate the passed list, returns a new list def _normalize_tags_type(self, tags, device_name=None, metric_name=None): """ Normalize tags contents and type: - append `...
Normalize a text data to bytes (type `bytes`) so that the go bindings can handle it easily. def _to_bytes(self, data): """ Normalize a text data to bytes (type `bytes`) so that the go bindings can handle it easily. """ # TODO: On Python 3, move this `if` line to the `exc...
Create a config object from an instance dictionary def from_instance(instance): """ Create a config object from an instance dictionary """ url = instance.get('url') if not url: raise ConfigurationError("A URL must be specified in the instance") pshard_stats = is_affirmative(instance.ge...
Download the dataset from the hosted Yellowbrick data store and save it to the location specified by ``get_data_home``. The downloader verifies the download completed successfully and safely by comparing the expected signature with the SHA 256 signature of the downloaded archive file. ...
Contents returns a list of the files in the data directory. def contents(self): """ Contents returns a list of the files in the data directory. """ data = find_dataset_path( self.name, data_home=self.data_home, ext=None ) return os.listdir(data)
Returns the contents of the README.md file that describes the dataset in detail and contains attribution information. def README(self): """ Returns the contents of the README.md file that describes the dataset in detail and contains attribution information. """ path = fi...
Returns the contents of the meta.json file that describes important attributes about the dataset and modifies the behavior of the loader. def meta(self): """ Returns the contents of the meta.json file that describes important attributes about the dataset and modifies the behavior of the...
Returns the contents of the citation.bib file that describes the source and provenance of the dataset or to cite for academic work. def citation(self): """ Returns the contents of the citation.bib file that describes the source and provenance of the dataset or to cite for academic work....
Returns the dataset as two numpy arrays: X and y. Returns ------- X : array-like with shape (n_instances, n_features) A numpy array describing the instance features. y : array-like with shape (n_instances,) A numpy array describing the target vector. def to_num...
Returns the dataset as two pandas objects: X and y. Returns ------- X : DataFrame with shape (n_instances, n_features) A pandas DataFrame containing feature data and named columns. y : Series with shape (n_instances,) A pandas Series containing target data and a...
Returns the entire dataset as a single pandas DataFrame. Returns ------- df : DataFrame with shape (n_instances, n_columns) A pandas DataFrame containing the complete original data table including all targets (specified by the meta data) and all features (inc...
Return the unique labels assigned to the documents. def labels(self): """ Return the unique labels assigned to the documents. """ return [ name for name in os.listdir(self.root) if os.path.isdir(os.path.join(self.root, name)) ]
Returns the list of file names for all documents. def files(self): """ Returns the list of file names for all documents. """ return [ os.path.join(self.root, label, name) for label in self.labels for name in os.listdir(os.path.join(self.root, label)) ...
Read all of the documents from disk into an in-memory list. def data(self): """ Read all of the documents from disk into an in-memory list. """ def read(path): with open(path, 'r', encoding='UTF-8') as f: return f.read() return [ read(f) ...
Returns the label associated with each item in data. def target(self): """ Returns the label associated with each item in data. """ return [ os.path.basename(os.path.dirname(f)) for f in self.files ]
Fits the model and generates the silhouette visualization. def fit(self, X, y=None, **kwargs): """ Fits the model and generates the silhouette visualization. """ # TODO: decide to use this method or the score method to draw. # NOTE: Probably this would be better in score, but th...
Draw the silhouettes for each sample and the average score. Parameters ---------- labels : array-like An array with the cluster label for each silhouette sample, usually computed with ``predict()``. Labels are not stored on the visualizer so that the figure ...
Prepare the figure for rendering by setting the title and adjusting the limits on the axes, adding labels and a legend. def finalize(self): """ Prepare the figure for rendering by setting the title and adjusting the limits on the axes, adding labels and a legend. """ # ...
Computes the SHA256 signature of a file to verify that the file has not been modified in transit and that it is the correct version of the data. def sha256sum(path, blocksize=65536): """ Computes the SHA256 signature of a file to verify that the file has not been modified in transit and that it is the ...
Uses Scikit-Learn to fit a model to X and y then uses the resulting model to predict the curve based on the X values. This curve is drawn to the ax (matplotlib axis) which must be passed as the third variable. The estimator function can be one of the following: - ``'linear'``: Uses OLS to fit the...
Selects the best fit of the estimators already implemented by choosing the model with the smallest mean square error metric for the trained values. def fit_select_best(X, y): """ Selects the best fit of the estimators already implemented by choosing the model with the smallest mean square error metric ...
Uses OLS to fit the regression. def fit_linear(X, y): """ Uses OLS to fit the regression. """ model = linear_model.LinearRegression() model.fit(X, y) return model
Uses OLS with Polynomial order 2. def fit_quadratic(X, y): """ Uses OLS with Polynomial order 2. """ model = make_pipeline( PolynomialFeatures(2), linear_model.LinearRegression() ) model.fit(X, y) return model
Draws a 45 degree identity line such that y=x for all points within the given axes x and y limits. This function also registeres a callback so that as the figure is modified, the axes are updated and the line remains drawn correctly. Parameters ---------- ax : matplotlib Axes, default: None ...
Quick method: Creates a heatmap visualization of the sklearn.metrics.confusion_matrix(). A confusion matrix shows each combination of the true and predicted classes for a test data set. The default color map uses a yellow/orange/red color scale. The user can choose between displaying values as the...
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 of n instances with m features y : ...
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 conf...
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. Param...
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 features. y : ndarray or Series of length n ...
Precision-Recall Curve quick method: Parameters ---------- model : the Scikit-Learn estimator A classification model to score the precision-recall curve on. X : ndarray or DataFrame of shape n x m A feature array of n instances with m features the model is trained on. This arra...
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 On...
Generates the Precision-Recall curve on the specified test data. Returns ------- score_ : float Average precision, a summary of the plot as a weighted mean of precision at each threshold, weighted by the increase in recall from the previous threshold. def sc...
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 ...
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_: ...
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=...
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, col...
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_re...
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 array of one dimension or a pandas Series ax : matplotlib Axes, default: None This is ...
Draws a histogram with the reference value for binning as vertical lines. Parameters ---------- y : an array of one dimension or a pandas Series def draw(self, y, **kwargs): """ Draws a histogram with the reference value for binning as vertical lines. P...
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 passed to scikit-learn API. def fit(self, y, **kw...
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. ...
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_...
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 ...
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 by displaying how frequently each class occurs as a bar graph. The figur...
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 In balance mode, the bar chart is displayed with ea...
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 ...
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. ...
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_typ...
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 of the final transformer or estimat...
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_colum...
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 array is montonically decreasing. def is_monotonic(...
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, 0, 1], 0 ) == [0, 0, 0] def div_safe( numerator, ...
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)})^{power} If ``log=True``, the natural logarithm of the property va...
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 representation of the text .. seeals...
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 the model. .. seealso:: http://kldavenport.com/the-cost-fun...
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 c...
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 s...
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 ...
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 exten...
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 w...
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 tec...
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 : Pipeline Pipelined transformer for UMAP projections d...
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. Parameters ----------...
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...
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. Parameters ...
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 positive rate on the Y axis and the false positive rate on th...
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 An array or series of target or class values ...
Renders ROC-AUC plot. Called internally by score, possibly more than once Returns ------- ax : the axis with the plotted figure def draw(self): """ Renders ROC-AUC plot. Called internally by score, possibly more than once Returns ------- ...
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 ``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 resolving the estimator methods that re...
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)...
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....
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 def is_estimator(model): """ Determines if ...
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 def is_gridsearch(estimator): """ Returns True if the given es...
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. def is_dataframe(obj): """ Returns True if the given object is a Pandas Data Frame. Parameters ---------- obj: instance ...
Returns True if the given object is a Pandas Series. Parameters ---------- obj: instance The object to test whether or not is a Pandas Series. def is_series(obj): """ Returns True if the given object is a Pandas Series. Parameters ---------- obj: instance The object to...
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. def is_structured_array(obj): """ Returns True if the given object is a Numpy Structured Array. Parameters ---------- ...
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. Parameters ---------- model : the Scikit-Learn estimator (should be a...
Quick method: Divides the dataset X, y into a train and test split (the size of the splits determined by test_size) then plots the training and test residuals agains the predicted value for the given model. This helper function is a quick wrapper to utilize the ResidualsPlot ScoreVisualizer for on...
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. ...
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 ------ ax : the axis with the plotted figure def dr...
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. ...
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 " ...
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 Scikit-Learn API. Returns ------- ...
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 y (also y_test) is the independent actual variables to score agains...
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. Parameters ---------- ...
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 for DiscriminationThreshold. Visualizes how precision, recall, f1 score, and queue rate change as the discrimination threshold increases. For probabilistic, binary classifiers, the discrimination threshold is the probability at which you choose the positive class over the negative. General...
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 b...
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 differently but in a deterministic fashion for testing purp...
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 id...
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( ...
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 splitt...
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 = frozens...
DecisionBoundariesVisualizer is a bivariate data visualization algorithm that plots the decision boundaries of each class. This helper function is a quick wrapper to utilize the DecisionBoundariesVisualizers for one-off analysis. Parameters ---------- model : the Scikit-Learn estimator, re...
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 background. This must be specified in RGBA with values between 0 and 1 (note, this is the default ...
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. Parameters ---------- ...
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 features y : ndarray or Series of length n ...