id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
602
import logging import pathlib import pickle import typing as t import numpy as np from deepchecks.vision.utils.test_utils import hash_image from deepchecks.vision.vision_data import VisionData def mnist_generator(shuffle: bool = False, batch_size: int = 64, train: bool = True, n_samples: int = None, ...
Return MNIST VisionData, containing prediction produced by a simple fully connected model. Model and data are taken from https://www.tensorflow.org/tutorials/quickstart/beginner. Parameters ---------- train : bool, default : True Train or Test dataset with_predictions : bool, default : True Whether the returned VisonDa...
603
from enum import Enum from collections import defaultdict from typing import Any, Dict, List from deepchecks.core.errors import DeepchecksValueError The provided code snippet includes necessary dependencies for implementing the `calc_vision_properties` function. Write a Python function `def calc_vision_properties(raw_...
Calculate the image properties for a batch of images. Parameters ---------- raw_data : torch.Tensor Batch of images to transform to image properties. properties_list: List[Dict] , default: None A list of properties to calculate. Returns ------ batch_properties: dict[str, List] A dict of property name, property value pe...
604
from enum import Enum from collections import defaultdict from typing import Any, Dict, List from deepchecks.core.errors import DeepchecksValueError class DeepchecksValueError(DeepchecksBaseError): """Exception class that represent a fault parameter was passed to Deepchecks.""" pass The provided code snippet...
Validate structure of measurements.
605
from typing import List from deepchecks.core.errors import ModelValidationError from deepchecks.vision.utils.vision_properties import PropertiesInputType from deepchecks.vision.vision_data import TaskType from deepchecks.vision.vision_data.batch_wrapper import BatchWrapper class ModelValidationError(DeepchecksBaseErro...
Transform the data to the relevant format and calculate the properties on it. Intended for the checks PropertyLabelCorrelation and PropertyLabelCorrelationChange.
606
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_samples_per_class_classification` function. Write a Python function `def _get_samples_per_class_classification(labels: Union[np.ndarray, List]) -> List[int]` to solve the fol...
Return a list containing the class per image in batch.
607
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_samples_per_class_object_detection` function. Write a Python function `def _get_samples_per_class_object_detection(labels: List[np.ndarray]) -> List[List[int]]` to solve the ...
Return a list containing the classes in batch.
608
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_bbox_area` function. Write a Python function `def _get_bbox_area(labels: List[np.ndarray]) -> List[List[int]]` to solve the following problem: Return a list containing the ar...
Return a list containing the area of bboxes in batch.
609
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_count_num_bboxes` function. Write a Python function `def _count_num_bboxes(labels: List[np.ndarray]) -> List[int]` to solve the following problem: Return a list containing the nu...
Return a list containing the number of bboxes in per sample batch.
610
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_samples_per_class_semantic_segmentation` function. Write a Python function `def _get_samples_per_class_semantic_segmentation(labels: List[np.ndarray]) -> List[List[int]]` to ...
Return a list containing the classes in batch.
611
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_segment_area` function. Write a Python function `def _get_segment_area(labels: List[np.ndarray]) -> List[List[int]]` to solve the following problem: Return a list containing ...
Return a list containing the area of segments in batch.
612
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_count_classes_by_segment_in_image` function. Write a Python function `def _count_classes_by_segment_in_image(labels: List[np.ndarray]) -> List[int]` to solve the following proble...
Return a list containing the number of unique classes per image for semantic segmentation.
613
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_predicted_classes_per_image_classification` function. Write a Python function `def _get_predicted_classes_per_image_classification(predictions: List[np.ndarray]) -> List[int]...
Return a list of the predicted class per image in the batch.
614
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_predicted_classes_per_image_object_detection` function. Write a Python function `def _get_predicted_classes_per_image_object_detection(predictions: List[np.ndarray]) -> List[...
Return a list containing the classes in batch.
615
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_predicted_bbox_area` function. Write a Python function `def _get_predicted_bbox_area(predictions: List[np.ndarray]) -> List[List[int]]` to solve the following problem: Return...
Return a list of the predicted bbox sizes per image in the batch.
616
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_predicted_classes_per_image_semantic_segmentation` function. Write a Python function `def _get_predicted_classes_per_image_semantic_segmentation(predictions: List[np.ndarray]...
Return a list containing the classes in batch.
617
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_get_segment_pred_area` function. Write a Python function `def _get_segment_pred_area(predictions: List[np.ndarray]) -> List[List[int]]` to solve the following problem: Return a l...
Return a list containing the area of segments in batch.
618
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `_count_pred_classes_by_segment_in_image` function. Write a Python function `def _count_pred_classes_by_segment_in_image(predictions: List[np.ndarray]) -> List[int]` to solve the f...
Return a list containing the number of unique classes per image for semantic segmentation.
619
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `get_column_type` function. Write a Python function `def get_column_type(output_type)` to solve the following problem: Get column type to use in drift functions. Here is the funct...
Get column type to use in drift functions.
620
from typing import List, Sequence, Union import numpy as np The provided code snippet includes necessary dependencies for implementing the `properties_flatten` function. Write a Python function `def properties_flatten(in_list: Sequence) -> List` to solve the following problem: Flatten a list of lists into a single lev...
Flatten a list of lists into a single level list.
621
import io import typing as t from numbers import Number from pathlib import Path import cv2 import numpy as np import PIL.Image as pilimage import PIL.ImageDraw as pildraw import PIL.ImageOps as pilops import plotly.graph_objects as go from PIL import ImageColor, ImageFont from deepchecks.core.errors import DeepchecksV...
Return an image to show as output of the display. Parameters ---------- image : np.ndarray The image to draw, must be a [H, W, C] 3D numpy array. label : 2-dim labels tensor for the image to draw on top of the image, shape depends on task type. task_type : TaskType The task type associated with the label. label_map: La...
622
import io import typing as t from numbers import Number from pathlib import Path import cv2 import numpy as np import PIL.Image as pilimage import PIL.ImageDraw as pildraw import PIL.ImageOps as pilops import plotly.graph_objects as go from PIL import ImageColor, ImageFont from deepchecks.core.errors import DeepchecksV...
Create heatmap graph object from given numpy array data.
623
import io import typing as t from numbers import Number from pathlib import Path import cv2 import numpy as np import PIL.Image as pilimage import PIL.ImageDraw as pildraw import PIL.ImageOps as pilops import plotly.graph_objects as go from PIL import ImageColor, ImageFont from deepchecks.core.errors import DeepchecksV...
For heatmap and grayscale images, need to add those properties which on Image exists automatically.
624
import io import typing as t from numbers import Number from pathlib import Path import cv2 import numpy as np import PIL.Image as pilimage import PIL.ImageDraw as pildraw import PIL.ImageOps as pilops import plotly.graph_objects as go from PIL import ImageColor, ImageFont from deepchecks.core.errors import DeepchecksV...
Return the cropped numpy array image by x, y, w, h coordinates (top left corner, width and height.
625
from collections import Counter from typing import Iterable, List, Sequence, Tuple, Union import numpy as np from PIL.Image import Image from deepchecks.vision.vision_data.utils import is_torch_object def verify_bbox_format_notation(notation: str) -> Tuple[bool, List[str]]: """Verify and tokenize bbox format notati...
Convert batch of bboxes to the required format. Parameters ---------- batch : iterable of tuple like object with two items - image, list of bboxes batch of images and bboxes corresponding to them notation : str bboxes format notation Returns ------- List[np.ndarray] list of transformed bboxes
626
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def _sizes(batch: List[np.ndarray]): """Return list of tuples of image height and width.""" return [get_size(img) for img in batch] The provided code snippet includes necessary dependenc...
Return list of floats of image height to width ratio.
627
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def get_size(img) -> Tuple[int, int]: """Get size of image as (height, width) tuple.""" return img.shape[0], img.shape[1] The provided code snippet includes necessary dependencies for im...
Return list of integers of image areas (height multiplied by width).
628
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def _is_grayscale(img): return get_dimension(img) == 1 The provided code snippet includes necessary dependencies for implementing the `brightness` function. Write a Python function `def brig...
Calculate brightness on each image in the batch.
629
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def _is_grayscale(img): return get_dimension(img) == 1 The provided code snippet includes necessary dependencies for implementing the `rms_contrast` function. Write a Python function `def rm...
Return RMS contrast of image.
630
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def _rgb_relative_intensity_mean(batch: List[np.ndarray]) -> List[Tuple[float, float, float]]: """Calculate normalized mean for each channel (rgb) in image. The normalized mean of each ch...
Return the mean of the red channel relative intensity.
631
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def _rgb_relative_intensity_mean(batch: List[np.ndarray]) -> List[Tuple[float, float, float]]: """Calculate normalized mean for each channel (rgb) in image. The normalized mean of each ch...
Return the mean of the green channel relative intensity.
632
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def _rgb_relative_intensity_mean(batch: List[np.ndarray]) -> List[Tuple[float, float, float]]: """Calculate normalized mean for each channel (rgb) in image. The normalized mean of each ch...
Return the mean of the blue channel relative intensity.
633
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def _is_grayscale(img): return get_dimension(img) == 1 The provided code snippet includes necessary dependencies for implementing the `texture_level` function. Write a Python function `def t...
Calculate the sharpness of each image in the batch.
634
from typing import Dict, List, Tuple import numpy as np from cv2 import CV_64F, Laplacian from skimage.color import rgb2gray def _sizes_array(batch: List[np.ndarray]): """Return an array of height and width per image (Nx2).""" return np.array(_sizes(batch)) def _rgb_relative_intensity_mean_array(batch: List[np....
Speed up the calculation for the default image properties by sharing common actions.
635
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Check if we're in an interactive context (Notebook, GUI support) or terminal-based. Returns ------- bool True if we are in a notebook context, False otherwise
636
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Check if we're in a sphinx gallery env. Returns ------- bool True if we are in a sphinx gallery context, False otherwise
637
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Check whether we are in a terminal interactive shell or not.
638
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Check if the system can support GUI. Returns ------- bool True if we cannot support GUI, False otherwise
639
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Check if we are in the google colab environment.
640
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Check if we are in the kaggle environment.
641
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Check if we are in the databricks environment.
642
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Check if we are in the AWS Sagemaker environment.
643
import logging import os import time import typing as t from functools import lru_cache import plotly.io as pio import tqdm from ipykernel.zmqshell import ZMQInteractiveShell from IPython import get_ipython from IPython.display import display from IPython.terminal.interactiveshell import TerminalInteractiveShell from t...
Create a progress bar instance.
644
import math from collections import Counter from typing import List, Union import numpy as np import pandas as pd from scipy.stats import entropy from deepchecks.utils.distribution.preprocessing import value_frequency def theil_u_correlation(x: Union[List, np.ndarray, pd.Series], y: Union[List, np.ndarray, pd.Series]) ...
Calculate the symmetric Theil's U correlation of y to x. Parameters ---------- x: Union[List, np.ndarray, pd.Series] A sequence of a categorical variable values without nulls y: Union[List, np.ndarray, pd.Series] A sequence of a categorical variable values without nulls Returns ------- float Representing the symmetric ...
645
import math from collections import Counter from typing import List, Union import numpy as np import pandas as pd from scipy.stats import entropy from deepchecks.utils.distribution.preprocessing import value_frequency The provided code snippet includes necessary dependencies for implementing the `correlation_ratio` fu...
Calculate the correlation ratio of numerical_variable to categorical_variable. Correlation ratio is a symmetric grouping based method that describe the level of correlation between a numeric variable and a categorical variable. returns a value in [0,1]. For more information see https://en.wikipedia.org/wiki/Correlation...
646
import contextlib import typing as t WANDB_INSTALLATION_CMD = 'pip install wandb' from typing import List The provided code snippet includes necessary dependencies for implementing the `wandb_run` function. Write a Python function `def wandb_run( project: t.Optional[str] = None, **kwargs ) -> t.Iterator[t.Any...
Create new one or use existing wandb run instance. Parameters ---------- project : Optional[str], default None project name **kwargs : additional parameters that will be passed to the 'wandb.init' Returns ------- Iterator[wandb.sdk.wandb_run.Run]
647
import copy import warnings from collections import Counter from typing import List, Tuple, Union import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin from sklearn.impute import SimpleImputer from sklearn.preprocessing import MinMaxScaler from deepchecks.core.errors import Dee...
Convert multi-label predictions to multi class format like predictions.
648
from numbers import Number from typing import Dict, Optional, Tuple, Union import numpy as np import pandas as pd from plotly.graph_objs import Figure from plotly.subplots import make_subplots from scipy.stats import chi2_contingency, wasserstein_distance from deepchecks.core import ConditionCategory, ConditionResult f...
Calculate drift score per column. Parameters ---------- train_column: pd.Series column from train dataset test_column: pd.Series same column from test dataset value_name: str title of the x axis, if plot_title is None then also the title of the whole plot. column_type: str type of column (either "numerical" or "categor...
649
from numbers import Number from typing import Dict, Optional, Tuple, Union import numpy as np import pandas as pd from plotly.graph_objs import Figure from plotly.subplots import make_subplots from scipy.stats import chi2_contingency, wasserstein_distance from deepchecks.core import ConditionCategory, ConditionResult f...
Create a condition function to be used in drift check's conditions. Parameters ---------- max_allowed_categorical_score: float Max value allowed for categorical drift max_allowed_numeric_score: float Max value allowed for numerical drift subject_single: str String that represents the subject being tested as single (fea...
650
The provided code snippet includes necessary dependencies for implementing the `sort_dict` function. Write a Python function `def sort_dict(x: dict, reverse=True)` to solve the following problem: Sort dictionary by values. Returns ------- Dict: sorted dictionary Here is the function: def sort_dict(x: dict, reverse=...
Sort dictionary by values. Returns ------- Dict: sorted dictionary
651
from typing import List import numpy as np import pandas as pd import plotly.graph_objects as go from sklearn.metrics import confusion_matrix from deepchecks import ConditionCategory, ConditionResult from deepchecks.core import CheckResult from deepchecks.core.errors import DeepchecksValueError from deepchecks.utils.st...
Calculate confusion matrix based on predictions and true label values.
652
from typing import List import numpy as np import pandas as pd import plotly.graph_objects as go from sklearn.metrics import confusion_matrix from deepchecks import ConditionCategory, ConditionResult from deepchecks.core import CheckResult from deepchecks.core.errors import DeepchecksValueError from deepchecks.utils.st...
Condition function that checks if the misclassified samples in the confusion matrix is below threshold. Parameters ---------- value: pd.DataFrame Dataframe containing the confusion matrix misclassified_samples_threshold: float Ratio of samples to be used for comparison in the condition (Value should be between 0 - 1 in...
653
import gc import torch.cuda The provided code snippet includes necessary dependencies for implementing the `empty_gpu` function. Write a Python function `def empty_gpu(device)` to solve the following problem: Empty GPU or MPS memory and run garbage collector. Here is the function: def empty_gpu(device): """Empty...
Empty GPU or MPS memory and run garbage collector.
654
import typing as t import jsonpickle from deepchecks.core.check_result import BaseCheckResult from deepchecks.core.suite import SuiteResult from typing import List class BaseCheckResult: """Generic class for any check output, contains some basic functions.""" check: Optional['BaseCheck'] header: Optional...
Convert a json object that was returned from one of our classes to_json. Parameters ---------- json_data: Union[str, Dict] Json data Returns ------- Union[BaseCheckResult, SuiteResult] A check output or a suite result object.
655
import typing as t T = t.TypeVar("T") from typing import List The provided code snippet includes necessary dependencies for implementing the `to_ordional_enumeration` function. Write a Python function `def to_ordional_enumeration(data: t.List[T]) -> t.Dict[T, int]` to solve the following problem: Enumarate each uniqu...
Enumarate each unique item.
656
from functools import lru_cache from inspect import Signature, signature from typing import Any, Callable, Dict def extract_signature(obj: Callable[..., Any]) -> Signature: """Extract signature object from a callable instance. Getting a callable signature is a heavy and not cheap op therefore we are caching...
Return object __dict__ variables that was passed throw constructor (__init__ method). Parameters ---------- obj : object include_defaults : bool, default False wherether to include vars with default value or not Returns ------- Dict[Any, Any] subset of the obj __dict__
657
from typing import Sequence, Tuple, Union import numpy as np from deepchecks.core.errors import DeepchecksValueError EPS = 0.001 class DeepchecksValueError(DeepchecksBaseError): """Exception class that represent a fault parameter was passed to Deepchecks.""" pass The provided code snippet includes necessary ...
Calculate outliers range on the data given using IQR. Parameters ---------- data: np.ndarray Data to calculate outliers range for. iqr_range: Tuple[int, int] Two percentiles which define the IQR range scale: float The scale to multiply the IQR range for the outliers' detection. When the percentiles values are the same ...
658
from typing import Sequence, Tuple, Union import numpy as np from deepchecks.core.errors import DeepchecksValueError EPS = 0.001 class DeepchecksValueError(DeepchecksBaseError): """Exception class that represent a fault parameter was passed to Deepchecks.""" pass The provided code snippet includes necessary ...
Calculate outliers range on the data given using sharp drop. Parameters ---------- data_percents : np.ndarray Counts of data to calculate outliers range for. The data is assumed to be sorted from the most common to the least common. sharp_drop_ratio : float , default 0.9 The sharp drop threshold to use for the outliers...
659
import numpy as np def create_proba_result(predictions, classes): def prediction_to_proba(y_pred): proba = np.zeros(len(classes)) proba[classes.index(y_pred)] = 1 return proba return np.apply_along_axis(prediction_to_proba, axis=1, arr=predictions.reshape(-1, 1))
null
660
import base64 from deepchecks.utils.logger import get_logger import sys from io import StringIO import pkg_resources The provided code snippet includes necessary dependencies for implementing the `imagetag` function. Write a Python function `def imagetag(img: bytes) -> str` to solve the following problem: Return html ...
Return html image tag with embedded image.
661
import base64 from deepchecks.utils.logger import get_logger import sys from io import StringIO import pkg_resources def get_logger() -> logging.Logger: """Retutn the deepchecks logger.""" return _logger The provided code snippet includes necessary dependencies for implementing the `display_in_gui` function. ...
Display suite result or check result in a new python gui window.
662
import textwrap import typing as t from functools import wraps from deepchecks.utils.logger import get_logger INDENT = ' ' from typing import List def indent( text: t.Optional[str], indents: int = 1, prefix: bool = False ) -> str: if not text or not isinstance(text, str): return '' iden...
null
663
import textwrap import typing as t from functools import wraps from deepchecks.utils.logger import get_logger F = t.TypeVar('F', bound=t.Callable[..., t.Any]) from typing import List def get_logger() -> logging.Logger: """Retutn the deepchecks logger.""" return _logger The provided code snippet includes nece...
Decorate a function with deprecated kwargs. Parameters ---------- old_arg_name : str Name of argument in function to deprecate new_arg_name : Optional[str], default None Name of preferred argument in function.
664
import textwrap import typing as t from functools import wraps from deepchecks.utils.logger import get_logger from typing import List def get_routine_name(it: t.Any) -> str: if hasattr(it, '__qualname__'): return it.__qualname__ elif callable(it) or isinstance(it, type): return it.__name__ ...
null
665
from typing import Hashable, List import numpy as np import pandas as pd from deepchecks.utils.array_math import fast_sum_by_row def calculate_distance(vec1: np.array, vec2: np.array, range_per_feature: np.array) -> float: """Calculate distance between two vectors using Gower's method. Parameters ----------...
Calculate distance matrix for a dataset using Gower's method. Gowers distance is a measurement for distance between two samples. It returns the average of their distances per feature. For numeric features it calculates the absolute distance divide by the range of the feature. For categorical features it is an indicator...
666
from typing import Hashable, List import numpy as np import pandas as pd from deepchecks.utils.array_math import fast_sum_by_row def _calculate_distances_to_sample(categorical_sample: np.ndarray, numeric_sample: np.ndarray, cat_data: np.ndarray, numeric_data: np.ndarray, numeric_featu...
Calculate distance matrix for a dataset using Gower's method. Gowers distance is a measurement for distance between two samples. It returns the average of their distances per feature. For numeric features it calculates the absolute distance divide by the range of the feature. For categorical features it is an indicator...
667
import typing as t import numpy as np import pandas as pd from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype, is_numeric_dtype from deepchecks.core.errors import DeepchecksValueError from deepchecks.utils.type_inference import infer_categorical_features from deepchecks.utils.typing import Hashable f...
Fill NaN values per column type.
668
import typing as t import numpy as np import pandas as pd from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype, is_numeric_dtype from deepchecks.core.errors import DeepchecksValueError from deepchecks.utils.type_inference import infer_categorical_features from deepchecks.utils.typing import Hashable f...
Return a series that if the type is int converted to float. Parameters ---------- ser : pd.Series series to convert Raises ------ pd.Series the converted series
669
import typing as t import numpy as np import pandas as pd from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype, is_numeric_dtype from deepchecks.core.errors import DeepchecksValueError from deepchecks.utils.type_inference import infer_categorical_features from deepchecks.utils.typing import Hashable f...
Compute pairwise correlation. Pairwise correlation is computed between columns of one DataFrame with columns of another DataFrame. Pandas' method corrwith only applies when both dataframes have the same column names, this generalized method applies to any two Dataframes with the same number of rows, regardless of the c...
670
import typing as t import numpy as np import pandas as pd from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype, is_numeric_dtype from deepchecks.core.errors import DeepchecksValueError from deepchecks.utils.type_inference import infer_categorical_features from deepchecks.utils.typing import Hashable f...
Check if a column must be a float - meaning does it contain fractions. Parameters ---------- col : pd.Series The column to check. Returns ------- bool True if the column is float, False otherwise.
671
import typing as t import numpy as np import pandas as pd from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype, is_numeric_dtype from deepchecks.core.errors import DeepchecksValueError from deepchecks.utils.type_inference import infer_categorical_features from deepchecks.utils.typing import Hashable f...
Cast categorical columns to the object dtype.
672
from typing import Union from sklearn.pipeline import Pipeline from deepchecks.utils.typing import BasicModel class BasicModel(Protocol): """Traits of a model that are necessary for deepchecks.""" def predict(self, X) -> List[Hashable]: """Predict on given X.""" ... The provided code snippet ...
Return the model of a given Pipeline or itself if a BaseEstimator is given. Parameters ---------- model : Union[Pipeline, BasicModel] a Pipeline or a BasicModel Returns ------- Union[Pipeline, BasicModel] the inner BaseEstimator of the Pipeline or itself
673
import io import itertools import json import os import random import re import sys import typing as t from collections import defaultdict from copy import copy from datetime import datetime from decimal import Decimal from string import ascii_uppercase, digits import numpy as np import pandas as pd from ipywidgets imp...
Return the docs summary if available. Parameters ---------- obj an object with_doc_link : bool , default: True if to add doc link Returns ------- str the object summary.
674
import io import itertools import json import os import random import re import sys import typing as t from collections import defaultdict from copy import copy from datetime import datetime from decimal import Decimal from string import ascii_uppercase, digits import numpy as np import pandas as pd from ipywidgets imp...
Transform widget into html string. Parameters ---------- widget: Widget The widget to save as html. title: str The title of the html file. requirejs: bool , default: True If to save with all javascript dependencies connected : bool, default True whether to use CDN or not full_html: bool, default True whether to return ...
675
import io import itertools import json import os import random import re import sys import typing as t from collections import defaultdict from copy import copy from datetime import datetime from decimal import Decimal from string import ascii_uppercase, digits import numpy as np import pandas as pd from ipywidgets imp...
Determine whether a pandas series is string type.
676
import io import itertools import json import os import random import re import sys import typing as t from collections import defaultdict from copy import copy from datetime import datetime from decimal import Decimal from string import ascii_uppercase, digits import numpy as np import pandas as pd from ipywidgets imp...
Transform camel case indentifier into snake case. Parameters ---------- value : str string to transform Returns ------- str transformed value
677
import io import itertools import json import os import random import re import sys import typing as t from collections import defaultdict from copy import copy from datetime import datetime from decimal import Decimal from string import ascii_uppercase, digits import numpy as np import pandas as pd from ipywidgets imp...
Create dict of base-form of the uniques to their values. function gets a set of strings, and returns a dictionary of shape Dict[str, Set] the key being the "base_form" (a clean version of the string), and the value being a set of all existing original values. This is done using the StringCategory class.
678
import io import itertools import json import os import random import re import sys import typing as t from collections import defaultdict from copy import copy from datetime import datetime from decimal import Decimal from string import ascii_uppercase, digits import numpy as np import pandas as pd from ipywidgets imp...
Split string by another substring into a list. Like str.split(), but keeps the separator occurrences in the list. Parameters ---------- s : str the string to split separators : t.Union[str, t.Iterable[str]] the substring to split by Returns ------- t.List[str] list of substrings, including the separator occurrences in ...
679
import io import itertools import json import os import random import re import sys import typing as t from collections import defaultdict from copy import copy from datetime import datetime from decimal import Decimal from string import ascii_uppercase, digits import numpy as np import pandas as pd from ipywidgets imp...
Split string by a list of substrings, each used once as a separator. Parameters ---------- s : str the string to split separators : t.Iterable[str] list of substrings to split by keep : bool , default: True whether to keep the separators in list as well. Default is True. Returns ------- t.List[str] list of substrings
680
import io import itertools import json import os import random import re import sys import typing as t from collections import defaultdict from copy import copy from datetime import datetime from decimal import Decimal from string import ascii_uppercase, digits import numpy as np import pandas as pd from ipywidgets imp...
Format datetime object or timestamp value. Parameters ---------- value : Union[datetime, int, float] datetime (timestamp) to format Returns ------- str string representation of the provided value Raises ------ ValueError if unexpected value type was passed to the function
681
import typing as t from deepchecks import __version__ links = { 'default': { 'supported-metrics-by-string': 'https://docs.deepchecks.com/stable/general/guides/metrics_guide.html#list-of-supported-strings', # pylint: disable=line-too-long # noqa 'supported-prediction-format': 'https://docs.deepcheck...
Get documentation link. Parameters ---------- name: str the name of the required link as appears in the links' dictionary. default_link: t.Optional[str], default: None default like to use if no link corresponding to name was found. template: t.Optional[str], default: None a string template in which to incorporate the l...
682
from typing import List, Optional import numpy as np import pandas as pd from deepchecks.core.errors import DeepchecksValueError The provided code snippet includes necessary dependencies for implementing the `calculate_neg_mse_per_sample` function. Write a Python function `def calculate_neg_mse_per_sample(labels, pred...
Calculate negative mean squared error per sample.
683
from typing import List, Optional import numpy as np import pandas as pd from deepchecks.core.errors import DeepchecksValueError class DeepchecksValueError(DeepchecksBaseError): """Exception class that represent a fault parameter was passed to Deepchecks.""" pass The provided code snippet includes necessary ...
Calculate negative cross entropy per sample.
684
import matplotlib.pyplot as plt import numpy as np from matplotlib.cm import ScalarMappable from matplotlib.colors import LinearSegmentedColormap def shifted_color_map(cmap, start=0, midpoint=0.5, stop=1.0, name: str = 'shiftedcmap', transparent_from: float = None): """Offset the "center" of a colormap. Parame...
Output a colorbar barchart using matplotlib. Parameters ---------- x: np.ndarray array containing x axis data. y: np.ndarray array containing y axis data. ylabel: str , default: Result Name of y axis xlabel : str , default: Features Name of x axis color_map : str , default: RdYlGn_r color_map name. See https://matplotl...
685
import matplotlib.pyplot as plt import numpy as np from matplotlib.cm import ScalarMappable from matplotlib.colors import LinearSegmentedColormap The provided code snippet includes necessary dependencies for implementing the `hex_to_rgba` function. Write a Python function `def hex_to_rgba(h, alpha)` to solve the follo...
Convert color value in hex format to rgba format with alpha transparency.
686
import numpy as np The provided code snippet includes necessary dependencies for implementing the `round_sig` function. Write a Python function `def round_sig(x: float, sig: int = 2)` to solve the following problem: Round a number to a given number of significant digits. Here is the function: def round_sig(x: float,...
Round a number to a given number of significant digits.
687
from collections import defaultdict from copy import deepcopy from typing import Callable, List, Optional, Tuple, Union import numpy as np import pandas as pd from sklearn.tree import _tree from deepchecks.tabular.dataset import Dataset from deepchecks.utils.strings import format_number from deepchecks.utils.typing imp...
Merge two DeepChecksFilters into one, an intersection of both filters.
688
from collections import defaultdict from copy import deepcopy from typing import Callable, List, Optional, Tuple, Union import numpy as np import pandas as pd from sklearn.tree import _tree from deepchecks.tabular.dataset import Dataset from deepchecks.utils.strings import format_number from deepchecks.utils.typing imp...
Split given series into segments containing specified segment. Tries to create segments as balanced as possible in size. Parameters ---------- column : pd.Series Series to be partitioned. segment : List[float] Segment to be included in the partition. max_additional_segments : int, default = 4 Maximum number of segments...
689
from collections import defaultdict from copy import deepcopy from typing import Callable, List, Optional, Tuple, Union import numpy as np import pandas as pd from sklearn.tree import _tree from deepchecks.tabular.dataset import Dataset from deepchecks.utils.strings import format_number from deepchecks.utils.typing imp...
Split column into segments. For categorical we'll have a max of max_segments + 1, for the 'Others'. We take the largest categories which cumulative percent in data is equal/larger than `max_cat_proportions`. the rest will go to 'Others' even if less than max_segments. For numerical we split into maximum number of `max_...
690
from collections import defaultdict from copy import deepcopy from typing import Callable, List, Optional, Tuple, Union import numpy as np import pandas as pd from sklearn.tree import _tree from deepchecks.tabular.dataset import Dataset from deepchecks.utils.strings import format_number from deepchecks.utils.typing imp...
Extract the leaves from a sklearn tree and covert them into DeepchecksBaseFilter. The function goes over the tree from root to leaf and concatenates (by intersecting) the relevant filters along the way. The function returns a list in which each element is a DeepchecksFilter representing the path between the root to a d...
691
from typing import Any, Callable, Dict, Hashable, List, Optional, Tuple import numpy as np import pandas as pd import plotly.express as px from category_encoders import TargetEncoder from sklearn.compose import ColumnTransformer from sklearn.ensemble import RandomForestRegressor from sklearn.impute import SimpleImputer...
Calculate features contributing to model error.
692
from typing import Any, Callable, Dict, Hashable, List, Optional, Tuple import numpy as np import pandas as pd import plotly.express as px from category_encoders import TargetEncoder from sklearn.compose import ColumnTransformer from sklearn.ensemble import RandomForestRegressor from sklearn.impute import SimpleImputer...
Wrap dataframe with tabular.Dataset for error_model_display with no scorer.
693
import logging import warnings _logger = logging.getLogger('deepchecks') _logger.addHandler(_stream_handler) _logger.setLevel(logging.INFO) The provided code snippet includes necessary dependencies for implementing the `set_verbosity` function. Write a Python function `def set_verbosity(level: int)` to solve the foll...
Set the deepchecks logger verbosity level. Same as doing logging.getLogger('deepchecks').setLevel(level). Control the package wide log level and the progrees bars - progress bars are level INFO. Examples -------- >>> import logging >>> import deepchecks >>> # will disable progress bars >>> deepchecks.set_verbosity(logg...
694
import random from dataclasses import dataclass, field from functools import partial from pathlib import Path import jax import jax.numpy as jnp import numpy as np from braceexpand import braceexpand from datasets import Dataset, load_dataset from .model.text import TextNormalizer def blank_caption_function(example, t...
null
695
import random from dataclasses import dataclass, field from functools import partial from pathlib import Path import jax import jax.numpy as jnp import numpy as np from braceexpand import braceexpand from datasets import Dataset, load_dataset from .model.text import TextNormalizer def normalize_function(example, text_...
null
696
import random from dataclasses import dataclass, field from functools import partial from pathlib import Path import jax import jax.numpy as jnp import numpy as np from braceexpand import braceexpand from datasets import Dataset, load_dataset from .model.text import TextNormalizer def filter_function( example, ...
null
697
import random from dataclasses import dataclass, field from functools import partial from pathlib import Path import jax import jax.numpy as jnp import numpy as np from braceexpand import braceexpand from datasets import Dataset, load_dataset from .model.text import TextNormalizer def shift_tokens_right(input_ids: np.a...
null
698
import html import math import random import re from pathlib import Path import emoji import ftfy from huggingface_hub import hf_hub_download from unidecode import unidecode person_token = [("a person", 282265), ("someone", 121194), ("somebody", 12219)] The provided code snippet includes necessary dependencies for imp...
Used for CC12M
699
import html import math import random import re from pathlib import Path import emoji import ftfy from huggingface_hub import hf_hub_download from unidecode import unidecode def fix_html(t): # from OpenAI CLIP return html.unescape(html.unescape(t))
null
700
import html import math import random import re from pathlib import Path import emoji import ftfy from huggingface_hub import hf_hub_download from unidecode import unidecode def replace_punctuation_with_commas(t): return re.sub("[()[\].,|:;?!=+~\-\/{}]", ",", t)
null
701
import html import math import random import re from pathlib import Path import emoji import ftfy from huggingface_hub import hf_hub_download from unidecode import unidecode def simplify_quotes(t): return re.sub("""['"`]""", ' " ', t)
null