code
stringlengths
17
6.64M
def _pil_interp(method): if (method == 'bicubic'): return Image.BICUBIC elif (method == 'lanczos'): return Image.LANCZOS elif (method == 'hamming'): return Image.HAMMING else: return Image.BILINEAR
class RandomResizedCropAndInterpolationWithTwoPic(): 'Crop the given PIL Image to random size and aspect ratio with random interpolation.\n\n A crop of random size (default: of 0.08 to 1.0) of the original size and a random\n aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This c...
def convert_to_list(y_aspect, y_sentiment, mask): y_aspect_list = [] y_sentiment_list = [] for (seq_aspect, seq_sentiment, seq_mask) in zip(y_aspect, y_sentiment, mask): l_a = [] l_s = [] for (label_dist_a, label_dist_s, m) in zip(seq_aspect, seq_sentiment, seq_mask): i...
def score(true_aspect, predict_aspect, true_sentiment, predict_sentiment, train_op): if train_op: begin = 3 inside = 4 else: begin = 1 inside = 2 pred_count = {'pos': 0, 'neg': 0, 'neu': 0} rel_count = {'pos': 0, 'neg': 0, 'neu': 0} correct_count = {'pos...
def get_metric(y_true_aspect, y_predict_aspect, y_true_sentiment, y_predict_sentiment, mask, train_op): (f_a, f_o) = (0, 0) (true_aspect, true_sentiment) = convert_to_list(y_true_aspect, y_true_sentiment, mask) (predict_aspect, predict_sentiment) = convert_to_list(y_predict_aspect, y_predict_sentiment, ma...
def get_optimizer(args): clipvalue = 0 clipnorm = 10 if (args.algorithm == 'rmsprop'): optimizer = opt.RMSprop(lr=0.0001, rho=0.9, epsilon=1e-06, clipnorm=clipnorm, clipvalue=clipvalue) elif (args.algorithm == 'sgd'): optimizer = opt.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False...
def child_model_params(num_features, num_layers, max_units): c = (((num_features * num_layers) * max_units) + (((max_units * num_layers) ** 2) / 2)) return c
def controller_search_space(input_blocks, output_blocks, num_layers, num_choices_per_layer): s = (np.log10(num_choices_per_layer) * num_layers) s += (((np.log10(2) * (num_layers - 1)) * num_layers) / 2) s += ((np.log10(input_blocks) * num_layers) + (np.log10(output_blocks) * num_layers)) return s
def unpack_data(data, unroll_generator_x=False, unroll_generator_y=False, callable_kwargs=None): is_generator = False unroll_generator = (unroll_generator_x or unroll_generator_y) if (type(data) in (tuple, list)): (x, y) = (data[0], data[1]) elif isinstance(data, tf.keras.utils.Sequence): ...
def batchify(x, y=None, batch_size=None, shuffle=True, drop_remainder=True): if (not (type(x) is list)): x = [x] if ((y is not None) and (type(y) is not list)): y = [y] n = len(x[0]) idx = np.arange(n) if (batch_size is None): batch_size = n if shuffle: idx = np...
def batchify_infer(x, y=None, batch_size=None, shuffle=True, drop_remainder=True): if (not (type(x) is list)): x = [x] if ((y is not None) and (type(y) is not list)): y = [y] n = len(x[0]) idx = np.arange(n) if (batch_size is None): batch_size = n if shuffle: id...
def numpy_shuffle_in_unison(List): rng_state = np.random.get_state() for x in List: np.random.set_state(rng_state) np.random.shuffle(x)
def get_tf_loss(loss, y_true, y_pred): loss = loss.lower() if ((loss == 'mse') or (loss == 'mean_squared_error')): loss_ = tf.reduce_mean(tf.square((y_true - y_pred))) elif (loss == 'categorical_crossentropy'): loss_ = tf.reduce_mean(tf.keras.losses.categorical_crossentropy(y_true, y_pred)...
def get_tf_metrics(m): if callable(m): return m elif (m.lower() == 'mae'): return tf.keras.metrics.MAE elif (m.lower() == 'mse'): return tf.keras.metrics.MSE elif (m.lower() == 'acc'): def acc(y_true, y_pred): return tf.reduce_mean(y_true) return ac...
def get_tf_layer(fn_str): fn_str = fn_str.lower() if (fn_str == 'relu'): return tf.nn.relu elif (fn_str == 'linear'): return (lambda x: x) elif (fn_str == 'softmax'): return tf.nn.softmax elif (fn_str == 'sigmoid'): return tf.nn.sigmoid elif (fn_str == 'leaky_re...
def create_weight(name, shape, initializer=None, trainable=True, seed=None): if (initializer is None): try: initializer = tf.contrib.keras.initializers.he_normal(seed=seed) except AttributeError: initializer = tf.keras.initializers.he_normal(seed=seed) return tf.get_var...
def create_bias(name, shape, initializer=None): if (initializer is None): initializer = tf.constant_initializer(0.0, dtype=tf.float32) return tf.get_variable(name, shape, initializer=initializer)
def batch_norm1d(x, is_training, name='bn', decay=0.9, epsilon=1e-05, data_format='NWC'): if (data_format == 'NWC'): shape = [x.get_shape()[(- 1)]] x = tf.expand_dims(x, axis=1) sq_dim = 1 elif (data_format == 'NCW'): shape = [x.get_shape()[1]] x = tf.expand_dims(x, axi...
def get_keras_train_ops(loss, tf_variables, optim_algo, **kwargs): assert (K.backend() == 'tensorflow') from keras.optimizers import get as get_opt opt = get_opt(optim_algo) grads = tf.gradients(loss, tf_variables) grad_var = [] no_grad_var = [] for (g, v) in zip(grads, tf_variables): ...
def count_model_params(tf_variables): num_vars = 0 for var in tf_variables: num_vars += np.prod([dim.value for dim in var.get_shape()]) return num_vars
def proximal_policy_optimization_loss(curr_prediction, curr_onehot, old_prediction, old_onehotpred, rewards, advantage, clip_val, beta=None): rewards_ = tf.squeeze(rewards, axis=1) advantage_ = tf.squeeze(advantage, axis=1) entropy = 0 r = 1 for (t, (p, onehot, old_p, old_onehot)) in enumerate(zip...
def get_kl_divergence_n_entropy(curr_prediction, curr_onehot, old_prediction, old_onehotpred): 'compute approx\n return kl, ent\n ' kl = [] ent = [] for (t, (p, onehot, old_p, old_onehot)) in enumerate(zip(curr_prediction, curr_onehot, old_prediction, old_onehotpred)): kl.append(tf.resha...
def lstm(x, prev_c, prev_h, w): ifog = tf.matmul(tf.concat([x, prev_h], axis=1), w) (i, f, o, g) = tf.split(ifog, 4, axis=1) i = tf.sigmoid(i) f = tf.sigmoid(f) o = tf.sigmoid(o) g = tf.tanh(g) next_c = ((i * g) + (f * prev_c)) next_h = (o * tf.tanh(next_c)) return (next_c, next_h)...
def stack_lstm(x, prev_c, prev_h, w): (next_c, next_h) = ([], []) for (layer_id, (_c, _h, _w)) in enumerate(zip(prev_c, prev_h, w)): inputs = (x if (layer_id == 0) else next_h[(- 1)]) (curr_c, curr_h) = lstm(inputs, _c, _h, _w) next_c.append(curr_c) next_h.append(curr_h) re...
class BaseNetworkManager(): def __init__(self, *args, **kwargs): pass def get_rewards(self, trial, model_arc): raise NotImplementedError('Abstract method.')
class GeneralManager(BaseNetworkManager): "Manager creates child networks, train them on a dataset, and retrieve rewards.\n\n Parameters\n ----------\n train_data : tuple, string or generator\n Training data to be fed to ``keras.models.Model.fit``.\n\n validation_data : tuple, string, or genera...
class DistributedGeneralManager(GeneralManager): 'Distributed manager will place all tensors of any child models to a pre-assigned GPU device\n ' def __init__(self, devices, train_data_kwargs, validate_data_kwargs, do_resample=False, *args, **kwargs): self.devices = devices super().__init_...
class EnasManager(GeneralManager): "A specialized manager for Efficient Neural Architecture Search (ENAS).\n\n Because\n\n Parameters\n ----------\n session : tensorflow.Session or None\n The tensorflow session that the manager will be parsed to modelers. By default it's None, which will then g...
def get_layer_shortname(layer): 'Get the short name for a computational operation of a layer, useful in converting a Layer object to a string as\n ID or when plotting\n\n Parameters\n ----------\n layer : amber.architect.Operation\n The ``Operation`` object for any layer.\n\n Returns\n --...
class State(object): 'The Amber internal holder for a computational operation at any layer\n\n Parameters\n ----------\n Layer_type : str\n The string for the operation type; supports most commonly used ``tf.keras.layers`` types\n\n kwargs :\n Operation/layer specifications are parsed th...
class ModelSpace(): 'Model Space constructor\n\n Provides utility functions for holding "states" / "operations" that the controller must use to train and predict.\n Also provides a more convenient way to define the model search space\n\n There are several ways to construct a model space. For example, one...
class BranchedModelSpace(ModelSpace): '\n Parameters\n ----------\n subspaces : list\n A list of `ModelSpace`. First element is a list of input branches. Second element is a stem model space\n concat_op : str\n string identifier for how to concatenate different input branches\n\n ' ...
class MultiInputController(GeneralController): "\n DOCSTRING\n\n Parameters\n ----------\n model_space:\n with_skip_connection:\n with_input_blocks:\n share_embedding: dict\n a Dictionary defining which child-net layers will share the softmax and\n embedding weights during Contr...
class MultiIOController(MultiInputController): '\n Example\n ----------\n >>> from BioNAS.MockBlackBox.dense_skipcon_space import get_model_space\n >>> from BioNAS.Controller.multiio_controller import MultiIOController\n >>> import numpy as np\n >>> model_space = get_model_space(5)\n >>> cont...
def get_store_fn(arg): 'The getter function that returns a callable store function from a string\n\n Parameters\n ----------\n arg : str\n The string identifier for a particular store function. Current choices are:\n - general\n - model_plot\n - minimal\n\n Returns\n ---...
def store_with_model_plot(trial, model, hist, data, pred, loss_and_metrics, working_dir='.', save_full_model=False, *args, **kwargs): par_dir = os.path.join(working_dir, 'weights', ('trial_%s' % trial)) os.makedirs(par_dir, exist_ok=True) store_general(trial=trial, model=model, hist=hist, data=data, pred=...
def store_with_hessian(trial, model, hist, data, pred, loss_and_metrics, working_dir='.', save_full_model=False, knowledge_func=None): assert (knowledge_func is not None), '`store_with_hessian` requires parsing theknowledge function used.' par_dir = os.path.join(working_dir, 'weights', ('trial_%s' % trial)) ...
def store_general(trial, model, hist, data, pred, loss_and_metrics, working_dir='.', save_full_model=False, *args, **kwargs): par_dir = os.path.join(working_dir, 'weights', ('trial_%s' % trial)) if os.path.isdir(par_dir): shutil.rmtree(par_dir) os.makedirs(par_dir) if save_full_model: ...
def store_minimal(trial, model, working_dir='.', save_full_model=False, **kwargs): par_dir = os.path.join(working_dir, 'weights', ('trial_%s' % trial)) if os.path.isdir(par_dir): shutil.rmtree(par_dir) os.makedirs(par_dir) if save_full_model: model.save(os.path.join(working_dir, 'weigh...
def write_pred_to_disk(fn, y_pred, y_obs, metadata=None, metrics=None): with open(fn, 'w') as f: if (metrics is not None): f.write(('\n'.join(['# {}: {}'.format(x, metrics[x]) for x in metrics]) + '\n')) if (type(y_pred) is list): y_pred = np.concatenate(y_pred, axis=1) ...
def get_controller_states(model): return [K.get_value(s) for (s, _) in model.state_updates]
def set_controller_states(model, states): for ((d, _), s) in zip(model.state_updates, states): K.set_value(d, s)
def get_controller_history(fn='train_history.csv'): with open(fn, 'r') as f: csvreader = csv.reader(f) for row in csvreader: trial = row[0] return int(trial)
def compute_entropy(prob_states): ent = 0 for prob in prob_states: for p in prob: p = np.array(p).flatten() i = np.where((p > 0))[0] t = np.sum(((- p[i]) * np.log2(p[i]))) ent += t return ent
class ControllerTrainEnvironment(): 'The training evnrionment employs ``controller`` model and ``manager`` to mange data and reward,\n creates a reinforcement learning environment\n\n Parameters\n ----------\n controller : amber.architect.BaseController\n The controller to search architectures ...
class EnasTrainEnv(ControllerTrainEnvironment): '\n Params:\n time_budget: defaults to 72 hours\n ' def __init__(self, *args, **kwargs): self.time_budget = kwargs.pop('time_budget', '72:00:00') self.child_train_steps = kwargs.pop('child_train_steps', None) self.child_warm...
class MultiManagerEnvironment(EnasTrainEnv): '\n MultiManagerEnvironment is an environment that allows one controller to interact with multiple EnasManagers\n ' def __init__(self, data_descriptive_features, is_enas='auto', *args, **kwargs): super(MultiManagerEnvironment, self).__init__(*args, *...
class ParallelMultiManagerEnvironment(MultiManagerEnvironment): def __init__(self, processes=2, enable_manager_sampling=False, *args, **kwargs): super().__init__(*args, **kwargs) self.processes = processes self.enable_manager_sampling = enable_manager_sampling self._gpus = get_ava...
def get_model_space(num_layers): state_space = ModelSpace() for i in range(num_layers): state_space.add_layer(i, [State('Dense', units=5, activation='relu'), State('Dense', units=5, activation='tanh')]) return state_space
def get_input_nodes(num_inputs, with_input_blocks): input_state = [] if with_input_blocks: for node in range(num_inputs): units = 1 name = ('X%i' % node) node_op = State('input', shape=(units,), name=name) input_state.append(node_op) else: in...
def get_output_nodes(): output_op = State('Dense', units=1, activation='linear', name='output') return output_op
def get_data(with_input_blocks): np.random.seed(111) n = 5000 p = 4 beta_a = np.array([0, 0, 0, 0]).astype('float32') beta_i = np.array(((([0, 3, 0, 0] + ([0] * 3)) + [0, (- 2)]) + [0])).astype('float32') simulator = HigherOrderSimulator(n=n, p=p, noise_var=0.1, x_var=1.0, degree=2, discretize...
def get_data_correlated(with_input_blocks, corr_coef=0.6): np.random.seed(111) n = 5000 p = 4 beta_a = np.array([0, 0, 0, 0]).astype('float32') beta_i = np.array(((([0, 3, 0, 0] + ([0] * 3)) + [0, (- 2)]) + [0])).astype('float32') cov_mat = (np.eye(4) * 1.0) cov_mat[(0, 2)] = cov_mat[(2, 0...
def get_knowledge_fn(): gkf = GraphKnowledgeHessFunc(total_feature_num=4) adjacency = np.zeros((4, 4)) adjacency[(0, 1)] = adjacency[(1, 0)] = 3.0 adjacency[(2, 3)] = adjacency[(3, 2)] = (- 2.0) (intr_idx, intr_eff) = gkf.convert_adjacency_to_knowledge(adjacency) gkf.knowledge_encoder(intr_idx...
def get_reward_fn(gkf, Lambda=1.0): reward_fn = KnowledgeReward(gkf, Lambda=Lambda) return reward_fn
def get_manager(train_data, validation_data, model_fn, reward_fn, wd='./tmp'): model_compile_dict = {'loss': 'mse', 'optimizer': 'adam', 'metrics': ['mae']} manager = GeneralManager(train_data, validation_data, working_dir=wd, model_fn=model_fn, reward_fn=reward_fn, post_processing_fn=store_with_hessian, mode...
def get_model_fn(model_space, inputs_op, output_op, num_layers, with_skip_connection, with_input_blocks): model_compile_dict = {'loss': 'mse', 'optimizer': 'adam', 'metrics': ['mae']} model_fn = DAGModelBuilder(inputs_op, output_op, num_layers, model_space, model_compile_dict, with_skip_connection, with_input...
def ID2arch(hist_df, state_str_to_state_shortname): id2arch = {} num_layers = sum([1 for x in hist_df.columns.values if x.startswith('L')]) for i in hist_df.ID: arch = tuple((state_str_to_state_shortname[x][hist_df.loc[(hist_df.ID == i)][('L%i' % (x + 1))].iloc[0]] for x in range(num_layers))) ...
def get_gold_standard(history_fn_list, state_space, metric_name_dict={'acc': 0, 'knowledge': 1, 'loss': 2}, id_remainder=None): state_str_to_state_shortname = {} for i in range(len(state_space)): state_str_to_state_shortname[i] = {str(x): get_layer_shortname(x) for x in state_space[i]} df = read_h...
def get_gold_standard_arc_seq(history_fn_list, model_space, metric_name_dict, with_skip_connection, with_input_blocks, num_input_blocks): model_gen = get_model_space_generator(model_space, with_skip_connection=with_skip_connection, with_input_blocks=with_input_blocks, num_input_blocks=num_input_blocks) df = r...
def get_model_space_generator(model_space, with_skip_connection, with_input_blocks, num_input_blocks=1): new_space = [] num_layers = len(model_space) for layer_id in range(num_layers): new_space.append([x for x in range(len(model_space[layer_id]))]) if with_skip_connection: for...
def combine_input_blocks(num_layers, num_input_blocks): 'return all combinations of input_blocks when `input_block_unique_connection=True`\n ' cmb_arr = np.zeros(((num_layers ** num_input_blocks), num_layers, num_input_blocks), dtype='int32') cmb_list = [list(range(num_layers)) for _ in range(num_input...
def train_hist_csv_writter(writer, trial, loss_and_metrics, reward, model_states): data = [trial, [loss_and_metrics[x] for x in sorted(loss_and_metrics.keys())], reward] action_list = [str(x) for x in model_states] data.extend(action_list) writer.writerow(data) print(action_list)
def rewrite_train_hist(working_dir, model_fn, knowledge_fn, data, suffix='new', metric_name_dict={'acc': 0, 'knowledge': 1, 'loss': 2}): import tensorflow as tf from ..utils.io import read_history old_df = read_history([os.path.join(working_dir, 'train_history.csv')], metric_name_dict) new_fh = open(o...
def grid_search(model_space_generator, manager, working_dir, B=10, resume_prev_run=True): write_mode = ('a' if resume_prev_run else 'w') fh = open(os.path.join(working_dir, 'train_history.csv'), write_mode) writer = csv.writer(fh) i = 0 for b in range(B): if getattr(model_space_generator, ...
def get_mock_reward(model_states, train_history_df, metric, stringify_states=True): if stringify_states: model_states_ = [str(x) for x in model_states] else: model_states_ = model_states idx_bool = np.array([(train_history_df[('L%i' % (i + 1))] == model_states_[i]) for i in range(len(model...
def get_default_mock_reward_fn(model_states, train_history_df, lbd=1.0, metric=['loss', 'knowledge', 'acc']): Lambda = lbd mock_reward = get_mock_reward(model_states, train_history_df, metric) this_reward = (- (mock_reward['loss'] + (Lambda * mock_reward['knowledge']))) loss_and_metrics = [mock_reward...
def get_mock_reward_fn(train_history_df, metric, stringify_states, lbd=1.0): def reward_fn(model_states, *args, **kwargs): mock_reward = get_mock_reward(model_states, train_history_df, metric, stringify_states) this_reward = (- (mock_reward['loss'] + (lbd * mock_reward['knowledge']))) los...
class MockManager(GeneralManager): 'Helper class for bootstrapping a random reward for any given architecture from a set of history records' def __init__(self, history_fn_list, model_compile_dict, train_data=None, validation_data=None, input_state=None, output_state=None, model_fn=None, reward_fn=None, post_...
def get_state_space(): 'State_space is the place we define all possible operations (called `States`) on each layer to stack a neural net.\n The state_space is defined in a layer-by-layer manner, i.e. first define the first layer (layer 0), then layer 1,\n so on and so forth. See below for how to define all ...
def get_data(): 'Test function for reading data from a set of FASTA sequences. Read Positive and Negative FASTA files, and\n convert to 4 x N matrices.\n ' pos_file = resource_filename('amber.resources', 'simdata/DensityEmbedding_motifs-MYC_known1_min-1_max-1_mean-1_zeroProb-0p0_seqLength-200_numSeqs-10...
class DataToParse(): def __init__(self, path, method=None): self.path = path self.method = method self._extension() def _extension(self): ext = os.path.splitext(self.path)[1] if (ext in ('.pkl', '.pickle')): self.method = 'pickle' elif (ext in ('.n...
def load_data_dict(d): for (k, v) in d.items(): if (type(v) is DataToParse): d[k] = v.unpack() elif (type(v) is str): assert os.path.isfile(v), ('cannot find file: %s' % v) d[k] = DataToParse(v).unpack() return d
def get_train_env(env_type, controller, manager, *args, **kwargs): if (env_type == 'ControllerTrainEnv'): from .architect.trainEnv import ControllerTrainEnvironment env = ControllerTrainEnvironment(*args, controller=controller, manager=manager, **kwargs) elif (env_type == 'EnasTrainEnv'): ...
def get_controller(controller_type, model_space, session, **kwargs): if ((controller_type == 'General') or (controller_type == 'GeneralController')): from .architect import GeneralController controller = GeneralController(model_space=model_space, session=session, **kwargs) elif ((controller_ty...
def get_model_space(arg): from .architect.modelSpace import ModelSpace if (type(arg) is str): if (arg == 'Default ANN'): from .bootstrap.dense_skipcon_space import get_model_space as ms_ann model_space = ms_ann(3) elif (arg == 'Default 1D-CNN'): from .bootst...
def get_manager(manager_type, model_fn, reward_fn, data_dict, session, *args, **kwargs): data_dict = load_data_dict(data_dict) if ((manager_type == 'General') or (manager_type == 'GeneralManager')): from .architect.manager import GeneralManager manager = GeneralManager(*args, model_fn=model_fn...
def get_modeler(model_fn_type, model_space, session, *args, **kwargs): from .architect.modelSpace import State if ((model_fn_type == 'DAG') or (model_fn_type == 'DAGModelBuilder')): from .modeler import DAGModelBuilder assert (('inputs_op' in kwargs) and ('outputs_op' in kwargs)) inp_o...
def get_reward_fn(reward_fn_type, knowledge_fn, *args, **kwargs): if (reward_fn_type == 'KnowledgeReward'): from .architect.reward import KnowledgeReward reward_fn = KnowledgeReward(knowledge_fn, *args, **kwargs) elif (reward_fn_type == 'LossReward'): from .architect.reward import Loss...
def get_knowledge_fn(knowledge_fn_type, knowledge_data_dict, *args, **kwargs): if (knowledge_data_dict is not None): knowledge_data_dict = load_data_dict(knowledge_data_dict) if ((knowledge_fn_type == 'ght') or (knowledge_fn_type == 'GraphHierarchyTree')): from .objective import GraphHierarchy...
def get_model_and_io_nodes(model_space_arg): import json import ast def eval_shape(d_): for j in range(len(d_)): if (('shape' in d_[j]) and (type(d_[j]['shape']) is str)): d_[j]['shape'] = ast.literal_eval(d_[j]['shape']) return d_ if os.path.isfile(model_s...
def gui_mapper(var_dict): wd = var_dict['wd'] train_data = DataToParse(var_dict['train_data']) val_data = DataToParse(var_dict['validation_data']) (model_space, input_states, output_state) = get_model_and_io_nodes(var_dict['model_space']) model_compile_dict = {'optimizer': var_dict['optimizer'], '...
def load_images(wd, frame): global images_, captions_ pngs = sorted([x for x in os.listdir(wd) if x.endswith('png')]) images_ = [os.path.join(wd, x) for x in pngs] captions_ = [x.split('.')[0] for x in pngs] if (len(pngs) == 0): messagebox.showinfo('Warning', 'Load failed. No figures found...
def move(delta, frame): global current, images_, images_type_indices gallery_type = frame.gallery_showtype.get() if (not (0 <= (current + delta) < len(images_type_indices[gallery_type]))): if (len(images_type_indices[gallery_type]) == 0): frame.gallery_showtype.set(GALLERY_SHOW_TYPES[0...
class EvaluateTab(tk.Frame): def __init__(self, parent, controller, global_wd, global_thread_spawner=None, prev_=None, next_=None): tk.Frame.__init__(self, master=parent, bg=BODY_COLOR) self.global_wd = global_wd self.global_thread_spawner = global_thread_spawner self._create_head...
def parse_layout(master): frames = [] var_dict = {} for tab_name in PARAMS_LAYOUT: f = tk.Frame(master=master, bg=BODY_COLOR) f.grid_columnconfigure([0, 1, 2, 3], minsize=100) for (k, v) in PARAMS_LAYOUT[tab_name].items(): try: (str_var, widget, btn_var)...
def pretty_print_dict(d): print(('-' * 80)) for (k, v) in d.items(): print(k, ' = ', v)
class InitializeTab(tk.Frame): def __init__(self, parent, controller, global_wd, global_thread_spawner=None, prev_=None, next_=None): tk.Frame.__init__(self, parent, bg=BODY_COLOR) self.global_wd = global_wd self.var_dict = {'wd': (global_wd, 0)} self.animation_register = [] ...
class AmberApp(tk.Tk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.geometry('800x600+500+100') self.resizable(0, 0) self.style = ttk.Style() self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.glob...
class TabController(tk.Frame): def __init__(self, master, global_wd, global_thread_spawner, *args, **kwargs): super().__init__(*args, master=master, **kwargs) self.global_wd = global_wd self.global_thread_spawner = global_thread_spawner container = tk.Frame(master=self, width=800,...
def beautify_status_update(tab): var_dict = tab.var_dict def colorify(p, widget=None): if (p is None): color = 'grey' elif (p < 30): color = 'green' elif (30 <= p < 70): color = 'orange' elif (70 <= p < 100): color = 'red' ...
class TrainTab(tk.Frame): def __init__(self, parent, controller, global_wd, global_thread_spawner=None, prev_=None, next_=None): tk.Frame.__init__(self, master=parent, bg=BODY_COLOR) self.global_wd = global_wd self.global_thread_spawner = global_thread_spawner self.init_page = Non...
class welcome_page(tk.Toplevel): def __init__(self, master, global_wd, *args, **kwargs): super().__init__(master=master) self.geometry('600x400+500+100') self.title('BioNAS - Welcome') self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self....
class LabelSeparator(tk.Frame): def __init__(self, parent, text='', width='', *args): tk.Frame.__init__(self, parent, *args, bg=BODY_COLOR) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.separator = ttk.Separator(self, orient=tk.HORIZONTAL) ...
def create_widget(arg, master): if ((type(arg) is list) and (len(arg) > 0)): str_var = tk.StringVar(master) str_var.set(arg[0]) btn_var = tk.StringVar(master) btn_var.set(arg[0]) def set_fp(x): if (btn_var.get() == 'Custom..'): fp = filedialog.a...
def load_full_model(modelPath): model = load_model(modelPath, custom_objects=custom_objects) return model
def get_models_from_hist_by_load(hist_idx, hist): model_dict = {} for idx in hist_idx: model_dict[idx] = load_full_model(('%s/weights/trial_%i/full_bestmodel.h5' % (hist.iloc[idx].dir, hist.iloc[idx].ID))) return model_dict
def get_best_model(state_space, controller, working_directory): 'Given a controller and a state_space, find the best model states in its\n state space\n\n Returns:\n dict: a dict of conditions for selected best model(s)\n ' return
def get_hist_index_by_conditions(condition_dict, hist, complementary=False): 'Get a set of indices for models that satisfy certain\n conditions from a hist file\n ' sign_dict = {'==': (lambda x, y: (x == y)), '>': (lambda x, y: (x > y)), '<': (lambda x, y: (x < y)), '>=': (lambda x, y: (x >= y)), '<=': ...
def get_models_from_hist(hist_idx, hist, input_state, output_state, state_space, model_compile_dict): 'Given a set of indcies, build a dictionary of\n models from history file\n ' model_dict = {} for idx in hist_idx: model_state_str = [hist.iloc[idx][('L%i' % (i + 1))] for i in range((hist.s...