code
stringlengths
17
6.64M
def _child(new, *args, **kwargs): ...
class TestDelegates(): def test_default(self): fn = delegates(_parent)(_child) sig = inspect.signature(fn) sigd = dict(sig.parameters) assert (list(sigd) == ['new', 'a', 'b', 'c']), 'Incorrect delegated signature.'
def _stringify(x, suffix=''): 'Helper.' return f'{x}{suffix}'
class TestMapContainer(): def test_single(self): 'Test with a single input, i.e. equivalent to the original function.' input = 2 func = map_container(_stringify) assert (func(input) == _stringify(input)), "Error in 'map_apply' single input" assert (func(input, suffix='***'...
class Dataset(): def __init__(self, n): self.n = n self.log_time = True self.timer = MultiLevelTimer() self.__class__.__getitem__ = retry_new_on_error(self.__class__.getitem, exc=self.retry_exc, silent=self.silent, max=self.max, use_blacklist=self.use_blacklist) def __init_su...
class TestRetryDifferentOnError(): def test_default(self): 'Test default parameters, catching any exception and logging.' class TmpData(Dataset, retry_exc=Exception, silent=False, max_retries=None, use_blacklist=False): def getitem(self, item): if ((item % 2) == 0): ...
def _random_pil(shape): return Image.fromarray(np.random.randint(0, 255, size=shape, dtype=np.uint8))
def _random_np(shape): return np.random.rand(*shape).astype(np.float32)
def _random_torch(shape): return torch.rand(shape, dtype=torch.float32)
def test_all(): 'Check all expected symbols are imported.' items = {'readlines', 'pil2np', 'np2pil', 'write_yaml', 'load_yaml', 'load_merge_yaml'} assert (set(io.__all__) == items), 'Incorrect keys in `__all__`.'
def test_pil2np(): 'Test conversion from PIL to numpy.' shape = (100, 200, 3) image = _random_pil(shape) out = pil2np(image) assert isinstance(out, np.ndarray), 'Output should be a numpy array.' assert (out.dtype == np.float32), 'Output should be float32.' assert (out.shape == shape), 'Out...
def test_np2pil(): 'Test conversion from numpy to PIL.' shape = (h, w, _) = (100, 200, 3) image = _random_np(shape) out = np2pil(image) assert isinstance(out, Image.Image), 'Output should be a PIL Image.' assert (out.size == (w, h)), 'Output should be same size as input.' (vmax, vmin) = ou...
def test_all(): 'Check all expected symbols are imported.' items = {'get_logger', 'flatten_dict', 'sort_dict', 'apply_cmap'} assert (set(misc.__all__) == items), 'Incorrect keys in `__all__`.'
class TensorGetLogger(): def test_default(self): key = 'test1234' logger = get_logger(key) assert (key in logging.root.manager.loggerDict), 'Logger not created.' assert (logger == logging.root.manager.loggerDict[key]), 'Incorrect logger created.' assert (not logger.propaga...
class TestFlatten(): def test_default(self): 'Test basic nesting & default separator.' d = {'a': 1, 'b': 2, 'c': dict(a=1, b=2)} tgt = {'a': 1, 'b': 2, 'c/a': 1, 'c/b': 2} out = flatten_dict(d) assert (out == tgt), 'Incorrect flattened keys.' out = flatten_dict(d, ...
class TestSortedDict(): def test_sorted_dict(self): 'Test sorting dict keys.' d = dict(b=2, c=1, a=10) tgt = dict(a=10, b=2, c=1) out = sort_dict(d) assert (out == tgt), 'Incorrect sorted order' with pytest.raises(TypeError): sort_dict({'a': 1, 1: 0, 't...
class TestApplyCmap(): def test_default(self): 'Test applying a cmap with default parameters.' arr = np.array([0, 0, 0.5, 0.5, 1, 1]) out = apply_cmap(arr) assert np.allclose(out[0], out[1]), 'Incorrect 0 mapping.' assert np.allclose(out[2], out[3]), 'Incorrect 0.5 mapping...
def test_all(): 'Check all expected symbols are imported.' items = {'Timer', 'MultiLevelTimer'} assert (set(timers.__all__) == items), 'Incorrect keys in `__all__`.'
class TestTimer(): def test_options(self): 'Test that formatting options are set correctly.' (name, precision) = ('Test', 4) timer = Timer(name=name, as_ms=True, precision=precision) assert (timer.name == name), 'Incorrect Timer name' assert (repr(timer) == f'Timer(name={n...
class TestMultiLevelTimer(): def test_options(self): 'Test that formatting options are set correctly.' (name, precision) = ('Test', 4) timer = MultiLevelTimer(name=name, as_ms=True, sync_gpu=False, precision=precision) assert (repr(timer) == f'MultiLevelTimer(name={name}, as_ms=Tr...
class FontDataLoader(): def __init__(self, dataset, sampler, batch_size): self.data_loader = torch.utils.data.DataLoader(dataset, sampler=sampler, batch_size=batch_size) def __iter__(self): self.data_loader_iterator = iter(self.data_loader) return self def __next__(self): ...
class FontData(): def __init__(self, font_name, font_path, image=None): self.font_name = font_name self.font_path = font_path self.image = None def load_data(self, loader): if (self.image == None): self.image = loader(self.font_path) return self.image ...
class FontDataset(Dataset): 'The Font Dataset.' def __init__(self, root_dir, glyph_size=(64, 64), glyphs_per_image=26): self.fonts = self.load_font_filenames(root_dir) self.root_dir = root_dir self.glyph_size = glyph_size self.glyphs_per_image = glyphs_per_image def __len...
def image_loader(path): return Image.open(path).convert('RGB')
def l1_and_adversarial_loss(D, G, real_data, generated_data, losses, options): l1_lamba = 10 return (min_max_loss(D, G, real_data, generated_data, losses, options) + (l1_lamba * l1_loss(D, G, real_data, generated_data, losses, options)))
def wasserstein_loss(D, G, real_data, generated_data, losses, options): real_loss = D(real_data) generated_loss = D(generated_data) (batch_size, data_type) = itemgetter('batch_size', 'data_type')(options) gradient_penalty_weight = 10 gradient_penalty = calculate_gradient_penalty(D, real_data, gene...
def min_max_loss(D, G, real_data, generated_data, losses, options): discriminator_loss = D(generated_data) loss = (- discriminator_loss.mean()) return loss
def l1_loss(D, G, real_data, generated_data, losses, options): '\n Performs the L1 loss between the generated data and the real data.\n\n It is expected that both `real_data` and `generated_data` are of the same shape.\n ' return torch.nn.L1Loss()(generated_data, real_data)
def calculate_gradient_penalty(D, real_data, generated_data, batch_size, gradient_penalty_weight, losses, data_type): alpha = torch.rand(batch_size, 1, 1, 1).expand_as(real_data).type(data_type) interpolated = ((alpha * real_data.data) + ((1 - alpha) * generated_data.data)).type(data_type) interpolated.re...
def build_font_shape_generator(glyph_size=(64, 64, 1), glyph_count=26, dimension=16): '\n Generator model for our GAN.\n\n Architecture is similar to DC-GAN with the exception of the input being an image.\n\n Inputs:\n - `image_size`: A triple (W, H, C) for the size of the images and number of channels. This ...
def simple_upscale_generator(dimension): '\n A generator that performs several ConvTranpsose2D Operations to upscale an image from `individual_image_size` to `final_image_size`. The dimensions of `final_image_size` must be an integer multiple of `individual_image_size.`\n\n Inputs:\n - `individual_image_size`:...
def intermediate_generator(glyph_size=(64, 64), glyph_count=26, dimension=16): linear_width = int((((((2 * dimension) * glyph_size[0]) / 4) * glyph_size[1]) / 4)) hidden_width = int((glyph_size[0] * glyph_size[1])) final_width = int(((((4 * dimension) * glyph_count) * 2) * 2)) return nn.Sequential(nn....
def intermediate_generator_alt(glyph_size=(16, 16), glyph_count=26, dimension=512): conv_dimensions = [dimension, int((dimension / 2)), int((dimension / 4))] fc_layer_widths = [int(((((conv_dimensions[2] * glyph_size[0]) / 8) * glyph_size[1]) / 8)), int((glyph_size[0] * glyph_size[1])), int(((((((glyph_size[0...
def build_font_shape_discriminator(image_size=(64, 1664), dimension=16): '\n PyTorch model implementing the GlyphGAN critic.\n\n Inputs:\n - `image_size`: The size of the entire alphabet (usually (H, W * 26))\n - `dimension`: The filter depth after each conv. Doubles per conv layer (1 - > 2 -> 4 -> 8)\n ' ...
def get_optimizer(model, learning_rate=0.0002, beta1=0.5, beta2=0.99): '\n Adam optimizer for model\n\n Input:\n - model: A PyTorch model that we want to optimize.\n\n Returns:\n - An Adam optimizer for the model with the desired hyperparameters.\n ' optimizer = optim.Adam(model.parameters()...
class Flatten(nn.Module): def forward(self, x): (N, _, _, _) = x.size() return x.view(N, (- 1))
class Unflatten(nn.Module): '\n An Unflatten module receives an input of shape (N, C*H*W) and reshapes it\n to produce an output of shape (N, C, H, W).\n ' def __init__(self, N=(- 1), C=128, H=7, W=7): super(Unflatten, self).__init__() self.N = N self.C = C self.H = H ...
def initialize_weights(m): if (isinstance(m, nn.Linear) or isinstance(m, nn.ConvTranspose2d) or isinstance(m, nn.Conv2d)): nn.init.xavier_uniform_(m.weight.data)
class TestFontDatasets(unittest.TestCase): def test_cannot_create_invalid_font_dataset(self): with self.assertRaises(AssertionError): FontDataset('does_not_exist') def test_can_create_font_dataset(self): dataset = FontDataset(abspath(join(dirname(__file__), 'test_datasets/valid')...
def show_grayscale_image(image): plot.imshow(transforms.Compose([transforms.ToPILImage(), transforms.Grayscale(num_output_channels=3)])(image)) plot.axis('off') plot.show()
def CreateDataset(opt): 'loads dataset class' if ((opt.arch == 'vae') or (opt.arch == 'gan')): from data.grasp_sampling_data import GraspSamplingData dataset = GraspSamplingData(opt) else: from data.grasp_evaluator_data import GraspEvaluatorData dataset = GraspEvaluatorData...
class DataLoader(): 'multi-threaded data loading' def __init__(self, opt): self.opt = opt self.dataset = CreateDataset(opt) self.dataloader = torch.utils.data.DataLoader(self.dataset, batch_size=opt.num_objects_per_batch, shuffle=(not opt.serial_batches), num_workers=int(opt.num_threa...
def create_model(opt): from .grasp_net import GraspNetModel model = GraspNetModel(opt) return model
class GraspNetModel(): ' Class for training Model weights\n\n :args opt: structure containing configuration params\n e.g.,\n --dataset_mode -> sampling / evaluation)\n ' def __init__(self, opt): self.opt = opt self.gpu_ids = opt.gpu_ids self.is_train = opt.is_train ...
def control_point_l1_loss_better_than_threshold(pred_control_points, gt_control_points, confidence, confidence_threshold, device='cpu'): npoints = pred_control_points.shape[1] mask = torch.greater_equal(confidence, confidence_threshold) mask_ratio = torch.mean(mask) mask = torch.repeat_interleave(mask...
def accuracy_better_than_threshold(pred_success_logits, gt, confidence, confidence_threshold, device='cpu'): '\n Computes average precision for the grasps with confidence > threshold.\n ' pred_classes = torch.argmax(pred_success_logits, (- 1)) correct = torch.equal(pred_classes, gt) mask = tor...
def control_point_l1_loss(pred_control_points, gt_control_points, confidence=None, confidence_weight=None, device='cpu'): '\n Computes the l1 loss between the predicted control points and the\n groundtruth control points on the gripper.\n ' error = torch.sum(torch.abs((pred_control_points - gt_co...
def classification_with_confidence_loss(pred_logit, gt, confidence, confidence_weight, device='cpu'): '\n Computes the cross entropy loss and confidence term that penalizes\n outputing zero confidence. Returns cross entropy loss and the confidence\n regularization term.\n ' classification_lo...
def min_distance_loss(pred_control_points, gt_control_points, confidence=None, confidence_weight=None, threshold=None, device='cpu'): '\n Computes the minimum distance (L1 distance)between each gt control point \n and any of the predicted control points.\n\n Args: \n pred_control_points: tensor of (...
def min_distance_better_than_threshold(pred_control_points, gt_control_points, confidence, confidence_threshold, device='cpu'): error = (torch.expand_dims(pred_control_points, 1) - torch.expand_dims(gt_control_points, 0)) error = torch.sum(torch.abs(error), (- 1)) error = torch.mean(error, (- 1)) erro...
def kl_divergence(mu, log_sigma, device='cpu'): '\n Computes the kl divergence for batch of mu and log_sigma.\n ' return torch.mean(((- 0.5) * torch.sum((((1.0 + log_sigma) - (mu ** 2)) - torch.exp(log_sigma)), dim=(- 1))))
def confidence_loss(confidence, confidence_weight, device='cpu'): return (torch.mean(torch.log(torch.max(confidence, torch.tensor(1e-10).to(device)))) * confidence_weight)
def get_scheduler(optimizer, opt): if (opt.lr_policy == 'lambda'): def lambda_rule(epoch): lr_l = (1.0 - (max(0, (((epoch + 1) + 1) - opt.niter)) / float((opt.niter_decay + 1)))) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif (opt....
def init_weights(net, init_type, init_gain): def init_func(m): classname = m.__class__.__name__ if (hasattr(m, 'weight') and ((classname.find('Conv') != (- 1)) or (classname.find('Linear') != (- 1)))): if (init_type == 'normal'): init.normal_(m.weight.data, 0.0, init_g...
def init_net(net, init_type, init_gain, gpu_ids): if (len(gpu_ids) > 0): assert torch.cuda.is_available() net.cuda(gpu_ids[0]) net = net.cuda() net = torch.nn.DataParallel(net, gpu_ids) if (init_type != 'none'): init_weights(net, init_type, init_gain) return net
def define_classifier(opt, gpu_ids, arch, init_type, init_gain, device): net = None if (arch == 'vae'): net = GraspSamplerVAE(opt.model_scale, opt.pointnet_radius, opt.pointnet_nclusters, opt.latent_size, device) elif (arch == 'gan'): net = GraspSamplerGAN(opt.model_scale, opt.pointnet_rad...
def define_loss(opt): if (opt.arch == 'vae'): kl_loss = losses.kl_divergence reconstruction_loss = losses.control_point_l1_loss return (kl_loss, reconstruction_loss) elif (opt.arch == 'gan'): reconstruction_loss = losses.min_distance_loss return reconstruction_loss ...
class GraspSampler(nn.Module): def __init__(self, latent_size, device): super(GraspSampler, self).__init__() self.latent_size = latent_size self.device = device def create_decoder(self, model_scale, pointnet_radius, pointnet_nclusters, num_input_features): self.decoder = base...
class GraspSamplerVAE(GraspSampler): 'Network for learning a generative VAE grasp-sampler\n ' def __init__(self, model_scale, pointnet_radius=0.02, pointnet_nclusters=128, latent_size=2, device='cpu'): super(GraspSamplerVAE, self).__init__(latent_size, device) self.create_encoder(model_sca...
class GraspSamplerGAN(GraspSampler): '\n Altough the name says this sampler is based on the GAN formulation, it is\n not actually optimizing based on the commonly known adversarial game.\n Instead, it is based on the Implicit Maximum Likelihood Estimation from\n https://arxiv.org/pdf/1809.09087.pdf wh...
class GraspEvaluator(nn.Module): def __init__(self, model_scale=1, pointnet_radius=0.02, pointnet_nclusters=128, device='cpu'): super(GraspEvaluator, self).__init__() self.create_evaluator(pointnet_radius, model_scale, pointnet_nclusters) self.device = device def create_evaluator(sel...
def base_network(pointnet_radius, pointnet_nclusters, scale, in_features): sa1_module = pointnet2.PointnetSAModule(npoint=pointnet_nclusters, radius=pointnet_radius, nsample=64, mlp=[in_features, (64 * scale), (64 * scale), (128 * scale)]) sa2_module = pointnet2.PointnetSAModule(npoint=32, radius=0.04, nsampl...
class BaseOptions(): def __init__(self): self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.initialized = False def initialize(self): self.parser.add_argument('--dataset_root_folder', type=str, default='/home/jens/Documents/datasets/gra...
class TestOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--which_epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model') self.is_train = False
class TrainOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--print_freq', type=int, default=100, help='frequency of showing training results on console') self.parser.add_argument('--save_latest_freq', type=int, default=250, help='frequenc...
class OnlineObjectRenderer(): def __init__(self, fov=(np.pi / 6), caching=True): '\n Args:\n fov: float, \n ' self._fov = fov self._fy = self._fx = (1 / (0.5 / np.tan((self._fov * 0.5)))) self.mesh = None self._scene = None self.tmesh = None ...
def run_test(epoch=(- 1), name=''): print('Running Test') opt = TestOptions().parse() opt.serial_batches = True opt.name = name dataset = DataLoader(opt) model = create_model(opt) writer = Writer(opt) writer.reset_counter() for (i, data) in enumerate(dataset): model.set_inp...
def main(): opt = TrainOptions().parse() if (opt == None): return dataset = DataLoader(opt) dataset_size = (len(dataset) * opt.num_grasps_per_object) model = create_model(opt) writer = Writer(opt) total_steps = 0 for epoch in range(opt.epoch_count, ((opt.niter + opt.niter_decay...
class Writer(): def __init__(self, opt): self.name = opt.name self.opt = opt self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) self.log_name = os.path.join(self.save_dir, 'loss_log.txt') self.testacc_log = os.path.join(self.save_dir, 'testacc_log.txt') se...
def define_model(x, is_training, model, num_classes): if (model == 'MTT_musicnn'): return build_musicnn(x, is_training, num_classes, num_filt_midend=64, num_units_backend=200) elif (model == 'MTT_vgg'): return vgg(x, is_training, num_classes, 128) elif (model == 'MSD_musicnn'): ret...
def build_musicnn(x, is_training, num_classes, num_filt_frontend=1.6, num_filt_midend=64, num_units_backend=200): frontend_features_list = frontend(x, is_training, config.N_MELS, num_filt=1.6, type='7774timbraltemporal') frontend_features = tf.concat(frontend_features_list, 2) midend_features_list = miden...
def frontend(x, is_training, yInput, num_filt, type): expand_input = tf.expand_dims(x, 3) normalized_input = tf.compat.v1.layers.batch_normalization(expand_input, training=is_training) if ('timbral' in type): input_pad_7 = tf.pad(normalized_input, [[0, 0], [3, 3], [0, 0], [0, 0]], 'CONSTANT') ...
def timbral_block(inputs, filters, kernel_size, is_training, padding='valid', activation=tf.nn.relu): conv = tf.compat.v1.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, padding=padding, activation=activation) bn_conv = tf.compat.v1.layers.batch_normalization(conv, training=is_training)...
def tempo_block(inputs, filters, kernel_size, is_training, padding='same', activation=tf.nn.relu): conv = tf.compat.v1.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, padding=padding, activation=activation) bn_conv = tf.compat.v1.layers.batch_normalization(conv, training=is_training) ...
def midend(front_end_output, is_training, num_filt): front_end_output = tf.expand_dims(front_end_output, 3) front_end_pad = tf.pad(front_end_output, [[0, 0], [3, 3], [0, 0], [0, 0]], 'CONSTANT') conv1 = tf.compat.v1.layers.conv2d(inputs=front_end_pad, filters=num_filt, kernel_size=[7, front_end_pad.shape[...
def backend(feature_map, is_training, num_classes, output_units, type): max_pool = tf.reduce_max(feature_map, axis=1) (mean_pool, var_pool) = tf.nn.moments(feature_map, axes=[1]) tmp_pool = tf.concat([max_pool, mean_pool], 2) flat_pool = tf.compat.v1.layers.flatten(tmp_pool) flat_pool = tf.compat....
def vgg(x, is_training, num_classes, num_filters=32): input_layer = tf.expand_dims(x, 3) bn_input = tf.compat.v1.layers.batch_normalization(input_layer, training=is_training) conv1 = tf.compat.v1.layers.conv2d(inputs=bn_input, filters=num_filters, kernel_size=[3, 3], padding='same', activation=tf.nn.relu,...
def top_tags(file_name, model='MTT_musicnn', topN=3, input_length=3, input_overlap=False, print_tags=True, save_tags=False): " Predict the topN tags of the music-clip in file_name with the selected model.\n\n INPUT\n\n - file_name: path to the music file to tag.\n Data format: string.\n Example: './au...
def parse_args(): parser = argparse.ArgumentParser(description='Predict the topN tags of the music-clip in file_name with the selected model') parser.add_argument('file_name', type=str, help='audio file to process') parser.add_argument('-mod', '--model', metavar='', type=str, default='MTT_musicnn', help='...
class SubSectionTitleOrder(): "Sort example gallery by title of subsection.\n\n Assumes README.txt exists for all subsections and uses the subsection with\n dashes, '---', as the adornment.\n " def __init__(self, src_dir): self.src_dir = src_dir self.regex = re.compile('^([\\w ]+)\\n...
def gh_role(name, rawtext, text, lineno, inliner, options={}, content=[]): 'Link to a GitHub issue.' try: int(text) except ValueError: slug = text else: slug = ('issues/' + text) text = ('#' + text) ref = ('https://github.com/juaml/julearn/' + slug) set_classes(opti...
def setup(app): app.add_role('gh', gh_role) return
def pearson_scorer(y_true, y_pred): return scipy.stats.pearsonr(y_true.squeeze(), y_pred.squeeze())[0]
def change_column_type(column: str, new_type: str): 'Change the type of a column.\n\n Parameters\n ----------\n column : str\n The column to change the type of.\n new_type : str\n The new type of the column.\n\n Returns\n -------\n str\n The new column name with the type ...
def get_column_type(column): 'Get the type of a column.\n\n Parameters\n ----------\n column : str\n The column to get the type of.\n\n Returns\n -------\n str\n The type of the column.\n ' return column.split('__:type:__')[1]
def get_renamer(X_df): 'Get the dictionary that will rename the columns to add the type.\n\n Parameters\n ----------\n X_df : pd.DataFrame\n The dataframe to rename the columns of.\n\n Returns\n -------\n dict\n The dictionary that will rename the columns.\n\n ' return {x: (...
class make_type_selector(): 'Make a type selector.\n\n This type selector is to be used with\n :class:`sklearn.compose.ColumnTransformer`\n\n Parameters\n ----------\n pattern : str\n The pattern to select the columns.\n\n Returns\n -------\n function\n The type selector.\n\n...
class ColumnTypes(): 'Class to hold types in regards to a pd.DataFrame Column.\n\n Parameters\n ----------\n column_types : ColumnTypes or str or list of str or set of str\n One str representing on type if columns or a list of these.\n Instead of a str you can also provide a ColumnTypes its...
def ensure_column_types(attr: ColumnTypesLike) -> ColumnTypes: 'Ensure that the attribute is a ColumnTypes.\n\n Parameters\n ----------\n attr : ColumnTypes or str\n The attribute to check.\n\n Returns\n -------\n ColumnTypes\n The attribute as a ColumnTypes.\n ' return (Col...
def set_config(key: str, value: Any) -> None: 'Set a global config value.\n\n Parameters\n ----------\n key : str\n The key to set.\n value : Any\n The value to set.\n ' if (key not in _global_config): raise_error(f'Global config {key} does not exist') logger.info(f'Se...
def get_config(key: str) -> Any: 'Get a global config value.\n\n Parameters\n ----------\n key : str\n The key to get.\n\n Returns\n -------\n Any\n The value of the key.\n ' return _global_config.get(key, None)
class PipelineInspector(): def __init__(self, model): check_is_fitted(model) self._model = model def get_step_names(self): return list(self._model.named_steps.keys()) def get_step(self, name, as_estimator=False): step = self._model.named_steps[name] if (not as_es...
class _EstimatorInspector(): def __init__(self, estimator): self._estimator = estimator def get_params(self): return self._estimator.get_params() def get_fitted_params(self): all_params = vars(self._estimator) if isinstance(self._estimator, JuColumnTransformer): ...
def preprocess(pipeline: Pipeline, X: List[str], data: pd.DataFrame, until: Optional[str]=None, with_column_types: bool=False) -> pd.DataFrame: 'Preprocess data with a pipeline until a certain step (inclusive).\n\n Parameters\n ----------\n pipeline : Pipeline\n The pipeline to use.\n X : list ...
class Inspector(): 'Base class for inspector.\n\n Parameters\n ----------\n scores : pd.DataFrame\n The scores as dataframe.\n model : str, optional\n The model to inspect (default None).\n X : list of str, optional\n The features as list (default None).\n y : str, optional\...
def list_searchers() -> List[str]: 'List all available searching algorithms.\n\n Returns\n -------\n out : list(str)\n A list of all available searcher names.\n ' return list(_available_searchers)
def get_searcher(name: str) -> object: 'Get a searcher by name.\n\n Parameters\n ----------\n name : str\n The searchers name.\n\n Returns\n -------\n obj\n scikit-learn compatible searcher.\n\n Raises\n ------\n ValueError\n If the specified searcher is not availab...
def register_searcher(searcher_name: str, searcher: object, overwrite: Optional[bool]=None) -> None: 'Register searcher to julearn.\n\n This function allows you to add a scikit-learn compatible searching\n algorithm to julearn. After, you can call it as all other searchers in\n julearn.\n\n Parameters...
def reset_searcher_register() -> None: 'Reset the searcher register to its initial state.' global _available_searchers _available_searchers = deepcopy(_available_searchers_reset)
def _discretize_y(method: str, y: np.ndarray, n_bins: int) -> np.ndarray: discrete_y = None if (method == 'binning'): bins = np.histogram_bin_edges(y, bins=n_bins) elif (method == 'quantile'): bins = np.quantile(y, np.linspace(0, 1, (n_bins + 1))) else: raise_error(f'Unknown y ...