code
stringlengths
17
6.64M
def blocks_tags(obj): results = [] if isinstance(obj, PIL.Image.Image): results.append(pil_to_html(obj)) elif isinstance(obj, (str, int, float)): results.append('<div>') results.append(html_module.escape(str(obj))) results.append('</div>') elif isinstance(obj, IPython.d...
def pil_to_b64(img, format='png'): buffered = io.BytesIO() img.save(buffered, format=format) return base64.b64encode(buffered.getvalue()).decode('utf-8')
def pil_to_url(img, format='png'): return ('data:image/%s;base64,%s' % (format, pil_to_b64(img, format)))
def pil_to_html(img, margin=1): mattr = (' style="margin:%dpx"' % margin) return ('<img src="%s"%s>' % (pil_to_url(img), mattr))
def a(x, cols=None): global g_buffer if (g_buffer is None): g_buffer = [] g_buffer.append(x) if ((cols is not None) and (len(g_buffer) >= cols)): flush()
def reset(): global g_buffer g_buffer = []
def flush(*args, **kwargs): global g_buffer if (g_buffer is not None): x = g_buffer g_buffer = None display(blocks(x, *args, **kwargs))
def show(x=None, *args, **kwargs): flush(*args, **kwargs) if (x is not None): display(blocks(x, *args, **kwargs))
class CallableModule(types.ModuleType): def __init__(self): types.ModuleType.__init__(self, __name__) self.__dict__.update(sys.modules[__name__].__dict__) def __call__(self, x=None, *args, **kwargs): show(x, *args, **kwargs)
class LinePlotter(object): def __init__(self, writer, tag): self.writer = writer self.tag = tag def plot(self, x, data, walltime=None): if (not hasattr(self, 'plot_data')): self.plot_data = {'X': [], 'Y': []} self.plot_data['X'].append(x) self.plot_data['Y...
class ImageGridPlotter(object): def __init__(self, writer, ncols, grid=False): self.ncols = ncols self.writer = writer self.grid = grid def plot(self, visuals, niter=0): ncols = self.ncols ncols = min(ncols, len(visuals)) if self.grid: images = [] ...
def remove_prefix(s, prefix): if s.startswith(prefix): s = s[len(prefix):] return s
def get_subset_dict(in_dict, keys): if len(keys): subset = OrderedDict() for key in keys: subset[key] = in_dict[key] else: subset = in_dict return subset
def datestring(): return time.strftime('%Y-%m-%d %H:%M:%S')
def format_str_one(v, float_prec=6, int_pad=1): if (isinstance(v, torch.Tensor) and (v.numel() == 1)): v = v.item() if isinstance(v, float): return (('{:.' + str(float_prec)) + 'f}').format(v) if (isinstance(v, int) and int_pad): return (('{:0' + str(int_pad)) + 'd}').format(v) ...
def format_str(*args, format_opts={}, **kwargs): ss = [format_str_one(arg, **format_opts) for arg in args] for (k, v) in kwargs.items(): ss.append('{}: {}'.format(k, format_str_one(v, **format_opts))) return '\t'.join(ss)
def complete_device(device): if (not torch.cuda.is_available()): return torch.device('cpu') if (type(device) == str): device = torch.device(device) if ((device.type == 'cuda') and (device.index is None)): return torch.device(device.type, torch.cuda.current_device()) return devi...
def check_timestamp(checkpoint_path, timestamp_path): " returns True if checkpoint_path timestamp is different\n from timestamp path or timestamp_path doesn't exist" if (not os.path.isfile(timestamp_path)): print('No timestamp found') return True newtime = os.path.getmtime(checkpoin...
def update_timestamp(checkpoint_path, timestamp_path): ' write the last modified date of checkpoint_path to the\n the file timestamp_path ' newtime = os.path.getmtime(checkpoint_path) newtime = datetime.fromtimestamp(newtime).strftime('%Y-%m-%d %H:%M:%S') with open(timestamp_path, 'w') as f: ...
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val...
class Visualizer(): def __init__(self, opt, loss_names, visual_names=None): from . import tensorboard_utils as tb_utils self.name = opt.name self.opt = opt self.visual_names = visual_names tb_path = os.path.join('runs', self.name) if os.path.isdir(tb_path): ...
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 EmbedWord2Vec(walks, dimension): time_start = time.time() print('Creating embeddings.') model = Word2Vec(walks, size=dimension, window=5, min_count=0, sg=1, workers=32, iter=1) node_ids = model.wv.index2word node_embeddings = model.wv.vectors print('Embedding generation runtime: ', (time.t...
def EmbedPoincare(relations, epochs, dimension): model = PoincareModel(relations, size=dimension, workers=32) model.train(epochs) node_ids = model.index2entity node_embeddings = model.vectors return (node_ids, node_embeddings)
def TraverseAndSelect(length, num_walks, hyperedges, vertexMemberships, alpha=1.0, beta=0): walksTAS = [] for hyperedge_index in hyperedges: hyperedge = hyperedges[hyperedge_index] walk_hyperedge = [] for _ in range(num_walks): curr_vertex = random.choice(hyperedge['members...
def SubsampleAndTraverse(length, num_walks, hyperedges, vertexMemberships, alpha=1.0, beta=0): walksSAT = [] for hyperedge_index in hyperedges: hyperedge = hyperedges[hyperedge_index] walk_vertex = [] curr_vertex = random.choice(hyperedge['members']) for _ in range(num_walks): ...
def getFeaturesTrainingData(): i = 0 lists = [] labels = [] for vertex in G.nodes: vertex_embedding_list = [] lists.append({'f': vertex_features[vertex].tolist()}) labels.append(vertex_labels[vertex]) X_unshuffled = [] for hlist in lists: x = np.zeros((feature_d...
def getTrainingData(): i = 0 lists = [] labels = [] for h in hyperedges: vertex_embedding_list = [] hyperedge = hyperedges[h] for vertex in hyperedge['members']: i += 1 if ((i % 100000) == 0): print(i) try: ver...
def getMLPTrainingData(): i = 0 lists = [] labels = [] maxi = 0 for h in hyperedges: vertex_embedding_list = [] hyperedge = hyperedges[h] lists.append({'h': hyperedge_embeddings[hyperedge_ids.index(h)].tolist(), 'f': vertex_features[h].tolist()}) label = np.zeros((n...
def getDSTrainingData(): i = 0 lists = [] labels = [] maxi = 0 for h in hyperedges: vertex_embedding_list = [] hyperedge = hyperedges[h] for vertex in hyperedge['members']: i += 1 if ((i % 100000) == 0): print(i) try: ...
def hyperedgesTrain(X_train, Y_train, num_epochs): deephyperedges_transductive_model.load_weights((('models/' + dataset_name) + '/deephyperedges_transductive_model.h5')) history = deephyperedges_transductive_model.fit(X_train, Y_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_split=0...
def MLPTrain(X_MLP_transductive_train, Y_MLP_transductive_train, num_epochs): MLP_transductive_model.load_weights((('models/' + dataset_name) + '/MLP_transductive_model.h5')) history = MLP_transductive_model.fit(X_MLP_transductive_train, Y_MLP_transductive_train, epochs=num_epochs, batch_size=batch_size, shuf...
def DeepSetsTrain(X_deepset_transductive_train, Y_deepset_transductive_train, num_epochs): deepsets_transductive_model.load_weights((('models/' + dataset_name) + '/deepsets_transductive_model.h5')) history = deepsets_transductive_model.fit(X_deepset_transductive_train, Y_deepset_transductive_train, epochs=num...
def testModel(model, X_tst, Y_tst): from sklearn.metrics import classification_report, accuracy_score target_names = ['Neural Networks', 'Case Based', 'Reinforcement Learning', 'Probabilistic Methods', 'Genetic Algorithms', 'Rule Learning', 'Theory'] y_pred = model.predict(X_tst, batch_size=16, verbose=0)...
def RunAllTests(percentTraining, num_times, num_epochs): for i in range(num_times): print('percent: ', percentTraining, ', iteration: ', (i + 1), ', model: deep hyperedges') (X, Y) = getTrainingData() (X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, train_size=percentTraining, t...
def getFeaturesTrainingData(): i = 0 lists = [] labels = [] for vertex in G.nodes: vertex_embedding_list = [] lists.append({'f': vertex_features[vertex].tolist()}) labels.append(vertex_labels[vertex]) X_unshuffled = [] for hlist in lists: x = np.zeros((feature_d...
def getTrainingData(): i = 0 lists = [] labels = [] for h in hyperedges: vertex_embedding_list = [] hyperedge = hyperedges[h] for vertex in hyperedge['members']: i += 1 if ((i % 100000) == 0): print(i) try: ver...
def getMLPTrainingData(): i = 0 lists = [] labels = [] maxi = 0 for h in hyperedges: vertex_embedding_list = [] hyperedge = hyperedges[h] lists.append({'h': hyperedge_embeddings[hyperedge_ids.index(h)].tolist(), 'f': vertex_features[h].tolist()}) label = np.zeros((n...
def getDSTrainingData(): i = 0 lists = [] labels = [] maxi = 0 for h in hyperedges: vertex_embedding_list = [] hyperedge = hyperedges[h] for vertex in hyperedge['members']: i += 1 if ((i % 100000) == 0): print(i) try: ...
def hyperedgesTrain(X_train, Y_train): deephyperedges_transductive_model.load_weights((('models/' + dataset_name) + '/deephyperedges_transductive_model.h5')) history = deephyperedges_transductive_model.fit(X_train, Y_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, validation_split=0, verbose=0)...
def MLPTrain(X_MLP_transductive_train, Y_MLP_transductive_train): MLP_transductive_model.load_weights((('models/' + dataset_name) + '/MLP_transductive_model.h5')) history = MLP_transductive_model.fit(X_MLP_transductive_train, Y_MLP_transductive_train, epochs=num_epochs, batch_size=batch_size, shuffle=True, va...
def DeepSetsTrain(X_deepset_transductive_train, Y_deepset_transductive_train): deepsets_transductive_model.load_weights((('models/' + dataset_name) + '/deepsets_transductive_model.h5')) history = deepsets_transductive_model.fit(X_deepset_transductive_train, Y_deepset_transductive_train, epochs=num_epochs, bat...
def testModel(model, X_tst, Y_tst): from sklearn.metrics import classification_report, accuracy_score target_names = target_names = ['Type-1 Diabetes', 'Type-2 Diabetes', 'Type-3 Diabetes'] y_pred = model.predict(X_tst, batch_size=16, verbose=0) finals_pred = [] finals_test = [] for p in y_pre...
def RunAllTests(percentTraining, num_times=10): for i in range(num_times): print('percent: ', percentTraining, ', iteration: ', (i + 1), ', model: deep hyperedges') (X, Y) = getTrainingData() (X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, train_size=percentTraining, test_size=...
def smooth(scalars, weight): last = scalars[0] smoothed = list() for point in scalars: smoothed_val = ((last * weight) + ((1 - weight) * point)) smoothed.append(smoothed_val) last = smoothed_val return smoothed
def plot(deephyperedges_directory, MLP_directory, deepsets_directory, metric, dataset): dhe_metrics = pd.read_csv(deephyperedges_directory) x = [] y = [] for (index, row) in dhe_metrics.iterrows(): x.append(float(row['Step'])) y.append(float(row['Value'])) mlp_metrics = pd.read_csv...
def plotAll(dataset): metric = 'run-.-tag-categorical_accuracy.csv' deephyperedges_directory = ((('images/paper/' + dataset) + '/deephyperedges/') + metric) MLP_directory = ((('images/paper/' + dataset) + '/MLP/') + metric) deepsets_directory = ((('images/paper/' + dataset) + '/deepsets/') + metric) ...
@register_line_cell_magic def writetemplate(line, cell): with open(line, 'w') as f: f.write(cell.format(**globals()))
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 ...
class ContinuousStratifiedKFold(StratifiedKFold): 'Stratified K-Fold cross validator for regression problems.\n\n Stratification is done based on the discretization of the target variable\n into a fixed number of bins/quantiles.\n\n Parameters\n ----------\n n_bins : int\n Number of bins/qua...
class RepeatedContinuousStratifiedKFold(_RepeatedSplits): 'Repeated Contionous Stratified K-Fold cross validator.\n\n Repeats :class:`julearn.model_selection.ContinuousStratifiedKFold`\n n times with different randomization in each repetition.\n\n Parameters\n ----------\n n_bins : int\n Num...
class ContinuousStratifiedGroupKFold(StratifiedGroupKFold): 'Stratified Group K-Fold cross validator for regression problems.\n\n Stratified Group K-Fold, where stratification is done based on the\n discretization of the target variable into a fixed number of\n bins/quantiles.\n\n Parameters\n ----...