code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def adversarial_group_calibration( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, cali_type: str, prop_type: str = "interval", num_bins: int = 100, num_group_bins: int = 10, draw_with_replacement: bool = False, num_trials: int = 10, num_group_draws: int = 10, verb...
Adversarial group calibration. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the held out dataset. y_true: 1D array of the true labels in the held out dataset. cali_type: type of calibration error to ...
adversarial_group_calibration
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_calibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py
MIT
def miscalibration_area_from_proportions( exp_proportions: np.ndarray, obs_proportions: np.ndarray ) -> float: """Miscalibration area from expected and observed proportions lists. This function returns the same output as `miscalibration_area` directly from a list of expected proportions (the proportion...
Miscalibration area from expected and observed proportions lists. This function returns the same output as `miscalibration_area` directly from a list of expected proportions (the proportion of data that you expect to observe within prediction intervals) and a list of observed proportions (the proportion da...
miscalibration_area_from_proportions
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_calibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py
MIT
def get_proportion_lists_vectorized( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, num_bins: int = 100, recal_model: Any = None, prop_type: str = "interval", ) -> Tuple[np.ndarray, np.ndarray]: """Arrays of expected and observed proportions Returns the expected proportions ...
Arrays of expected and observed proportions Returns the expected proportions and observed proportion of points falling into intervals corresponding to a range of quantiles. Computations here are vectorized for faster execution, but this function is not suited when there are memory constraints. Arg...
get_proportion_lists_vectorized
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_calibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py
MIT
def get_proportion_lists( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, num_bins: int = 100, recal_model: IsotonicRegression = None, prop_type: str = "interval", ) -> Tuple[np.ndarray, np.ndarray]: """Arrays of expected and observed proportions Return arrays of expected and...
Arrays of expected and observed proportions Return arrays of expected and observed proportions of points falling into intervals corresponding to a range of quantiles. Computations here are not vectorized, in case there are memory constraints. Args: y_pred: 1D array of the predicted means for t...
get_proportion_lists
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_calibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py
MIT
def get_proportion_in_interval( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, quantile: float ) -> float: """For a specified quantile, return the proportion of points falling into an interval corresponding to that quantile. Args: y_pred: 1D array of the predicted means for the held...
For a specified quantile, return the proportion of points falling into an interval corresponding to that quantile. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the held out dataset. y_true: 1D array of t...
get_proportion_in_interval
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_calibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py
MIT
def get_proportion_under_quantile( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, quantile: float, ) -> float: """Get the proportion of data that are below the predicted quantile. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array...
Get the proportion of data that are below the predicted quantile. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the held out dataset. y_true: 1D array of the true labels in the held out dataset. quant...
get_proportion_under_quantile
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_calibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py
MIT
def get_prediction_interval( y_pred: np.ndarray, y_std: np.ndarray, quantile: np.ndarray, recal_model: Optional[IsotonicRegression] = None, ) -> Namespace: """Return the centered predictional interval corresponding to a quantile. For a specified quantile level q (must be a float, or a singleton...
Return the centered predictional interval corresponding to a quantile. For a specified quantile level q (must be a float, or a singleton), return the centered prediction interval corresponding to the pair of quantiles at levels (0.5-q/2) and (0.5+q/2), i.e. interval that has nominal coverage equal to q...
get_prediction_interval
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_calibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py
MIT
def get_quantile( y_pred: np.ndarray, y_std: np.ndarray, quantile: np.ndarray, recal_model: Optional[IsotonicRegression] = None, ) -> float: """Return the value corresponding with a quantile. For a specified quantile level q (must be a float, or a singleton), return the quantile prediction,...
Return the value corresponding with a quantile. For a specified quantile level q (must be a float, or a singleton), return the quantile prediction, i.e. bound that has nominal coverage below the bound equal to q. Args: y_pred: 1D array of the predicted means for the held out dataset. y...
get_quantile
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_calibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_calibration.py
MIT
def nll_gaussian( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, scaled: bool = True, ) -> float: """Negative log likelihood for a gaussian. The negative log likelihood for held out data (y_true) given predictive uncertainty with mean (y_pred) and standard-deviation (y_std). ...
Negative log likelihood for a gaussian. The negative log likelihood for held out data (y_true) given predictive uncertainty with mean (y_pred) and standard-deviation (y_std). Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard d...
nll_gaussian
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_scoring_rule.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_scoring_rule.py
MIT
def crps_gaussian( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, scaled: bool = True, ) -> float: """The negatively oriented continuous ranked probability score for Gaussians. Computes CRPS for held out data (y_true) given predictive uncertainty with mean (y_pred) and standard-...
The negatively oriented continuous ranked probability score for Gaussians. Computes CRPS for held out data (y_true) given predictive uncertainty with mean (y_pred) and standard-deviation (y_std). Each test point is given equal weight in the overall score over the test set. Negatively oriented means a ...
crps_gaussian
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_scoring_rule.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_scoring_rule.py
MIT
def check_score( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, scaled: bool = True, start_q: float = 0.01, end_q: float = 0.99, resolution: int = 99, ) -> float: """The negatively oriented check score. Computes the negatively oriented check score for held out data (y_tr...
The negatively oriented check score. Computes the negatively oriented check score for held out data (y_true) given predictive uncertainty with mean (y_pred) and standard-deviation (y_std). Each test point and each quantile is given equal weight in the overall score over the test set and list of quantil...
check_score
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_scoring_rule.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_scoring_rule.py
MIT
def interval_score( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, scaled: bool = True, start_p: float = 0.01, end_p: float = 0.99, resolution: int = 99, ) -> float: """The negatively oriented interval score. Compute the negatively oriented interval score for held out da...
The negatively oriented interval score. Compute the negatively oriented interval score for held out data (y_true) given predictive uncertainty with mean (y_pred) and standard-deviation (y_std). Each test point and each percentile is given equal weight in the overall score over the test set and list of ...
interval_score
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/metrics_scoring_rule.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/metrics_scoring_rule.py
MIT
def get_q_idx(exp_props: np.ndarray, q: float) -> int: """Utility function which outputs the array index of an element. Gets the (approximate) index of a specified probability value, q, in the expected proportions array. Used as a utility function in isotonic regression recalibration. Args: ex...
Utility function which outputs the array index of an element. Gets the (approximate) index of a specified probability value, q, in the expected proportions array. Used as a utility function in isotonic regression recalibration. Args: exp_props: 1D array of expected probabilities. q: a spec...
get_q_idx
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/recalibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/recalibration.py
MIT
def iso_recal( exp_props: np.ndarray, obs_props: np.ndarray, ) -> IsotonicRegression: """Recalibration algorithm based on isotonic regression. Fits and outputs an isotonic recalibration model that maps observed probabilities to expected probabilities. This mapping provides the necessary adjustm...
Recalibration algorithm based on isotonic regression. Fits and outputs an isotonic recalibration model that maps observed probabilities to expected probabilities. This mapping provides the necessary adjustments to produce better calibrated outputs. Args: exp_props: 1D array of expected probabi...
iso_recal
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/recalibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/recalibration.py
MIT
def optimize_recalibration_ratio( y_mean: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, criterion: str = "ma_cal", optimizer_bounds: Tuple[float, float] = (1e-2, 1e2), ) -> float: """Scale factor which uniformly recalibrates predicted standard deviations. Searches via black-box optimiz...
Scale factor which uniformly recalibrates predicted standard deviations. Searches via black-box optimization the standard deviation scale factor (opt_ratio) which produces the best recalibration, i.e. updated standard deviation can be written as opt_ratio * y_std. Args: y_mean: 1D array of the...
optimize_recalibration_ratio
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/recalibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/recalibration.py
MIT
def get_std_recalibrator( y_mean: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, criterion: str = "ma_cal", optimizer_bounds: Tuple[float, float] = (1e-2, 1e2), ) -> Callable[[np.ndarray], np.ndarray]: """Standard deviation recalibrator. Computes the standard deviation recalibration rat...
Standard deviation recalibrator. Computes the standard deviation recalibration ratio and returns a function which takes in an array of uncalibrated standard deviations and returns an array of recalibrated standard deviations. Args: y_mean: 1D array of the predicted means for the recalibration ...
get_std_recalibrator
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/recalibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/recalibration.py
MIT
def get_quantile_recalibrator( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, ) -> Callable[[np.ndarray, np.ndarray, Union[float, np.ndarray]], np.ndarray]: """Quantile recalibrator. Fits an isotonic regression recalibration model and returns a function which takes in the mean and s...
Quantile recalibrator. Fits an isotonic regression recalibration model and returns a function which takes in the mean and standard deviation predictions and a specified quantile level, and returns the recalibrated quantile. Args: y_pred: 1D array of the predicted means for the recalibration da...
get_quantile_recalibrator
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/recalibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/recalibration.py
MIT
def get_interval_recalibrator( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, ) -> Callable[[np.ndarray, np.ndarray, Union[float, np.ndarray]], np.ndarray]: """Prediction interval recalibrator. Fits an isotonic regression recalibration model and returns a function which takes in the...
Prediction interval recalibrator. Fits an isotonic regression recalibration model and returns a function which takes in the mean and standard deviation predictions and a specified centered interval coverage level, and returns the recalibrated interval. Args: y_pred: 1D array of the predicted m...
get_interval_recalibrator
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/recalibration.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/recalibration.py
MIT
def assert_is_flat_same_shape(*args: Any) -> Union[bool, NoReturn]: """Check if inputs are all same-length 1d numpy.ndarray. Args: args: the numpy arrays to check. Returns: True if all arrays are flat and the same shape, or else raises assertion error. """ assert len(args) > 0 ...
Check if inputs are all same-length 1d numpy.ndarray. Args: args: the numpy arrays to check. Returns: True if all arrays are flat and the same shape, or else raises assertion error.
assert_is_flat_same_shape
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/utils.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/utils.py
MIT
def assert_is_positive(*args: Any) -> Union[bool, NoReturn]: """Assert that all numpy arrays are positive. Args: args: the numpy arrays to check. Returns: True if all elements in all arrays are positive values, or else raises assertion error. """ assert len(args) > 0 for arr in...
Assert that all numpy arrays are positive. Args: args: the numpy arrays to check. Returns: True if all elements in all arrays are positive values, or else raises assertion error.
assert_is_positive
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/utils.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/utils.py
MIT
def trapezoid_area( xl: np.ndarray, al: np.ndarray, bl: np.ndarray, xr: np.ndarray, ar: np.ndarray, br: np.ndarray, absolute: bool = True, ) -> Numeric: """ Calculate the area of a vertical-sided trapezoid, formed connecting the following points: (xl, al) - (xl, bl) - (xr, br...
Calculate the area of a vertical-sided trapezoid, formed connecting the following points: (xl, al) - (xl, bl) - (xr, br) - (xr, ar) - (xl, al) This function considers the case that the edges of the trapezoid might cross, and explicitly accounts for this. Args: xl: The x coordinate of ...
trapezoid_area
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/utils.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/utils.py
MIT
def intersection( p1: Tuple[Numeric, Numeric], p2: Tuple[Numeric, Numeric], p3: Tuple[Numeric, Numeric], p4: Tuple[Numeric, Numeric], ) -> Tuple[Numeric, Numeric]: """ Calculate the intersection of two lines between four points, as defined in https://en.wikipedia.org/wiki/Line%E2%80%93line_i...
Calculate the intersection of two lines between four points, as defined in https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection. This is an array option and works can be used to calculate the intersections of entire arrays of points at the same time. Args: p1: The point (x1, y1), ...
intersection
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/utils.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/utils.py
MIT
def plot_xy( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, x: np.ndarray, n_subset: Union[int, None] = None, ylims: Union[Tuple[float, float], None] = None, xlims: Union[Tuple[float, float], None] = None, num_stds_confidence_bound: int = 2, leg_loc: Union[int, str] = 3, ...
Plot one-dimensional inputs with associated predicted values, predictive uncertainties, and true values. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the held out dataset. y_true: 1D array of the true la...
plot_xy
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def plot_intervals( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, n_subset: Union[int, None] = None, ylims: Union[Tuple[float, float], None] = None, num_stds_confidence_bound: int = 2, ax: Union[matplotlib.axes.Axes, None] = None, ) -> matplotlib.axes.Axes: """Plot predictio...
Plot predictions and predictive intervals versus true values. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the held out dataset. y_true: 1D array of the true labels in the held out dataset. n_subset:...
plot_intervals
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def plot_intervals_ordered( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, n_subset: Union[int, None] = None, ylims: Union[Tuple[float, float], None] = None, num_stds_confidence_bound: int = 2, ax: Union[matplotlib.axes.Axes, None] = None, ) -> matplotlib.axes.Axes: """Plot p...
Plot predictions and predictive intervals versus true values, with points ordered by true value along x-axis. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the held out dataset. y_true: 1D array of the tr...
plot_intervals_ordered
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def plot_calibration( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, n_subset: Union[int, None] = None, curve_label: Union[str, None] = None, vectorized: bool = True, exp_props: Union[np.ndarray, None] = None, obs_props: Union[np.ndarray, None] = None, ax: Union[matplotli...
Plot the observed proportion vs prediction proportion of outputs falling into a range of intervals, and display miscalibration area. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the held out dataset. y_t...
plot_calibration
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def plot_adversarial_group_calibration( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, n_subset: Union[int, None] = None, cali_type: str = "mean_abs", curve_label: Union[str, None] = None, group_size: Union[np.ndarray, None] = None, score_mean: Union[np.ndarray, None] = None,...
Plot adversarial group calibration plots by varying group size from 0% to 100% of dataset size and recording the worst calibration occurred for each group size. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the h...
plot_adversarial_group_calibration
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def plot_sharpness( y_std: np.ndarray, n_subset: Union[int, None] = None, ax: Union[matplotlib.axes.Axes, None] = None, ) -> matplotlib.axes.Axes: """Plot sharpness of the predictive uncertainties. Args: y_std: 1D array of the predicted standard deviations for the held out dataset. ...
Plot sharpness of the predictive uncertainties. Args: y_std: 1D array of the predicted standard deviations for the held out dataset. n_subset: Number of points to plot after filtering. ax: matplotlib.axes.Axes object. Returns: matplotlib.axes.Axes object with plot added.
plot_sharpness
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def plot_residuals_vs_stds( y_pred: np.ndarray, y_std: np.ndarray, y_true: np.ndarray, n_subset: Union[int, None] = None, ax: Union[matplotlib.axes.Axes, None] = None, ) -> matplotlib.axes.Axes: """Plot absolute value of the prediction residuals versus standard deviations of the predictive u...
Plot absolute value of the prediction residuals versus standard deviations of the predictive uncertainties. Args: y_pred: 1D array of the predicted means for the held out dataset. y_std: 1D array of the predicted standard deviations for the held out dataset. y_true: 1D array of the true...
plot_residuals_vs_stds
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def filter_subset(input_list: List[List[Any]], n_subset: int) -> List[List[Any]]: """Keep only n_subset random indices from all lists given in input_list. Args: input_list: list of lists. n_subset: Number of points to plot after filtering. Returns: List of all input lists with size...
Keep only n_subset random indices from all lists given in input_list. Args: input_list: list of lists. n_subset: Number of points to plot after filtering. Returns: List of all input lists with sizes reduced to n_subset.
filter_subset
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def set_style(style_str: str = "default") -> NoReturn: """Set the matplotlib plotting style. Args: style_str: string for style file. """ if style_str == "default": plt.style.use((pathlib.Path(__file__).parent / "matplotlibrc").resolve())
Set the matplotlib plotting style. Args: style_str: string for style file.
set_style
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def save_figure( file_name: str = "figure", ext_list: Union[list, str, None] = None, white_background: bool = True, ) -> NoReturn: """Save matplotlib figure for all extensions in ext_list. Args: file_name: name of saved image file. ext_list: list of strings (or single string) denoti...
Save matplotlib figure for all extensions in ext_list. Args: file_name: name of saved image file. ext_list: list of strings (or single string) denoting file type. white_background: set background of image to white if True.
save_figure
python
uncertainty-toolbox/uncertainty-toolbox
uncertainty_toolbox/viz.py
https://github.com/uncertainty-toolbox/uncertainty-toolbox/blob/master/uncertainty_toolbox/viz.py
MIT
def setup(self) -> None: """Load the model into memory to make running multiple predictions efficient""" self.enhancer = FaceEnhancement( base_dir="checkpoints", size=512, model="GPEN-BFR-512", use_sr=False, sr_model="rrdb_realesrnet_psnr", ...
Load the model into memory to make running multiple predictions efficient
setup
python
OpenTalker/video-retalking
predict.py
https://github.com/OpenTalker/video-retalking/blob/master/predict.py
Apache-2.0
def predict( self, face: Path = Input(description="Input video file of a talking-head."), input_audio: Path = Input(description="Input audio file."), ) -> Path: """Run a single prediction on the model""" device = "cuda" args = argparse.Namespace( DNet_path...
Run a single prediction on the model
predict
python
OpenTalker/video-retalking
predict.py
https://github.com/OpenTalker/video-retalking/blob/master/predict.py
Apache-2.0
def image_transform(self, images, lm): """ param: images: -- PIL image lm: -- numpy array """ W,H = images.size if np.mean(lm) == -1: lm = (self.lm3d_std[:, :2]+1)/2. lm = np.concatenate( [lm[:...
param: images: -- PIL image lm: -- numpy array
image_transform
python
OpenTalker/video-retalking
third_part/face3d/coeff_detector.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/coeff_detector.py
Apache-2.0
def __init__(self, opt): """Initialize the class; save the options in the class Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions """ self.opt = opt # self.root = opt.dataroot self.current_epoch = 0
Initialize the class; save the options in the class Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
__init__
python
OpenTalker/video-retalking
third_part/face3d/data/base_dataset.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/base_dataset.py
Apache-2.0
def default_flist_reader(flist): """ flist format: impath label\nimpath label\n ...(same to caffe's filelist) """ imlist = [] with open(flist, 'r') as rf: for line in rf.readlines(): impath = line.strip() imlist.append(impath) return imlist
flist format: impath label impath label ...(same to caffe's filelist)
default_flist_reader
python
OpenTalker/video-retalking
third_part/face3d/data/flist_dataset.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/flist_dataset.py
Apache-2.0
def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ BaseDataset.__init__(self, opt) self.lm3d_std = load_lm3d(opt.bfm_folder) ...
Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
__init__
python
OpenTalker/video-retalking
third_part/face3d/data/flist_dataset.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/flist_dataset.py
Apache-2.0
def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index (int) -- a random integer for data indexing Returns a dictionary that contains A, B, A_paths and B_paths img (tensor) -- an image in the input domain ...
Return a data point and its metadata information. Parameters: index (int) -- a random integer for data indexing Returns a dictionary that contains A, B, A_paths and B_paths img (tensor) -- an image in the input domain msk (tensor) -- its correspondi...
__getitem__
python
OpenTalker/video-retalking
third_part/face3d/data/flist_dataset.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/flist_dataset.py
Apache-2.0
def modify_commandline_options(parser, is_train): """Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add tra...
Add new dataset-specific options, and rewrite default values for existing options. Parameters: parser -- original option parser is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: ...
modify_commandline_options
python
OpenTalker/video-retalking
third_part/face3d/data/template_dataset.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/template_dataset.py
Apache-2.0
def __init__(self, opt): """Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions A few things can be done here. - save the options (have been done in BaseDataset) - get image paths an...
Initialize this dataset class. Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions A few things can be done here. - save the options (have been done in BaseDataset) - get image paths and meta information of the dataset. ...
__init__
python
OpenTalker/video-retalking
third_part/face3d/data/template_dataset.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/template_dataset.py
Apache-2.0
def __getitem__(self, index): """Return a data point and its metadata information. Parameters: index -- a random integer for data indexing Returns: a dictionary of data with their names. It usually contains the data itself and its metadata information. Step 1: ...
Return a data point and its metadata information. Parameters: index -- a random integer for data indexing Returns: a dictionary of data with their names. It usually contains the data itself and its metadata information. Step 1: get a random image path: e.g., path = sel...
__getitem__
python
OpenTalker/video-retalking
third_part/face3d/data/template_dataset.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/template_dataset.py
Apache-2.0
def find_dataset_using_name(dataset_name): """Import the module "data/[dataset_name]_dataset.py". In the file, the class called DatasetNameDataset() will be instantiated. It has to be a subclass of BaseDataset, and it is case-insensitive. """ dataset_filename = "data." + dataset_name + "_datase...
Import the module "data/[dataset_name]_dataset.py". In the file, the class called DatasetNameDataset() will be instantiated. It has to be a subclass of BaseDataset, and it is case-insensitive.
find_dataset_using_name
python
OpenTalker/video-retalking
third_part/face3d/data/__init__.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/__init__.py
Apache-2.0
def create_dataset(opt, rank=0): """Create a dataset given the option. This function wraps the class CustomDatasetDataLoader. This is the main interface between this package and 'train.py'/'test.py' Example: >>> from data import create_dataset >>> dataset = create_dataset(opt) ...
Create a dataset given the option. This function wraps the class CustomDatasetDataLoader. This is the main interface between this package and 'train.py'/'test.py' Example: >>> from data import create_dataset >>> dataset = create_dataset(opt)
create_dataset
python
OpenTalker/video-retalking
third_part/face3d/data/__init__.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/__init__.py
Apache-2.0
def __init__(self, opt, rank=0): """Initialize this class Step 1: create a dataset instance given the name [dataset_mode] Step 2: create a multi-threaded data loader. """ self.opt = opt dataset_class = find_dataset_using_name(opt.dataset_mode) self.dataset = data...
Initialize this class Step 1: create a dataset instance given the name [dataset_mode] Step 2: create a multi-threaded data loader.
__init__
python
OpenTalker/video-retalking
third_part/face3d/data/__init__.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/data/__init__.py
Apache-2.0
def __init__(self, opt): """Initialize the BaseModel class. Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions When creating your custom class, you need to implement your own initialization. In this fucntion, you should f...
Initialize the BaseModel class. Parameters: opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions When creating your custom class, you need to implement your own initialization. In this fucntion, you should first call <BaseModel.__init__(self, ...
__init__
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def setup(self, opt): """Load and print networks; create schedulers Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions """ if self.isTrain: self.schedulers = [networks.get_scheduler(optimizer, opt) for optimiz...
Load and print networks; create schedulers Parameters: opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
setup
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def update_learning_rate(self): """Update learning rates for all the networks; called at the end of every epoch""" for scheduler in self.schedulers: if self.opt.lr_policy == 'plateau': scheduler.step(self.metric) else: scheduler.step() lr ...
Update learning rates for all the networks; called at the end of every epoch
update_learning_rate
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def get_current_visuals(self): """Return visualization images. train.py will display these images with visdom, and save the images to a HTML""" visual_ret = OrderedDict() for name in self.visual_names: if isinstance(name, str): visual_ret[name] = getattr(self, name)[:...
Return visualization images. train.py will display these images with visdom, and save the images to a HTML
get_current_visuals
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def get_current_losses(self): """Return traning losses / errors. train.py will print out these errors on console, and save them to a file""" errors_ret = OrderedDict() for name in self.loss_names: if isinstance(name, str): errors_ret[name] = float(getattr(self, 'loss_...
Return traning losses / errors. train.py will print out these errors on console, and save them to a file
get_current_losses
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def save_networks(self, epoch): """Save all the networks to the disk. Parameters: epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name) """ if not os.path.isdir(self.save_dir): os.makedirs(self.save_dir) save_filename = 'epo...
Save all the networks to the disk. Parameters: epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
save_networks
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0): """Fix InstanceNorm checkpoints incompatibility (prior to 0.4)""" key = keys[i] if i + 1 == len(keys): # at the end, pointing to a parameter/buffer if module.__class__.__name__.startswith('InstanceNorm') and ...
Fix InstanceNorm checkpoints incompatibility (prior to 0.4)
__patch_instance_norm_state_dict
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def load_networks(self, epoch): """Load all the networks from the disk. Parameters: epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name) """ if self.opt.isTrain and self.opt.pretrained_name is not None: load_dir = os.path.join(self....
Load all the networks from the disk. Parameters: epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
load_networks
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def print_networks(self, verbose): """Print the total number of parameters in the network and (if verbose) network architecture Parameters: verbose (bool) -- if verbose: print the network architecture """ print('---------- Networks initialized -------------') for nam...
Print the total number of parameters in the network and (if verbose) network architecture Parameters: verbose (bool) -- if verbose: print the network architecture
print_networks
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def set_requires_grad(self, nets, requires_grad=False): """Set requies_grad=Fasle for all the networks to avoid unnecessary computations Parameters: nets (network list) -- a list of networks requires_grad (bool) -- whether the networks require gradients or not """ ...
Set requies_grad=Fasle for all the networks to avoid unnecessary computations Parameters: nets (network list) -- a list of networks requires_grad (bool) -- whether the networks require gradients or not
set_requires_grad
python
OpenTalker/video-retalking
third_part/face3d/models/base_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/base_model.py
Apache-2.0
def compute_shape(self, id_coeff, exp_coeff): """ Return: face_shape -- torch.tensor, size (B, N, 3) Parameters: id_coeff -- torch.tensor, size (B, 80), identity coeffs exp_coeff -- torch.tensor, size (B, 64), expression coeffs ""...
Return: face_shape -- torch.tensor, size (B, N, 3) Parameters: id_coeff -- torch.tensor, size (B, 80), identity coeffs exp_coeff -- torch.tensor, size (B, 64), expression coeffs
compute_shape
python
OpenTalker/video-retalking
third_part/face3d/models/bfm.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py
Apache-2.0
def compute_texture(self, tex_coeff, normalize=True): """ Return: face_texture -- torch.tensor, size (B, N, 3), in RGB order, range (0, 1.) Parameters: tex_coeff -- torch.tensor, size (B, 80) """ batch_size = tex_coeff.shape[0] face_tex...
Return: face_texture -- torch.tensor, size (B, N, 3), in RGB order, range (0, 1.) Parameters: tex_coeff -- torch.tensor, size (B, 80)
compute_texture
python
OpenTalker/video-retalking
third_part/face3d/models/bfm.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py
Apache-2.0
def compute_norm(self, face_shape): """ Return: vertex_norm -- torch.tensor, size (B, N, 3) Parameters: face_shape -- torch.tensor, size (B, N, 3) """ v1 = face_shape[:, self.face_buf[:, 0]] v2 = face_shape[:, self.face_buf[:, 1]] ...
Return: vertex_norm -- torch.tensor, size (B, N, 3) Parameters: face_shape -- torch.tensor, size (B, N, 3)
compute_norm
python
OpenTalker/video-retalking
third_part/face3d/models/bfm.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py
Apache-2.0
def compute_color(self, face_texture, face_norm, gamma): """ Return: face_color -- torch.tensor, size (B, N, 3), range (0, 1.) Parameters: face_texture -- torch.tensor, size (B, N, 3), from texture model, range (0, 1.) face_norm -- torch.tens...
Return: face_color -- torch.tensor, size (B, N, 3), range (0, 1.) Parameters: face_texture -- torch.tensor, size (B, N, 3), from texture model, range (0, 1.) face_norm -- torch.tensor, size (B, N, 3), rotated face normal gamma ...
compute_color
python
OpenTalker/video-retalking
third_part/face3d/models/bfm.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py
Apache-2.0
def compute_rotation(self, angles): """ Return: rot -- torch.tensor, size (B, 3, 3) pts @ trans_mat Parameters: angles -- torch.tensor, size (B, 3), radian """ batch_size = angles.shape[0] ones = torch.ones([batch_size, 1])...
Return: rot -- torch.tensor, size (B, 3, 3) pts @ trans_mat Parameters: angles -- torch.tensor, size (B, 3), radian
compute_rotation
python
OpenTalker/video-retalking
third_part/face3d/models/bfm.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py
Apache-2.0
def to_image(self, face_shape): """ Return: face_proj -- torch.tensor, size (B, N, 2), y direction is opposite to v direction Parameters: face_shape -- torch.tensor, size (B, N, 3) """ # to image_plane face_proj = face_shape @ self.pe...
Return: face_proj -- torch.tensor, size (B, N, 2), y direction is opposite to v direction Parameters: face_shape -- torch.tensor, size (B, N, 3)
to_image
python
OpenTalker/video-retalking
third_part/face3d/models/bfm.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py
Apache-2.0
def split_coeff(self, coeffs): """ Return: coeffs_dict -- a dict of torch.tensors Parameters: coeffs -- torch.tensor, size (B, 256) """ id_coeffs = coeffs[:, :80] exp_coeffs = coeffs[:, 80: 144] tex_coeffs = coeffs[:, 144: 224...
Return: coeffs_dict -- a dict of torch.tensors Parameters: coeffs -- torch.tensor, size (B, 256)
split_coeff
python
OpenTalker/video-retalking
third_part/face3d/models/bfm.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py
Apache-2.0
def compute_for_render(self, coeffs): """ Return: face_vertex -- torch.tensor, size (B, N, 3), in camera coordinate face_color -- torch.tensor, size (B, N, 3), in RGB order landmark -- torch.tensor, size (B, 68, 2), y direction is opposite to v directi...
Return: face_vertex -- torch.tensor, size (B, N, 3), in camera coordinate face_color -- torch.tensor, size (B, N, 3), in RGB order landmark -- torch.tensor, size (B, 68, 2), y direction is opposite to v direction Parameters: coeffs ...
compute_for_render
python
OpenTalker/video-retalking
third_part/face3d/models/bfm.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/bfm.py
Apache-2.0
def modify_commandline_options(parser, is_train=True): """ Configures options specific for CUT model """ # net structure and parameters parser.add_argument('--net_recon', type=str, default='resnet50', choices=['resnet18', 'resnet34', 'resnet50'], help='network structure') parser...
Configures options specific for CUT model
modify_commandline_options
python
OpenTalker/video-retalking
third_part/face3d/models/facerecon_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/facerecon_model.py
Apache-2.0
def __init__(self, opt): """Initialize this model class. Parameters: opt -- training/test options A few things can be done here. - (required) call the initialization function of BaseModel - define loss function, visualization images, model names, and optimizers ...
Initialize this model class. Parameters: opt -- training/test options A few things can be done here. - (required) call the initialization function of BaseModel - define loss function, visualization images, model names, and optimizers
__init__
python
OpenTalker/video-retalking
third_part/face3d/models/facerecon_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/facerecon_model.py
Apache-2.0
def set_input(self, input): """Unpack input data from the dataloader and perform necessary pre-processing steps. Parameters: input: a dictionary that contains the data itself and its metadata information. """ self.input_img = input['imgs'].to(self.device) self.atten...
Unpack input data from the dataloader and perform necessary pre-processing steps. Parameters: input: a dictionary that contains the data itself and its metadata information.
set_input
python
OpenTalker/video-retalking
third_part/face3d/models/facerecon_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/facerecon_model.py
Apache-2.0
def compute_losses(self): """Calculate losses, gradients, and update network weights; called in every training iteration""" assert self.net_recog.training == False trans_m = self.trans_m if not self.opt.use_predef_M: trans_m = estimate_norm_torch(self.pred_lm, self.input_img...
Calculate losses, gradients, and update network weights; called in every training iteration
compute_losses
python
OpenTalker/video-retalking
third_part/face3d/models/facerecon_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/facerecon_model.py
Apache-2.0
def forward(imageA, imageB, M): """ 1 - cosine distance Parameters: imageA --torch.tensor (B, 3, H, W), range (0, 1) , RGB order imageB --same as imageA """ imageA = self.preprocess(resize_n_crop(imageA, M, self.input_size)) imageB = s...
1 - cosine distance Parameters: imageA --torch.tensor (B, 3, H, W), range (0, 1) , RGB order imageB --same as imageA
forward
python
OpenTalker/video-retalking
third_part/face3d/models/losses.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py
Apache-2.0
def photo_loss(imageA, imageB, mask, eps=1e-6): """ l2 norm (with sqrt, to ensure backward stabililty, use eps, otherwise Nan may occur) Parameters: imageA --torch.tensor (B, 3, H, W), range (0, 1), RGB order imageB --same as imageA """ loss = torch.sqrt(eps + torch.sum(...
l2 norm (with sqrt, to ensure backward stabililty, use eps, otherwise Nan may occur) Parameters: imageA --torch.tensor (B, 3, H, W), range (0, 1), RGB order imageB --same as imageA
photo_loss
python
OpenTalker/video-retalking
third_part/face3d/models/losses.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py
Apache-2.0
def landmark_loss(predict_lm, gt_lm, weight=None): """ weighted mse loss Parameters: predict_lm --torch.tensor (B, 68, 2) gt_lm --torch.tensor (B, 68, 2) weight --numpy.array (1, 68) """ if not weight: weight = np.ones([68]) weight[28:31] = 2...
weighted mse loss Parameters: predict_lm --torch.tensor (B, 68, 2) gt_lm --torch.tensor (B, 68, 2) weight --numpy.array (1, 68)
landmark_loss
python
OpenTalker/video-retalking
third_part/face3d/models/losses.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py
Apache-2.0
def reg_loss(coeffs_dict, opt=None): """ l2 norm without the sqrt, from yu's implementation (mse) tf.nn.l2_loss https://www.tensorflow.org/api_docs/python/tf/nn/l2_loss Parameters: coeffs_dict -- a dict of torch.tensors , keys: id, exp, tex, angle, gamma, trans """ # coefficient re...
l2 norm without the sqrt, from yu's implementation (mse) tf.nn.l2_loss https://www.tensorflow.org/api_docs/python/tf/nn/l2_loss Parameters: coeffs_dict -- a dict of torch.tensors , keys: id, exp, tex, angle, gamma, trans
reg_loss
python
OpenTalker/video-retalking
third_part/face3d/models/losses.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py
Apache-2.0
def reflectance_loss(texture, mask): """ minimize texture variance (mse), albedo regularization to ensure an uniform skin albedo Parameters: texture --torch.tensor, (B, N, 3) mask --torch.tensor, (N), 1 or 0 """ mask = mask.reshape([1, mask.shape[0], 1]) texture_m...
minimize texture variance (mse), albedo regularization to ensure an uniform skin albedo Parameters: texture --torch.tensor, (B, N, 3) mask --torch.tensor, (N), 1 or 0
reflectance_loss
python
OpenTalker/video-retalking
third_part/face3d/models/losses.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/losses.py
Apache-2.0
def resnext50_32x4d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet: r"""ResNeXt-50 32x4d model from `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_. Args: pretrained (bool): If True, returns a model pre-trained on Im...
ResNeXt-50 32x4d model from `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
resnext50_32x4d
python
OpenTalker/video-retalking
third_part/face3d/models/networks.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/networks.py
Apache-2.0
def resnext101_32x8d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet: r"""ResNeXt-101 32x8d model from `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_. Args: pretrained (bool): If True, returns a model pre-trained on ...
ResNeXt-101 32x8d model from `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
resnext101_32x8d
python
OpenTalker/video-retalking
third_part/face3d/models/networks.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/networks.py
Apache-2.0
def wide_resnet50_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet: r"""Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every ...
Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 h...
wide_resnet50_2
python
OpenTalker/video-retalking
third_part/face3d/models/networks.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/networks.py
Apache-2.0
def wide_resnet101_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet: r"""Wide ResNet-101-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in ever...
Wide ResNet-101-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_. The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 ...
wide_resnet101_2
python
OpenTalker/video-retalking
third_part/face3d/models/networks.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/networks.py
Apache-2.0
def modify_commandline_options(parser, is_train=True): """Add new model-specific options and rewrite default values for existing options. Parameters: parser -- the option parser is_train -- if it is training phase or test phase. You can use this flag to add training-specific or ...
Add new model-specific options and rewrite default values for existing options. Parameters: parser -- the option parser is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options. Returns: the modified ...
modify_commandline_options
python
OpenTalker/video-retalking
third_part/face3d/models/template_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/template_model.py
Apache-2.0
def __init__(self, opt): """Initialize this model class. Parameters: opt -- training/test options A few things can be done here. - (required) call the initialization function of BaseModel - define loss function, visualization images, model names, and optimizers ...
Initialize this model class. Parameters: opt -- training/test options A few things can be done here. - (required) call the initialization function of BaseModel - define loss function, visualization images, model names, and optimizers
__init__
python
OpenTalker/video-retalking
third_part/face3d/models/template_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/template_model.py
Apache-2.0
def set_input(self, input): """Unpack input data from the dataloader and perform necessary pre-processing steps. Parameters: input: a dictionary that contains the data itself and its metadata information. """ AtoB = self.opt.direction == 'AtoB' # use <direction> to swap dat...
Unpack input data from the dataloader and perform necessary pre-processing steps. Parameters: input: a dictionary that contains the data itself and its metadata information.
set_input
python
OpenTalker/video-retalking
third_part/face3d/models/template_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/template_model.py
Apache-2.0
def backward(self): """Calculate losses, gradients, and update network weights; called in every training iteration""" # calculate the intermediate results if necessary; here self.output has been computed during function <forward> # calculate loss given the input and intermediate results ...
Calculate losses, gradients, and update network weights; called in every training iteration
backward
python
OpenTalker/video-retalking
third_part/face3d/models/template_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/template_model.py
Apache-2.0
def optimize_parameters(self): """Update network weights; it will be called in every training iteration.""" self.forward() # first call forward to calculate intermediate results self.optimizer.zero_grad() # clear network G's existing gradients self.backward() ...
Update network weights; it will be called in every training iteration.
optimize_parameters
python
OpenTalker/video-retalking
third_part/face3d/models/template_model.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/template_model.py
Apache-2.0
def find_model_using_name(model_name): """Import the module "models/[model_name]_model.py". In the file, the class called DatasetNameModel() will be instantiated. It has to be a subclass of BaseModel, and it is case-insensitive. """ model_filename = "face3d.models." + model_name + "_model" ...
Import the module "models/[model_name]_model.py". In the file, the class called DatasetNameModel() will be instantiated. It has to be a subclass of BaseModel, and it is case-insensitive.
find_model_using_name
python
OpenTalker/video-retalking
third_part/face3d/models/__init__.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/__init__.py
Apache-2.0
def create_model(opt): """Create a model given the option. This function warps the class CustomDatasetDataLoader. This is the main interface between this package and 'train.py'/'test.py' Example: >>> from models import create_model >>> model = create_model(opt) """ model = find...
Create a model given the option. This function warps the class CustomDatasetDataLoader. This is the main interface between this package and 'train.py'/'test.py' Example: >>> from models import create_model >>> model = create_model(opt)
create_model
python
OpenTalker/video-retalking
third_part/face3d/models/__init__.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/__init__.py
Apache-2.0
def __init__(self, rank, local_rank, world_size, batch_size, resume, margin_softmax, num_classes, sample_rate=1.0, embedding_size=512, prefix="./"): """ rank: int Unique process(GPU) ID from 0 to world_size - 1. local_rank: int Unique process(GPU) ID with...
rank: int Unique process(GPU) ID from 0 to world_size - 1. local_rank: int Unique process(GPU) ID within the server from 0 to 7. world_size: int Number of GPU. batch_size: int Batch size on current rank(GPU). resume: bool ...
__init__
python
OpenTalker/video-retalking
third_part/face3d/models/arcface_torch/partial_fc.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py
Apache-2.0
def sample(self, total_label): """ Sample all positive class centers in each rank, and random select neg class centers to filling a fixed `num_sample`. total_label: tensor Label after all gather, which cross all GPUs. """ index_positive = (self.class_start <=...
Sample all positive class centers in each rank, and random select neg class centers to filling a fixed `num_sample`. total_label: tensor Label after all gather, which cross all GPUs.
sample
python
OpenTalker/video-retalking
third_part/face3d/models/arcface_torch/partial_fc.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py
Apache-2.0
def update(self): """ Set updated weight and weight_mom to memory bank. """ self.weight_mom[self.index] = self.sub_weight_mom self.weight[self.index] = self.sub_weight
Set updated weight and weight_mom to memory bank.
update
python
OpenTalker/video-retalking
third_part/face3d/models/arcface_torch/partial_fc.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py
Apache-2.0
def prepare(self, label, optimizer): """ get sampled class centers for cal softmax. label: tensor Label tensor on each rank. optimizer: opt Optimizer for partial fc, which need to get weight mom. """ with torch.cuda.stream(self.stream): ...
get sampled class centers for cal softmax. label: tensor Label tensor on each rank. optimizer: opt Optimizer for partial fc, which need to get weight mom.
prepare
python
OpenTalker/video-retalking
third_part/face3d/models/arcface_torch/partial_fc.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py
Apache-2.0
def forward_backward(self, label, features, optimizer): """ Partial fc forward and backward with model parallel label: tensor Label tensor on each rank(GPU) features: tensor Features tensor on each rank(GPU) optimizer: optimizer Optimizer for ...
Partial fc forward and backward with model parallel label: tensor Label tensor on each rank(GPU) features: tensor Features tensor on each rank(GPU) optimizer: optimizer Optimizer for partial fc Returns: -------- x_grad: tenso...
forward_backward
python
OpenTalker/video-retalking
third_part/face3d/models/arcface_torch/partial_fc.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/partial_fc.py
Apache-2.0
def scale(self, outputs): """ Multiplies ('scales') a tensor or list of tensors by the scale factor. Returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, outputs are returned unmodified. Arguments: outputs (Tensor or iterable of Tensors):...
Multiplies ('scales') a tensor or list of tensors by the scale factor. Returns scaled outputs. If this instance of :class:`GradScaler` is not enabled, outputs are returned unmodified. Arguments: outputs (Tensor or iterable of Tensors): Outputs to scale.
scale
python
OpenTalker/video-retalking
third_part/face3d/models/arcface_torch/utils/utils_amp.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/models/arcface_torch/utils/utils_amp.py
Apache-2.0
def __init__(self, cmd_line=None): """Reset the class; indicates the class hasn't been initialized""" self.initialized = False self.cmd_line = None if cmd_line is not None: self.cmd_line = cmd_line.split()
Reset the class; indicates the class hasn't been initialized
__init__
python
OpenTalker/video-retalking
third_part/face3d/options/base_options.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py
Apache-2.0
def initialize(self, parser): """Define the common options that are used in both training and test.""" # basic parameters parser.add_argument('--name', type=str, default='face_recon', help='name of the experiment. It decides where to store samples and models') parser.add_argument('--gpu_...
Define the common options that are used in both training and test.
initialize
python
OpenTalker/video-retalking
third_part/face3d/options/base_options.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py
Apache-2.0
def gather_options(self): """Initialize our parser with basic options(only once). Add additional model-specific and dataset-specific options. These options are defined in the <modify_commandline_options> function in model and dataset classes. """ if not self.initialized: ...
Initialize our parser with basic options(only once). Add additional model-specific and dataset-specific options. These options are defined in the <modify_commandline_options> function in model and dataset classes.
gather_options
python
OpenTalker/video-retalking
third_part/face3d/options/base_options.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py
Apache-2.0
def print_options(self, opt): """Print and save options It will print both current options and default values(if different). It will save options into a text file / [checkpoints_dir] / opt.txt """ message = '' message += '----------------- Options ---------------\n' ...
Print and save options It will print both current options and default values(if different). It will save options into a text file / [checkpoints_dir] / opt.txt
print_options
python
OpenTalker/video-retalking
third_part/face3d/options/base_options.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py
Apache-2.0
def parse(self): """Parse our options, create checkpoints directory suffix, and set up gpu device.""" opt = self.gather_options() opt.isTrain = self.isTrain # train or test # process opt.suffix if opt.suffix: suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.s...
Parse our options, create checkpoints directory suffix, and set up gpu device.
parse
python
OpenTalker/video-retalking
third_part/face3d/options/base_options.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/options/base_options.py
Apache-2.0
def __init__(self, web_dir, title, refresh=0): """Initialize the HTML classes Parameters: web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/ title (str) -- the webpage name ...
Initialize the HTML classes Parameters: web_dir (str) -- a directory that stores the webpage. HTML file will be created at <web_dir>/index.html; images will be saved at <web_dir/images/ title (str) -- the webpage name refresh (int) -- how often the website refresh itself; ...
__init__
python
OpenTalker/video-retalking
third_part/face3d/util/html.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/html.py
Apache-2.0
def add_images(self, ims, txts, links, width=400): """add images to the HTML file Parameters: ims (str list) -- a list of image paths txts (str list) -- a list of image names shown on the website links (str list) -- a list of hyperref links; when you click an ima...
add images to the HTML file Parameters: ims (str list) -- a list of image paths txts (str list) -- a list of image names shown on the website links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page
add_images
python
OpenTalker/video-retalking
third_part/face3d/util/html.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/html.py
Apache-2.0
def save(self): """save the current content to the HTML file""" html_file = '%s/index.html' % self.web_dir f = open(html_file, 'wt') f.write(self.doc.render()) f.close()
save the current content to the HTML file
save
python
OpenTalker/video-retalking
third_part/face3d/util/html.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/html.py
Apache-2.0
def forward(self, vertex, tri, feat=None): """ Return: mask -- torch.tensor, size (B, 1, H, W) depth -- torch.tensor, size (B, 1, H, W) features(optional) -- torch.tensor, size (B, C, H, W) if feat is not None Parameters: ...
Return: mask -- torch.tensor, size (B, 1, H, W) depth -- torch.tensor, size (B, 1, H, W) features(optional) -- torch.tensor, size (B, C, H, W) if feat is not None Parameters: vertex -- torch.tensor, size (B, N, 3) ...
forward
python
OpenTalker/video-retalking
third_part/face3d/util/nvdiffrast.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/nvdiffrast.py
Apache-2.0
def align_img(img, lm, lm3D, mask=None, target_size=224., rescale_factor=102.): """ Return: transparams --numpy.array (raw_W, raw_H, scale, tx, ty) img_new --PIL.Image (target_size, target_size, 3) lm_new --numpy.array (68, 2), y direction is opposite to ...
Return: transparams --numpy.array (raw_W, raw_H, scale, tx, ty) img_new --PIL.Image (target_size, target_size, 3) lm_new --numpy.array (68, 2), y direction is opposite to v direction mask_new --PIL.Image (target_size, target_size) ...
align_img
python
OpenTalker/video-retalking
third_part/face3d/util/preprocess.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/preprocess.py
Apache-2.0
def estimate_norm(lm_68p, H): # from https://github.com/deepinsight/insightface/blob/c61d3cd208a603dfa4a338bd743b320ce3e94730/recognition/common/face_align.py#L68 """ Return: trans_m --numpy.array (2, 3) Parameters: lm --numpy.array (68, 2), y direction is op...
Return: trans_m --numpy.array (2, 3) Parameters: lm --numpy.array (68, 2), y direction is opposite to v direction H --int/float , image height
estimate_norm
python
OpenTalker/video-retalking
third_part/face3d/util/preprocess.py
https://github.com/OpenTalker/video-retalking/blob/master/third_part/face3d/util/preprocess.py
Apache-2.0