code stringlengths 17 6.64M |
|---|
def extract_translations(translations: List[str], texts: List[str], translate_args: Dict[(str, Any)]) -> List[str]:
'\n Extract the translation from the output of the translation model.\n\n Args:\n - translations: A list containing the translations to be extracted.\n - texts: A list containing the tex... |
def translate_texts(dataset: DatasetDict, texts: Dict[(str, Dict[(str, List[str])])], translate_args: Dict[(str, Any)], dataset_args: Dict[(str, Any)]) -> None:
'\n Translate the texts.\n\n Args:\n - dataset: A DatasetDict object containing the dataset.\n - texts: A dictionary containing the texts to ... |
def save_file(translations: Dict[(str, List[str])], config: str, translate_args: Dict[(str, Any)], dataset_args: Dict[(str, Any)]) -> None:
'\n Save the translations to a file.\n\n Args:\n - translations: A dictionary containing the translations to be saved.\n - config: A string representing the confi... |
def main(translate_args: Dict[(str, Any)], dataset_args: Dict[(str, Any)]) -> None:
'\n Main function to translate the dataset.\n\n Args:\n - translate_args: A dictionary containing the translation configurations.\n - dataset_args: A dictionary containing the dataset configurations.\n\n Returns:\n ... |
def get_dataset(dataset_args):
dataset = DatasetDict()
for config in dataset_args['dataset_configs']:
dataset[config] = load_dataset(dataset_args['dataset'], config, split=dataset_args['dataset_split'])
return dataset
|
def get_texts(dataset, dataset_args):
texts = defaultdict(dict)
for config in dataset_args['dataset_configs']:
for field in dataset_args['dataset_fields']:
texts[config][field] = dataset[config][field]
return texts
|
def translate_texts(dataset, texts, translate_args, dataset_args):
translations = {}
for config in dataset_args['dataset_configs']:
translations[config] = dataset[config].to_dict()
translate_args['source_lang'] = dataset_args['lang_codes'][config]
print(f'Translating from {config}')
... |
def save_file(translations, config, translate_args, dataset_args):
name = translate_args['model_name'].split('/')[(- 1)]
dirname = f"{dataset_args['file_path']}/{name}"
if (not os.path.exists(dirname)):
os.makedirs(dirname)
translated_df = pd.DataFrame(translations)
filename = f"{dirname}/... |
def main(translate_args, dataset_args):
dataset = get_dataset(dataset_args)
texts = get_texts(dataset, dataset_args)
translate_texts(dataset, texts, translate_args, dataset_args)
|
def encode_string(text):
return text.replace('\r', '\\r').replace('\n', '\\n').replace('\t', '\\t')
|
def get_dataloader(accelerator: Accelerator, translate_data, tokenizer: PreTrainedTokenizerBase, batch_size: int, max_length: int) -> DataLoader:
dataset = DatasetReader(translate_data, tokenizer, max_length)
if (accelerator.distributed_type == DistributedType.TPU):
data_collator = DataCollatorForSeq2... |
def main(source_lang: str, target_lang: str, starting_batch_size: int, model_name: str='facebook/m2m100_1.2B', cache_dir: str=None, precision: str='32', max_length: int=128, max_new_tokens: int=128, num_beams: int=4, num_return_sequences: int=1, do_sample: bool=False, temperature: float=1.0, top_k: int=50, top_p: flo... |
def fixed_point(x, k, fraclength=None, signed=True):
if (fraclength != None):
f = fraclength
n = float((2.0 ** f))
mn = (- (2.0 ** ((k - f) - 1)))
mx = ((- mn) - (2.0 ** (- f)))
if (not signed):
mx -= mn
mn = 0
x = tf.clip_by_value(x, mn, mx)... |
def quantize(x, bit_width, frac_bits=None, signed=None):
if (bit_width is None):
return x
elif (bit_width == 1):
return (x + tf.stop_gradient((tf.sign(x) - x)))
elif (bit_width == 2):
ones = tf.ones_like(x)
zeros = (ones * 0)
mask = tf.where((x < 0.33), zeros, ones)... |
class SYQ(Conv2D):
def __init__(self, bit_width, *args, **kwargs):
self.bit_width = bit_width
super(SYQ, self).__init__(*args, **kwargs)
def get_config(self):
config = super().get_config()
config['bit_width'] = self.bit_width
return config
def build(self, input_s... |
class SYQ_Dense(Dense):
def __init__(self, bit_width, *args, **kwargs):
self.bit_width = bit_width
super(SYQ_Dense, self).__init__(*args, **kwargs)
def get_config(self):
config = super().get_config()
config['bit_width'] = self.bit_width
return config
def build(se... |
class Model():
def __init__(self, bit_width=None, model_name=None, load=None):
self.bit_width = bit_width
self.load = load
self.model_name = model_name
self.model = keras.Sequential([SYQ(self.bit_width, 32, (3, 3), activation='relu', input_shape=(28, 28, 1)), SYQ(self.bit_width, 3... |
def skip(app, what, name, obj, skip, options):
if (name == '__init__'):
return False
return skip
|
def process_signature(app, what, name, obj, options, signature, return_annotation):
if signature:
signature = re.sub("<Mock name='([^']+)'.*>", '\\g<1>', signature)
signature = re.sub('tensorflow', 'tf', signature)
return (signature, return_annotation)
|
def setup(app):
from recommonmark.transform import AutoStructify
app.connect('autodoc-process-signature', process_signature)
app.connect('autodoc-skip-member', skip)
app.add_config_value('recommonmark_config', {'url_resolver': (lambda url: ('https://github.com/ppwwyyxx/tensorpack/blob/master/tensorpac... |
def get_args():
description = 'plot points into graph.'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-i', '--input', help='input data file, use "-" for stdin. Default stdin. Input format is many rows of DELIMIETER-separated data', default='-')
parser.add_a... |
def filter_valid_range(points, rect):
'rect = (min_x, max_x, min_y, max_y)'
ret = []
for (x, y) in points:
if ((x >= rect[0]) and (x <= rect[1]) and (y >= rect[2]) and (y <= rect[3])):
ret.append((x, y))
if (len(ret) == 0):
ret.append(points[0])
return ret
|
def exponential_smooth(data, alpha):
' smooth data by alpha. returned a smoothed version'
ret = np.copy(data)
now = data[0]
for k in range(len(data)):
ret[k] = ((now * alpha) + (data[k] * (1 - alpha)))
now = ret[k]
return ret
|
def annotate_min_max(data_x, data_y, ax):
(max_x, min_x) = (max(data_x), min(data_x))
(max_y, min_y) = (max(data_y), min(data_y))
x_range = (max_x - min_x)
y_range = (max_y - min_y)
(x_max, y_max) = (data_y[0], data_y[0])
(x_min, y_min) = (data_x[0], data_y[0])
for i in range(1, len(data_x... |
def plot_args_from_column_desc(desc):
if (not desc):
return {}
ret = {}
desc = desc.split(';')
if ('thick' in desc):
ret['lw'] = 5
if ('dash' in desc):
ret['ls'] = '--'
for v in desc:
if v.startswith('c'):
ret['color'] = v[1:]
return ret
|
def do_plot(data_xs, data_ys):
'\n data_xs: list of 1d array, either of size 1 or size len(data_ys)\n data_ys: list of 1d array\n '
fig = plt.figure(figsize=((16.18 / 1.2), (10 / 1.2)))
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
nr_y = len(data_ys)
y_column = args.y_column
if args.legend... |
def main():
get_args()
if (args.input == STDIN_FNAME):
fin = sys.stdin
else:
fin = open(args.input)
all_inputs = fin.readlines()
if (args.input != STDIN_FNAME):
fin.close()
nr_column = len(all_inputs[0].rstrip('\n').split(args.delimeter))
if (args.column is None):
... |
def _global_import(name):
p = __import__(name, globals(), locals(), level=1)
lst = (p.__all__ if ('__all__' in dir(p)) else dir(p))
del globals()[name]
for k in lst:
globals()[k] = p.__dict__[k]
|
class PreventStuckPlayer(ProxyPlayer):
" Prevent the player from getting stuck (repeating a no-op)\n by inserting a different action. Useful in games such as Atari Breakout\n where the agent needs to press the 'start' button to start playing.\n "
def __init__(self, player, nr_repeat, action):
... |
class LimitLengthPlayer(ProxyPlayer):
' Limit the total number of actions in an episode.\n Will auto restart the underlying player on timeout\n '
def __init__(self, player, limit):
super(LimitLengthPlayer, self).__init__(player)
self.limit = limit
self.cnt = 0
def actio... |
class AutoRestartPlayer(ProxyPlayer):
" Auto-restart the player on episode ends,\n in case some player wasn't designed to do so. "
def action(self, act):
(r, isOver) = self.player.action(act)
if isOver:
self.player.finish_episode()
self.player.restart_episode()
... |
class MapPlayerState(ProxyPlayer):
def __init__(self, player, func):
super(MapPlayerState, self).__init__(player)
self.func = func
def current_state(self):
return self.func(self.player.current_state())
|
@six.add_metaclass(ABCMeta)
class RLEnvironment(object):
def __init__(self):
self.reset_stat()
@abstractmethod
def current_state(self):
'\n Observe, return a state representation\n '
@abstractmethod
def action(self, act):
'\n Perform an action. Will ... |
class ActionSpace(object):
def __init__(self):
self.rng = get_rng(self)
@abstractmethod
def sample(self):
pass
def num_actions(self):
raise NotImplementedError()
|
class DiscreteActionSpace(ActionSpace):
def __init__(self, num):
super(DiscreteActionSpace, self).__init__()
self.num = num
def sample(self):
return self.rng.randint(self.num)
def num_actions(self):
return self.num
def __repr__(self):
return 'DiscreteActionS... |
class NaiveRLEnvironment(RLEnvironment):
' for testing only'
def __init__(self):
self.k = 0
def current_state(self):
self.k += 1
return self.k
def action(self, act):
self.k = act
return (self.k, (self.k > 10))
|
class ProxyPlayer(RLEnvironment):
' Serve as a proxy another player '
def __init__(self, player):
self.player = player
def reset_stat(self):
self.player.reset_stat()
def current_state(self):
return self.player.current_state()
def action(self, act):
return self.p... |
class GymEnv(RLEnvironment):
'\n An OpenAI/gym wrapper. Can optionally auto restart.\n Only support discrete action space now\n '
def __init__(self, name, dumpdir=None, viz=False, auto_restart=True):
with _ENV_LOCK:
self.gymenv = gym.make(name)
if dumpdir:
mkd... |
class HistoryFramePlayer(ProxyPlayer):
' Include history frames in state, or use black images\n Assume player will do auto-restart.\n '
def __init__(self, player, hist_len):
'\n :param hist_len: total length of the state, including the current\n and `hist_len-1` history\n ... |
class TransitionExperience(object):
' A transition of state, or experience'
def __init__(self, state, action, reward, **kwargs):
' kwargs: whatever other attribute you want to save'
self.state = state
self.action = action
self.reward = reward
for (k, v) in six.iteritem... |
@six.add_metaclass(ABCMeta)
class SimulatorProcessBase(mp.Process):
def __init__(self, idx):
super(SimulatorProcessBase, self).__init__()
self.idx = int(idx)
self.name = u'simulator-{}'.format(self.idx)
self.identity = self.name.encode('utf-8')
@abstractmethod
def _build_... |
class SimulatorProcessStateExchange(SimulatorProcessBase):
'\n A process that simulates a player and communicates to master to\n send states and receive the next action\n '
def __init__(self, idx, pipe_c2s, pipe_s2c):
'\n :param idx: idx of this process\n '
super(Simula... |
class SimulatorMaster(threading.Thread):
' A base thread to communicate with all StateExchangeSimulatorProcess.\n It should produce action for each simulator, as well as\n defining callbacks when a transition or an episode is finished.\n '
class ClientState(object):
def __init__(sel... |
class SimulatorProcessDF(SimulatorProcessBase):
' A simulator which contains a forward model itself, allowing\n it to produce data points directly '
def __init__(self, idx, pipe_c2s):
super(SimulatorProcessDF, self).__init__(idx)
self.pipe_c2s = pipe_c2s
def run(self):
self.pl... |
class SimulatorProcessSharedWeight(SimulatorProcessDF):
' A simulator process with an extra thread waiting for event,\n and take shared weight from shm.\n\n Start me under some CUDA_VISIBLE_DEVICES set!\n '
def __init__(self, idx, pipe_c2s, condvar, shared_dic, pred_config):
super(SimulatorP... |
class WeightSync(Callback):
' Sync weight from main process to shared_dic and notify'
def __init__(self, condvar, shared_dic):
self.condvar = condvar
self.shared_dic = shared_dic
def _setup_graph(self):
self.vars = self._params_to_update()
def _params_to_update(self):
... |
def _global_import(name):
p = __import__(name, globals(), locals(), level=1)
lst = (p.__all__ if ('__all__' in dir(p)) else dir(p))
del globals()[name]
for k in lst:
globals()[k] = p.__dict__[k]
__all__.append(k)
|
@six.add_metaclass(ABCMeta)
class Callback(object):
' Base class for all callbacks '
def before_train(self):
'\n Called right before the first iteration.\n '
self._before_train()
def _before_train(self):
pass
def setup_graph(self, trainer):
'\n C... |
class ProxyCallback(Callback):
def __init__(self, cb):
self.cb = cb
def _before_train(self):
self.cb.before_train()
def _setup_graph(self):
self.cb.setup_graph(self.trainer)
def _after_train(self):
self.cb.after_train()
def _trigger_epoch(self):
self.cb... |
class PeriodicCallback(ProxyCallback):
"\n A callback to be triggered after every `period` epochs.\n Doesn't work for trigger_step\n "
def __init__(self, cb, period):
'\n :param cb: a `Callback`\n :param period: int\n '
super(PeriodicCallback, self).__init__(cb)
... |
class StartProcOrThread(Callback):
def __init__(self, procs_threads):
'\n Start extra threads and processes before training\n :param procs_threads: list of processes or threads\n '
if (not isinstance(procs_threads, list)):
procs_threads = [procs_threads]
s... |
class OutputTensorDispatcer(object):
def __init__(self):
self._names = []
self._idxs = []
def add_entry(self, names):
v = []
for n in names:
tensorname = get_op_tensor_name(n)[1]
if (tensorname in self._names):
v.append(self._names.inde... |
class DumpParamAsImage(Callback):
'\n Dump a variable to image(s) after every epoch to logger.LOG_DIR.\n '
def __init__(self, var_name, prefix=None, map_func=None, scale=255, clip=False):
'\n :param var_name: the name of the variable.\n :param prefix: the filename prefix for saved... |
class RunOp(Callback):
' Run an op periodically'
def __init__(self, setup_func, run_before=True, run_epoch=True):
'\n :param setup_func: a function that returns the op in the graph\n :param run_before: run the op before training\n :param run_epoch: run the op on every epoch trigg... |
class CallbackTimeLogger(object):
def __init__(self):
self.times = []
self.tot = 0
def add(self, name, time):
self.tot += time
self.times.append((name, time))
@contextmanager
def timed_callback(self, name):
s = time.time()
(yield)
self.add(nam... |
class Callbacks(Callback):
'\n A container to hold all callbacks, and execute them in the right order and proper session.\n '
def __init__(self, cbs):
'\n :param cbs: a list of `Callbacks`\n '
for cb in cbs:
assert isinstance(cb, Callback), cb.__class__
... |
@six.add_metaclass(ABCMeta)
class Inferencer(object):
def before_inference(self):
'\n Called before a new round of inference starts.\n '
self._before_inference()
def _before_inference(self):
pass
def datapoint(self, output):
'\n Called after complete... |
class ScalarStats(Inferencer):
'\n Write some scalar tensor to both stat and summary.\n The output of the given Ops must be a scalar.\n The value will be averaged over all data points in the inference dataflow.\n '
def __init__(self, names_to_print, prefix='validation'):
'\n :param... |
class ClassificationError(Inferencer):
'\n Compute classification error in batch mode, from a `wrong` variable\n\n The `wrong` tensor is supposed to be an 0/1 integer vector containing\n whether each sample in the batch is incorrectly classified.\n You can use `tf.nn.in_top_k` to produce this vector r... |
class BinaryClassificationStats(Inferencer):
' Compute precision/recall in binary classification, given the\n prediction vector and the label vector.\n '
def __init__(self, pred_var_name, label_var_name, summary_prefix='val'):
'\n :param pred_var_name: name of the 0/1 prediction tensor.\... |
def summary_inferencer(trainer, infs):
for inf in infs:
ret = inf.after_inference()
for (k, v) in six.iteritems(ret):
try:
v = float(v)
except:
logger.warn('{} returns a non-scalar statistics!'.format(type(inf).__name__))
cont... |
class InferenceRunner(Callback):
'\n A callback that runs different kinds of inferencer.\n '
IOTensor = namedtuple('IOTensor', ['index', 'isOutput'])
def __init__(self, ds, infs, inf_epochs, input_tensors=None):
'\n :param ds: inference dataset. a `DataFlow` instance.\n :param... |
class FeedfreeInferenceRunner(Callback):
IOTensor = namedtuple('IOTensor', ['index', 'isOutput'])
def __init__(self, input, infs, input_tensors=None):
assert isinstance(input, FeedfreeInput), input
self._input_data = input
if (not isinstance(infs, list)):
self.infs = [infs... |
@six.add_metaclass(ABCMeta)
class HyperParam(object):
' Base class for a hyper param'
def setup_graph(self):
' setup the graph in `setup_graph` callback stage, if necessary'
pass
@abstractmethod
def set_value(self, v):
' define how the value of the param will be set'
... |
class GraphVarParam(HyperParam):
' a variable in the graph can be a hyperparam'
def __init__(self, name, shape=[]):
self.name = name
self.shape = shape
(self._readable_name, self.var_name) = get_op_var_name(name)
def setup_graph(self):
try:
all_vars = tf.globa... |
class ObjAttrParam(HyperParam):
' an attribute of an object can be a hyperparam'
def __init__(self, obj, attrname, readable_name=None):
' :param readable_name: default to be attrname.'
self.obj = obj
self.attrname = attrname
if (readable_name is None):
self._readab... |
class HyperParamSetter(Callback):
'\n Base class to set hyperparameters after every epoch.\n '
def __init__(self, param):
'\n :param param: a `HyperParam` instance, or a string (assumed to be a scalar `GraphVarParam`)\n '
if isinstance(param, six.string_types):
... |
class HumanHyperParamSetter(HyperParamSetter):
'\n Set hyperparameters by loading the value from a file each time it get called.\n '
def __init__(self, param, file_name='hyper.txt'):
'\n :param file_name: a file containing the value of the variable.\n Each line in the file is ... |
class ScheduledHyperParamSetter(HyperParamSetter):
'\n Set hyperparameters by a predefined schedule.\n '
def __init__(self, param, schedule, interp=None):
"\n :param schedule: [(epoch1, val1), (epoch2, val2), (epoch3, val3), ...]\n (ep, val) means set the param to `val` after ... |
class HyperParamSetterWithFunc(HyperParamSetter):
def __init__(self, param, func):
'Set hyperparameter by a func\n new_value = f(epoch_num, old_value)\n '
super(HyperParamSetterWithFunc, self).__init__(param)
self.f = func
def _get_value_to_set(self):
return sel... |
class StatMonitorParamSetter(HyperParamSetter):
def __init__(self, param, stat_name, value_func, threshold, last_k, reverse=False):
"\n Set hyperparameter by a func, when a specific stat wasn't\n decreasing/increasing enough in the last $k$ epochs.\n Change param by `new_value = valu... |
class ModelSaver(Callback):
'\n Save the model to logger directory.\n '
def __init__(self, keep_recent=10, keep_freq=0.5, var_collections=None):
'\n :param keep_recent: see `tf.train.Saver` documentation.\n :param keep_freq: see `tf.train.Saver` documentation.\n '
s... |
class MinSaver(Callback):
def __init__(self, monitor_stat, reverse=True, filename=None):
self.monitor_stat = monitor_stat
self.reverse = reverse
self.filename = filename
self.min = None
def _get_stat(self):
try:
v = self.trainer.stat_holder.get_stat_now(se... |
class MaxSaver(MinSaver):
def __init__(self, monitor_stat):
super(MaxSaver, self).__init__(monitor_stat, True)
|
class StatHolder(object):
'\n A holder to keep all statistics aside from tensorflow events.\n '
def __init__(self, log_dir):
'\n :param log_dir: directory to save the stats.\n '
self.set_print_tag([])
self.blacklist_tag = set()
self.stat_now = {}
se... |
class StatPrinter(Callback):
'\n Control what stats to print.\n '
def __init__(self, print_tag=None):
'\n :param print_tag: a list of regex to match scalar summary to print.\n If None, will print all scalar tags\n '
self.print_tag = print_tag
def _before_tr... |
class SendStat(Callback):
'\n Execute a command with some specific stats.\n For example, send the stats to your phone through pushbullet:\n\n SendStat(\'curl -u your_id: https://api.pushbullet.com/v2/pushes -d type=note -d title="validation error" -d body={validation_error} > ... |
def _global_import(name):
p = __import__(name, globals(), locals(), level=1)
lst = (p.__all__ if ('__all__' in dir(p)) else dir(p))
del globals()[name]
for k in lst:
globals()[k] = p.__dict__[k]
|
@six.add_metaclass(ABCMeta)
class DataFlow(object):
' Base class for all DataFlow '
class Infinity():
pass
@abstractmethod
def get_data(self):
'\n A generator to generate data as a list.\n Datapoint should be a mutable list.\n Each component should be assumed imm... |
class RNGDataFlow(DataFlow):
' A dataflow with rng'
def reset_state(self):
self.rng = get_rng(self)
|
class ProxyDataFlow(DataFlow):
' Base class for DataFlow that proxies another'
def __init__(self, ds):
'\n :param ds: a :mod:`DataFlow` instance to proxy\n '
self.ds = ds
def reset_state(self):
'\n Will reset state of the proxied DataFlow\n '
s... |
class TestDataSpeed(ProxyDataFlow):
def __init__(self, ds, size=1000):
super(TestDataSpeed, self).__init__(ds)
self.test_size = size
def get_data(self):
self.start_test()
for dp in self.ds.get_data():
(yield dp)
def start_test(self):
self.ds.reset_sta... |
class BatchData(ProxyDataFlow):
def __init__(self, ds, batch_size, remainder=False):
'\n Group data in `ds` into batches.\n\n :param ds: a DataFlow instance. Its component must be either a scalar or a numpy array\n :param remainder: whether to return the remaining data smaller than a... |
class BatchDataByShape(BatchData):
def __init__(self, ds, batch_size, idx):
' Group datapoint of the same shape together to batches\n\n :param ds: a DataFlow instance. Its component must be either a scalar or a numpy array\n :param idx: dp[idx] will be used to group datapoints. Other compon... |
class FixedSizeData(ProxyDataFlow):
' Generate data from another DataFlow, but with a fixed epoch size.\n The state of the underlying DataFlow is maintained among each epoch.\n '
def __init__(self, ds, size):
'\n :param ds: a :mod:`DataFlow` to produce data\n :param size: a in... |
class RepeatedData(ProxyDataFlow):
" Take data points from another `DataFlow` and produce them until\n it's exhausted for certain amount of times.\n "
def __init__(self, ds, nr):
'\n :param ds: a :mod:`DataFlow` instance.\n :param nr: number of times to repeat ds.\n ... |
class MapData(ProxyDataFlow):
' Apply map/filter a function on the datapoint'
def __init__(self, ds, func):
"\n :param ds: a :mod:`DataFlow` instance.\n :param func: a function that takes a original datapoint, returns a new\n datapoint. return None to skip this data point.\n ... |
class MapDataComponent(ProxyDataFlow):
' Apply map/filter on the given index in the datapoint'
def __init__(self, ds, func, index=0):
"\n :param ds: a :mod:`DataFlow` instance.\n :param func: a function that takes a datapoint component dp[index], returns a\n new value of dp[i... |
class RandomChooseData(RNGDataFlow):
'\n Randomly choose from several DataFlow. Stop producing when any of them is\n exhausted.\n '
def __init__(self, df_lists):
'\n :param df_lists: list of dataflow, or list of (dataflow, probability) tuple\n '
super(RandomChooseData, ... |
class RandomMixData(RNGDataFlow):
"\n Randomly choose from several dataflow, and will eventually exhaust all dataflow. So it's a perfect mix.\n "
def __init__(self, df_lists):
'\n :param df_lists: list of dataflow.\n All DataFlow in `df_lists` must have :func:`size()` impleme... |
class ConcatData(DataFlow):
'\n Concatenate several dataflows.\n '
def __init__(self, df_lists):
'\n :param df_lists: list of :mod:`DataFlow` instances\n '
self.df_lists = df_lists
def reset_state(self):
for d in self.df_lists:
d.reset_state()
... |
class JoinData(DataFlow):
'\n Join the components from each DataFlow.\n\n .. code-block:: none\n\n e.g.: df1: [dp1, dp2]\n df2: [dp3, dp4]\n join: [dp1, dp2, dp3, dp4]\n '
def __init__(self, df_lists):
'\n :param df_lists: list of :mod:`DataFlow` insta... |
class LocallyShuffleData(ProxyDataFlow, RNGDataFlow):
def __init__(self, ds, cache_size, nr_reuse=1):
'\n Cache a number of datapoints and shuffle them.\n :param cache_size: size of the cache\n :param nr_reuse: reuse each datapoints several times\n '
ProxyDataFlow.__in... |
def SelectComponent(ds, idxs):
'\n :param ds: a :mod:`DataFlow` instance\n :param idxs: a list of datapoint component index of the original dataflow\n '
return MapData(ds, (lambda dp: [dp[i] for i in idxs]))
|
def global_import(name):
p = __import__(name, globals(), locals(), level=1)
lst = (p.__all__ if ('__all__' in dir(p)) else dir(p))
for k in lst:
globals()[k] = p.__dict__[k]
|
class BSDS500(RNGDataFlow):
'\n `Berkeley Segmentation Data Set and Benchmarks 500\n <http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/resources.html#bsds500>`_.\n\n Produce (image, label) pair, where image has shape (321, 481, 3) and\n ranges in [0,255]. Label is binary and has shape... |
def maybe_download_and_extract(dest_directory, cifar_classnum):
"Download and extract the tarball from Alex's website.\n copied from tensorflow example "
assert ((cifar_classnum == 10) or (cifar_classnum == 100))
if (cifar_classnum == 10):
cifar_foldername = 'cifar-10-batches-py'
else:
... |
def read_cifar(filenames, cifar_classnum):
assert ((cifar_classnum == 10) or (cifar_classnum == 100))
ret = []
for fname in filenames:
fo = open(fname, 'rb')
if six.PY3:
dic = pickle.load(fo, encoding='bytes')
else:
dic = pickle.load(fo)
data = dic[b... |
def get_filenames(dir, cifar_classnum):
assert ((cifar_classnum == 10) or (cifar_classnum == 100))
if (cifar_classnum == 10):
filenames = [os.path.join(dir, 'cifar-10-batches-py', ('data_batch_%d' % i)) for i in range(1, 6)]
filenames.append(os.path.join(dir, 'cifar-10-batches-py', 'test_batch... |
class CifarBase(RNGDataFlow):
'\n Return [image, label],\n image is 32x32x3 in the range [0,255]\n '
def __init__(self, train_or_test, shuffle=True, dir=None, cifar_classnum=10):
"\n Args:\n train_or_test: string either 'train' or 'test'\n shuffle: default to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.