INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 `device_name` as `device:` tag - normalize tags type - doesn't mutate the passed list, returns a new list """ normalized_tags = [] if ...
Turn a metric into a well-formed metric name prefix.b.c :param metric The metric name to normalize :param prefix A prefix to to add to the normalized name, default None :param fix_case A boolean, indicating whether to make sure that the metric name returned is in "snake_case"
def normalize(self, metric, prefix=None, fix_case=False): """ Turn a metric into a well-formed metric name prefix.b.c :param metric The metric name to normalize :param prefix A prefix to to add to the normalized name, default None :param fix_case A boolean, indicating whe...
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 `device_name` as `device:` tag - normalize tags type - doesn't mutate the passed list, returns a new list """ normalized_tags = [] if ...
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 `except` branch # as the common case will indeed no longer be bytes. if not isinstance(da...
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.get('pshard_stats', False)) pshard_graceful_to = i...
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. ...
def download(self, replace=False): """ 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 2...
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 = find_dataset_path( self.name, data_home=self.data_home, fname="README.md" ) with open(path, 'r') as f...
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 loader. """ path = find_dataset_path( self.name, data_home=self.data_home, fname="meta.json", raises=False ) ...
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. """ path = find_dataset_path( self.name, data_home=self.data_home, fname="meta.json", raises=False ) ...
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_numpy(self): """ 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 d...
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...
def to_pandas(self): """ 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 p...
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...
def to_dataframe(self): """ 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 ...
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) for f in self.files ]
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 the standard score # is a little different and I'm not...
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 ...
def draw(self, labels): """ 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 th...
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. """ # Set the title self.set_title(( "Silhouette Plot of {} Clustering for {} Samples in {} Centers" ).form...
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 correct version of the data. """ sig = hashlib.sha256() with open(path, 'rb') as f: buf = f.read(blocksize) while len(buf)...
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 for the trained values. """ models = [fit(X,y) for fit in [fit_linear, fit_quadratic]] errors = map(lambda model: mse(y, model.predict(X)), m...
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 ...
def draw_identity_line(ax=None, dynamic=True, **kwargs): """ 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. ...
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...
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. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features 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...
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 ...
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: 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...
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. 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 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. Parameters ---------- y : an array of one dimension or a pandas Series ax : matplotlib Axes, default: None This is ...
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. 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. 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. Parameters ---------- y : an array of one dimension or a pandas Series kwargs : dict keyword arguments passed to scikit-learn API.
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. 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. """ 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: 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...
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: 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...
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. 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( ...
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. 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...
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. 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(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 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, 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: y = mi + (ma -mi)(\frac{x_i - min(x){max(x) - min(x)})^{power} If ``log=True``, the natural logarithm of the property va...
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. Parameters ---------- text : string The string to slugify Returns ------- slug : string A normalized slug representation of the text .. seeals...
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. 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...
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 c...
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...
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...
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...
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 w...
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 tec...
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. Parameters ---------- Returns ------- transformer : Pipeline Pipelined transformer for UMAP projections
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. Parameters ----------...
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...
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. Parameters ...
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: 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...
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. 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 ...
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 Returns ------- ax : the axis with the plotted figure
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 ...
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...
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. 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 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. 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 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. 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 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. 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 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. 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 ---------- 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: 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...
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: 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...
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 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 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. 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 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 y : ndarray or Series of length n An array or series of target values kwargs: keyword arguments passed to Scikit-Learn API. Returns ------- ...
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. 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...
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 ...
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. """ # Add the title to the plot self.set_title...
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...
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 b...
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. 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...
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. This helper function is a quick wrapper to utilize the DecisionBoundariesVisualizers for one-off analysis. Parameters ---------- model : the Scikit-Learn estimator, re...
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' base_color: The color of the background. This must be specified in RGBA with values between 0 and 1 (note, this is the default ...
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. Parameters ---------- ...
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...
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( ...