code
stringlengths
17
6.64M
def categorical_crossentropy(y_true, y_pred): 'Expects a binary class matrix instead of a vector of scalar classes\n ' y_pred = T.clip(y_pred, epsilon, (1.0 - epsilon)) y_pred /= y_pred.sum(axis=(- 1), keepdims=True) cce = T.nnet.categorical_crossentropy(y_pred, y_true) return cce
def binary_crossentropy(y_true, y_pred): y_pred = T.clip(y_pred, epsilon, (1.0 - epsilon)) bce = T.nnet.binary_crossentropy(y_pred, y_true).mean(axis=(- 1)) return bce
def poisson_loss(y_true, y_pred): return T.mean((y_pred - (y_true * T.log((y_pred + epsilon)))), axis=(- 1))
def get(identifier): return get_from_module(identifier, globals(), 'objective')
def clip_norm(g, c, n): if (c > 0): g = T.switch(T.ge(n, c), ((g * c) / n), g) return g
def kl_divergence(p, p_hat): return ((p_hat - p) + (p * T.log((p / p_hat))))
class Optimizer(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) self.updates = [] def get_state(self): return [u[0].get_value() for u in self.updates] def set_state(self, value_list): assert (len(self.updates) == len(value_list)) for (u, v) in...
class SGD(Optimizer): def __init__(self, lr=0.01, momentum=0.0, decay=0.0, nesterov=False, *args, **kwargs): super(SGD, self).__init__(**kwargs) self.__dict__.update(locals()) self.iterations = shared_scalar(0) self.lr = shared_scalar(lr) self.momentum = shared_scalar(mome...
class RMSprop(Optimizer): def __init__(self, lr=0.001, rho=0.9, epsilon=1e-06, *args, **kwargs): super(RMSprop, self).__init__(**kwargs) self.__dict__.update(locals()) self.lr = shared_scalar(lr) self.rho = shared_scalar(rho) def get_updates(self, params, constraints, loss): ...
class Adagrad(Optimizer): def __init__(self, lr=0.01, epsilon=1e-06, *args, **kwargs): super(Adagrad, self).__init__(**kwargs) self.__dict__.update(locals()) self.lr = shared_scalar(lr) def get_updates(self, params, constraints, loss): grads = self.get_gradients(loss, params)...
class Adadelta(Optimizer): '\n Reference: http://arxiv.org/abs/1212.5701\n ' def __init__(self, lr=1.0, rho=0.95, epsilon=1e-06, *args, **kwargs): super(Adadelta, self).__init__(**kwargs) self.__dict__.update(locals()) self.lr = shared_scalar(lr) def get_updates(self, p...
class Adadelta_GaussianNoise(Optimizer): '\n Reference: http://arxiv.org/abs/1212.5701\n ' def __init__(self, lr=1.0, rho=0.95, epsilon=1e-06, *args, **kwargs): super(Adadelta_GaussianNoise, self).__init__(**kwargs) self.__dict__.update(locals()) self.lr = shared_scalar(lr) ...
class Adam(Optimizer): '\n Reference: http://arxiv.org/abs/1412.6980v8\n\n Default parameters follow those provided in the original paper.\n ' def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, *args, **kwargs): super(Adam, self).__init__(**kwargs) self.__d...
def get(identifier, kwargs=None): return get_from_module(identifier, globals(), 'optimizer', instantiate=True, kwargs=kwargs)
class MetaConfig(type): def __getitem__(self, key): return config._config[key] def __setitem__(self, key, value): config._config[key] = value
class config(object): _config = {} __metaclass__ = MetaConfig @staticmethod def set(key, val): config._config[key] = val @staticmethod def init_config(file='config.py'): if (len(config._config) > 0): return logging.info('use configuration: %s', file) ...
class HDF5Matrix(): refs = defaultdict(int) def __init__(self, datapath, dataset, start, end, normalizer=None): if (datapath not in list(self.refs.keys())): f = h5py.File(datapath) self.refs[datapath] = f else: f = self.refs[datapath] self.start = s...
def save_array(array, name): import tables f = tables.open_file(name, 'w') atom = tables.Atom.from_dtype(array.dtype) ds = f.createCArray(f.root, 'data', atom, array.shape) ds[:] = array f.close()
def load_array(name): import tables f = tables.open_file(name) array = f.root.data a = np.empty(shape=array.shape, dtype=array.dtype) a[:] = array[:] f.close() return a
def serialize_to_file(obj, path, protocol=cPickle.HIGHEST_PROTOCOL): f = open(path, 'wb') cPickle.dump(obj, f, protocol=protocol) f.close()
def deserialize_from_file(path): f = open(path, 'rb') obj = cPickle.load(f) f.close() return obj
def to_categorical(y, nb_classes=None): 'Convert class vector (integers from 0 to nb_classes)\n to binary class matrix, for use with categorical_crossentropy\n ' y = np.asarray(y, dtype='int32') if (not nb_classes): nb_classes = (np.max(y) + 1) Y = np.zeros((len(y), nb_classes)) for ...
def normalize(a, axis=(- 1), order=2): l2 = np.atleast_1d(np.linalg.norm(a, order, axis)) l2[(l2 == 0)] = 1 return (a / np.expand_dims(l2, axis))
def binary_logloss(p, y): epsilon = 1e-15 p = sp.maximum(epsilon, p) p = sp.minimum((1 - epsilon), p) res = sum(((y * sp.log(p)) + (sp.subtract(1, y) * sp.log(sp.subtract(1, p))))) res *= ((- 1.0) / len(y)) return res
def multiclass_logloss(P, Y): score = 0.0 npreds = [P[i][(Y[i] - 1)] for i in range(len(Y))] score = ((- (1.0 / len(Y))) * np.sum(np.log(npreds))) return score
def accuracy(p, y): return np.mean([(a == b) for (a, b) in zip(p, y)])
def probas_to_classes(y_pred): if ((len(y_pred.shape) > 1) and (y_pred.shape[1] > 1)): return categorical_probas_to_classes(y_pred) return np.array([(1 if (p > 0.5) else 0) for p in y_pred])
def categorical_probas_to_classes(p): return np.argmax(p, axis=1)
def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,), output_shape=(2,), classification=True, nb_class=2): '\n classification=True overrides output_shape\n (i.e. output_shape is set to (1,)) and the output\n consists in integers in [0, nb_class-1].\n\n Otherwise: float outpu...
def typename(x): return type(x).__name__
def escape(text): text = text.replace('"', '`').replace("'", '`').replace(' ', '-SP-').replace('\t', '-TAB-').replace('\n', '-NL-').replace('(', '-LRB-').replace(')', '-RRB-').replace('|', '-BAR-') return (repr(text)[1:(- 1)] if text else '-NONE-')
def makestr(node): if isinstance(node, ast.AST): n = 0 nodename = typename(node) s = ('(' + nodename) for (chname, chval) in ast.iter_fields(node): chstr = makestr(chval) if chstr: s += ((((' (' + chname) + ' ') + chstr) + ')') ...
def main(): p_elif = re.compile('^elif\\s?') p_else = re.compile('^else\\s?') p_try = re.compile('^try\\s?') p_except = re.compile('^except\\s?') p_finally = re.compile('^finally\\s?') p_decorator = re.compile('^@.*') for l in ['val = Header ( val , encoding ) . encode ( )']: l = l...
def is_numeric(s): if (s[0] in ('-', '+')): return s[1:].isdigit() return s.isdigit()
def process_story(text): 'Processed a story text into an (article, summary) tuple.\n ' elements = text.split('@highlight') elements = [_.strip() for _ in elements] story_text = elements[0] highlights = elements[1:] highlights_joined = '; '.join(highlights) highlights_joined = re.sub('\\s+...
def main(*args, **kwargs): 'Program entry point' story_text = '\n'.join(list(fileinput.input())) (story, highlights) = process_story(story_text) if (story and highlights): print('{}\t{}'.format(story, highlights))
def main(_argv): 'Program entry point.\n ' if FLAGS.config_path: with gfile.GFile(FLAGS.config_path) as config_file: config_flags = yaml.load(config_file) for (flag_key, flag_value) in config_flags.items(): setattr(FLAGS, flag_key, flag_value) if isinstance...
def _add_graph_level(graph, level, parent_ids, names, scores): 'Adds a levelto the passed graph' for (i, parent_id) in enumerate(parent_ids): new_node = (level, i) parent_node = ((level - 1), parent_id) graph.add_node(new_node) graph.node[new_node]['name'] = names[i] gr...
def create_graph(predicted_ids, parent_ids, scores, vocab=None): def get_node_name(pred): return (vocab[pred] if vocab else str(pred)) seq_length = predicted_ids.shape[0] graph = nx.DiGraph() for level in range(seq_length): names = [get_node_name(pred) for pred in predicted_ids[level]...
def main(): beam_data = np.load(ARGS.data) vocab = None if ARGS.vocab: with open(ARGS.vocab) as file: vocab = file.readlines() vocab = [_.strip() for _ in vocab] vocab += ['UNK', 'SEQUENCE_START', 'SEQUENCE_END'] if (not os.path.exists(ARGS.output_dir)): os....
def make_copy(num_examples, min_len, max_len): '\n Generates a dataset where the target is equal to the source.\n Sequence lengths are chosen randomly from [min_len, max_len].\n\n Args:\n num_examples: Number of examples to generate\n min_len: Minimum sequence length\n max_len: Maximum sequence length...
def make_reverse(num_examples, min_len, max_len): '\n Generates a dataset where the target is equal to the source reversed.\n Sequence lengths are chosen randomly from [min_len, max_len].\n\n Args:\n num_examples: Number of examples to generate\n min_len: Minimum sequence length\n max_len: Maximum seq...
def write_parallel_text(sources, targets, output_prefix): '\n Writes two files where each line corresponds to one example\n - [output_prefix].sources.txt\n - [output_prefix].targets.txt\n\n Args:\n sources: Iterator of source strings\n targets: Iterator of target strings\n output_prefix: Prefix f...
def main(): 'Main function' if (ARGS.type == 'copy'): generate_fn = make_copy elif (ARGS.type == 'reverse'): generate_fn = make_reverse examples = list(generate_fn(ARGS.num_examples, ARGS.min_len, ARGS.max_len)) try: os.makedirs(ARGS.output_dir) except OSError: ...
def _register_function_ops(func_list): 'Registers custom ops in the default graph. This is needed\n Because our checkpoint is saved with ops that are not part of Tensorflow.' op_dict = op_def_registry.get_registered_ops() for func in func_list: func._create_definition_if_needed() op_def =...
def load_metadata(model_dir): 'Loads RunMetadata, Graph and OpLog from files\n ' run_meta_path = os.path.join(model_dir, 'metadata/run_meta') run_meta = tf.RunMetadata() if gfile.Exists(run_meta_path): with gfile.GFile(run_meta_path, 'rb') as file: run_meta.MergeFromString(file.re...
def merge_default_with_oplog(graph, op_log=None, run_meta=None): 'Monkeypatch. There currently is a bug in tfprof_logger that\n prevents it from being used with Python 3. So we override the method\n manually until the fix comes in.\n ' tmp_op_log = tfprof_log_pb2.OpLog() logged_ops = tfprof_logger....
def param_analysis_options(output_dir): 'Options for model parameter analysis\n ' options = model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS.copy() options['select'] = ['params', 'bytes'] options['order_by'] = 'params' options['account_type_regexes'] = ['Variable'] if output_dir: opt...
def micro_anaylsis_options(output_dir): 'Options for microsecond analysis\n ' options = model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS.copy() options['select'] = ['micros', 'device'] options['min_micros'] = 1000 options['account_type_regexes'] = ['.*'] options['order_by'] = 'micros' if...
def flops_analysis_options(output_dir): 'Options for FLOPS analysis\n ' options = model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS.copy() options['select'] = ['float_ops', 'micros', 'device'] options['min_float_ops'] = 1 options['order_by'] = 'float_ops' options['account_type_regexes'] = ['....
def device_analysis_options(output_dir): 'Options for device placement analysis\n ' options = model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS.copy() options['select'] = ['device', 'float_ops', 'micros'] options['order_by'] = 'name' options['account_type_regexes'] = ['.*'] if output_dir: ...
def main(_argv): 'Main functions. Runs all anaylses.' tfprof_logger._merge_default_with_oplog = merge_default_with_oplog FLAGS.model_dir = os.path.abspath(os.path.expanduser(FLAGS.model_dir)) output_dir = os.path.join(FLAGS.model_dir, 'profile') gfile.MakeDirs(output_dir) (run_meta, graph, op_...
def create_experiment(output_dir): '\n Creates a new Experiment instance.\n\n Args:\n output_dir: Output directory for model checkpoints and summaries.\n ' config = run_config.RunConfig(tf_random_seed=FLAGS.tf_random_seed, save_checkpoints_secs=FLAGS.save_checkpoints_secs, save_checkpoints_steps=FLAGS.s...
def main(_argv): 'The entrypoint for the script' FLAGS.hooks = _maybe_load_yaml(FLAGS.hooks) FLAGS.metrics = _maybe_load_yaml(FLAGS.metrics) FLAGS.model_params = _maybe_load_yaml(FLAGS.model_params) FLAGS.input_pipeline_train = _maybe_load_yaml(FLAGS.input_pipeline_train) FLAGS.input_pipeline_...
class abstractstaticmethod(staticmethod): 'Decorates a method as abstract and static' __slots__ = () def __init__(self, function): super(abstractstaticmethod, self).__init__(function) function.__isabstractmethod__ = True __isabstractmethod__ = True
def _create_from_dict(dict_, default_module, *args, **kwargs): 'Creates a configurable class from a dictionary. The dictionary must have\n "class" and "params" properties. The class can be either fully qualified, or\n it is looked up in the modules passed via `default_module`.\n ' class_ = (locate(dict_['c...
def _maybe_load_yaml(item): 'Parses `item` only if it is a string. If `item` is a dictionary\n it is returned as-is.\n ' if isinstance(item, six.string_types): return yaml.load(item) elif isinstance(item, dict): return item else: raise ValueError('Got {}, expected YAML string...
def _deep_merge_dict(dict_x, dict_y, path=None): 'Recursively merges dict_y into dict_x.\n ' if (path is None): path = [] for key in dict_y: if (key in dict_x): if (isinstance(dict_x[key], dict) and isinstance(dict_y[key], dict)): _deep_merge_dict(dict_x[key], ...
def _parse_params(params, default_params): 'Parses parameter values to the types defined by the default parameters.\n Default parameters are used for missing values.\n ' if (params is None): params = {} result = copy.deepcopy(default_params) for (key, value) in params.items(): if (ke...
@six.add_metaclass(abc.ABCMeta) class Configurable(object): 'Interface for all classes that are configurable\n via a parameters dictionary.\n\n Args:\n params: A dictionary of parameters.\n mode: A value in tf.contrib.learn.ModeKeys\n ' def __init__(self, params, mode): self._params = _parse...
class Experiment(tf.contrib.learn.Experiment): 'A patched tf.learn Experiment class to handle GPU memory\n sharing issues.' def __init__(self, train_steps_per_iteration=None, *args, **kwargs): super(Experiment, self).__init__(*args, **kwargs) self._train_steps_per_iteration = train_steps_per...
class ExtendedMultiRNNCell(MultiRNNCell): 'Extends the Tensorflow MultiRNNCell with residual connections' def __init__(self, cells, residual_connections=False, residual_combiner='add', residual_dense=False): 'Create a RNN cell composed sequentially of a number of RNNCells.\n\n Args:\n cells: ...
def _transpose_batch_time(x): 'Transpose the batch and time dimensions of a Tensor.\n\n Retains as much of the static shape information as possible.\n\n Args:\n x: A tensor of rank 2 or higher.\n\n Returns:\n x transposed along the first two dimensions.\n\n Raises:\n ValueError: if `x` is rank 1 or l...
@six.add_metaclass(abc.ABCMeta) class Decoder(object): 'An RNN Decoder abstract interface object.' @property def batch_size(self): 'The batch size of the inputs returned by `sample`.' raise NotImplementedError @property def output_size(self): 'A (possibly nested tuple of....
def _create_zero_outputs(size, dtype, batch_size): 'Create a zero outputs Tensor structure.' def _t(s): return (s if isinstance(s, ops.Tensor) else constant_op.constant(tensor_shape.TensorShape(s).as_list(), dtype=dtypes.int32, name='zero_suffix_shape')) def _create(s, d): return array_o...
def dynamic_decode(decoder, output_time_major=False, impute_finished=False, maximum_iterations=None, parallel_iterations=32, swap_memory=False, scope=None): 'Perform dynamic decoding with `decoder`.\n\n Args:\n decoder: A `Decoder` instance.\n output_time_major: Python boolean. Default: `False` (batch maj...
class BaseCopyingDataProvider(data_provider.DataProvider): 'Base class for CopyingDataProvider. This data provider reads two datasets\n in parallel, keeping them aligned. It notes where each target copies\n from the parallel source or the schema.\n\n Args:\n dataset1: The first dataset. An instance of the D...
def _make_copying_data_provider_base(data_sources_source, data_sources_schema, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', **kwargs): '\n Prepare the Datasets that will be used to make the copying data provider.\n\n Args:\n data_sources_source: A list of data sources for the source text...
def make_schema_copying_data_provider(data_sources_source, data_sources_target, data_sources_schema, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', target_delimiter=' ', **kwargs): '\n Builds a copying data provider for schema-only copying.\n Args:\n data_sources_source: A list of data sou...
def make_schema_and_word_copying_data_provider(data_sources_source, data_sources_target, data_sources_schema, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', target_delimiter=' ', **kwargs): '\n Builds a copying data provider for schema and word copying.\n Args:\n data_sources_source: A lis...
def make_word_copying_data_provider(data_sources_source, data_sources_target, data_sources_schema=None, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', target_delimiter=' ', **kwargs): '\n Builds a copying data provider for word-only copying.\n Args:\n data_sources_source: A list of data so...
class SchemaCopyingDataProvider(BaseCopyingDataProvider): def _target_and_copy_sources(self, data_target, source_tensors, schema): return [data_target, None, schema]
class WordCopyingDataProvider(BaseCopyingDataProvider): def _target_and_copy_sources(self, data_target, source_tensors, schema): return [data_target, source_tensors, None]
class SchemaAndWordCopyingDataProvider(BaseCopyingDataProvider): def _target_and_copy_sources(self, data_target, source_tensors, schema): return [data_target, source_tensors, schema]
class BaseCopyingDecoder(split_tokens_decoder.SplitTokensDecoder): 'Base class for A DataDecoder that splits a string tensor into individual\n tokens and marks those copied from the input sequence or the schema.\n Optionally prepends or appends special tokens.\n\n Args:\n delimiter: Delimiter to spl...
class SchemaAndWordCopyingDecoder(BaseCopyingDecoder): '\n CopyingDecoder that marks where the output sequence copies from the input\n sequence and where it copies from the schema.\n\n Args:\n delimiter: Delimiter to split on. Must be a single character.\n tokens_feature_name: A descriptive fea...
class SchemaCopyingDecoder(BaseCopyingDecoder): '\n CopyingDecoder that marks where the output sequence copies from the\n schema.\n\n Args:\n delimiter: Delimiter to split on. Must be a single character.\n tokens_feature_name: A descriptive feature name for the token values\n length_featur...
class WordCopyingDecoder(BaseCopyingDecoder): '\n CopyingDecoder that marks where the output sequence copies from the input\n sequence.\n\n Args:\n delimiter: Delimiter to split on. Must be a single character.\n tokens_feature_name: A descriptive feature name for the token values\n length_...
def make_input_pipeline_from_def(def_dict, mode, **kwargs): 'Creates an InputPipeline object from a dictionary definition.\n\n Args:\n def_dict: A dictionary defining the input pipeline.\n It must have "class" and "params" that correspond to the class\n name and constructor parameters of an InputPip...
@six.add_metaclass(abc.ABCMeta) class InputPipeline(Configurable): 'Abstract InputPipeline class. All input pipelines must inherit from this.\n An InputPipeline defines how data is read, parsed, and separated into\n features and labels.\n\n Params:\n shuffle: If true, shuffle the data.\n num_epochs: Numb...
class ParallelTextInputPipeline(InputPipeline): 'An input pipeline that reads two parallel (line-by-line aligned) text\n files.\n\n Params:\n source_files: An array of file names for the source data.\n target_files: An array of file names for the target data. These must\n be aligned to the `source_fi...
class ParallelTextAndMaskInputPipeline(ParallelTextInputPipeline): @staticmethod def default_params(): params = ParallelTextInputPipeline.default_params() params.update({'decoder_mask_files': []}) return params def make_data_provider(self, **kwargs): target_files = self.p...
class ParallelTextAndSchemaInputPipeline(ParallelTextInputPipeline): '\n An input pipeline that reads three parallel (line-by-line aligned) text files:\n a source, a target, and a schema location.\n\n Params:\n source_files: An array of file names for the source data.\n target_files: An array of file nam...
class ParallelTextAndSchemaMapInputPipeline(ParallelTextAndSchemaInputPipeline): '\n An input pipeline that reads three parallel (line-by-line aligned) text files:\n a source, a target, and a schema location. Expects both schema embeddings and\n schema map at the schema locations.\n\n Params:\n source_file...
class ParallelTextAndMaskCopyingPipeline(ParallelTextAndMaskInputPipeline): def make_data_provider(self, **kwargs): target_files = self.params['target_files'] if (not target_files): target_files = None return self._get_copying_data_provider(target_files, **kwargs) def _ge...
class BaseParallelCopyingPipeline(ParallelTextAndSchemaInputPipeline): 'A base class for copying input pipeline that reads three parallel\n (line-by-line aligned) text files and identifies tokens copied from\n the schema or source.\n\n Params:\n source_files: An array of file names for the source data.\n ...
class ParallelSchemaCopyingPipeline(BaseParallelCopyingPipeline): 'A copying input pipeline that reads two parallel (line-by-line aligned)\n text files and a schema. It identifies tokens copied from the schema.\n\n Params:\n source_files: An array of file names for the source data.\n target_files: An arra...
class ParallelTextAndSchemaCopyingPipeline(ParallelSchemaCopyingPipeline): 'A copying input pipeline that reads two parallel (line-by-line aligned)\n text files and a schema. It identifies tokens copied from both the schema\n and source.\n\n Params:\n source_files: An array of file names for the source data...
class ParallelTextCopyingPipeline(BaseParallelCopyingPipeline): 'A copying input pipeline that reads two parallel (line-by-line aligned)\n text files. It identifies tokens copied from the input sequence to the\n output sequence.\n\n Params:\n source_files: An array of file names for the source data.\n ta...
class TFRecordInputPipeline(InputPipeline): 'An input pipeline that reads a TFRecords containing both source\n and target sequences.\n\n Params:\n files: An array of file names to read from.\n source_field: The TFRecord feature field containing the source text.\n target_field: The TFRecord feature fiel...
class ImageCaptioningInputPipeline(InputPipeline): 'An input pipeline that reads a TFRecords containing both source\n and target sequences.\n\n Params:\n files: An array of file names to read from.\n source_field: The TFRecord feature field containing the source text.\n target_field: The TFRecord featu...
def make_parallel_data_provider(data_sources_source, data_sources_target, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', target_delimiter=' ', **kwargs): 'Creates a DataProvider that reads parallel text data.\n\n Args:\n data_sources_source: A list of data sources for the source text files....
class ParallelDataProvider(data_provider.DataProvider): 'Creates a ParallelDataProvider. This data provider reads two datasets\n in parallel, keeping them aligned.\n\n Args:\n dataset1: The first dataset. An instance of the Dataset class.\n dataset2: The second dataset. An instance of the Dataset class.\n...
def strip_bpe(text): 'Deodes text that was processed using BPE from\n https://github.com/rsennrich/subword-nmt' return text.replace('@@ ', '').strip()
def decode_sentencepiece(text): 'Decodes text that uses https://github.com/google/sentencepiece encoding.\n Assumes that pieces are separated by a space' return ''.join(text.split(' ')).replace('▁', ' ').strip()
def slice_text(text, eos_token='SEQUENCE_END', sos_token='SEQUENCE_START'): 'Slices text from SEQUENCE_START to SEQUENCE_END, not including\n these special tokens.\n ' eos_index = text.find(eos_token) text = (text[:eos_index] if (eos_index > (- 1)) else text) sos_index = text.find(sos_token) tex...
class TFSEquenceExampleDecoder(data_decoder.DataDecoder): "A decoder for TensorFlow Examples.\n Decoding Example proto buffers is comprised of two stages: (1) Example parsing\n and (2) tensor manipulation.\n In the first stage, the tf.parse_example function is called with a list of\n FixedLenFeatures and Spar...
class SplitMaskDecoder(data_decoder.DataDecoder): 'A DataProvider that splits a string tensor into individual tokens and\n returns the tokens and the length.\n Optionally prepends or appends special tokens.\n\n Args:\n delimiter: Delimiter to split on. Must be a single character.\n tokens_feature_name: A...
class SplitTokensDecoder(data_decoder.DataDecoder): 'A DataProvider that splits a string tensor into individual tokens and\n returns the tokens and the length.\n Optionally prepends or appends special tokens.\n\n Args:\n delimiter: Delimiter to split on. Must be a single character.\n tokens_feature_name:...
def make_triple_data_provider(data_sources_source, data_sources_target, data_sources_schema, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', target_delimiter=' ', **kwargs): 'Creates a DataProvider that reads parallel text data.\n\n Args:\n data_sources_source: A list of data sources for the...