sia_tp_sample / A-bone1__Attention-ocr-Chinese-Version.jsonl
shahp7575's picture
commit files to HF hub
3a7f06a
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/utils.py","language":"python","identifier":"logits_to_log_prob","parameters":"(logits)","argument_list":"","return_statement":"return log_probs","docstring":"Computes log probabilities using numerically stable trick.\n\n This uses two numerical stability tricks:\n 1) softmax(x) = softmax(x - c) where c is a constant applied to all\n arguments. If we set c = max(x) then the softmax is more numerically\n stable.\n 2) log softmax(x) is not numerically stable, but we can stabilize it\n by using the identity log softmax(x) = x - log sum exp(x)\n\n Args:\n logits: Tensor of arbitrary shape whose last dimension contains logits.\n\n Returns:\n A tensor of the same shape as the input, but with corresponding log\n probabilities.","docstring_summary":"Computes log probabilities using numerically stable trick.","docstring_tokens":["Computes","log","probabilities","using","numerically","stable","trick","."],"function":"def logits_to_log_prob(logits):\n \"\"\"Computes log probabilities using numerically stable trick.\n\n This uses two numerical stability tricks:\n 1) softmax(x) = softmax(x - c) where c is a constant applied to all\n arguments. If we set c = max(x) then the softmax is more numerically\n stable.\n 2) log softmax(x) is not numerically stable, but we can stabilize it\n by using the identity log softmax(x) = x - log sum exp(x)\n\n Args:\n logits: Tensor of arbitrary shape whose last dimension contains logits.\n\n Returns:\n A tensor of the same shape as the input, but with corresponding log\n probabilities.\n \"\"\"\n\n with tf.variable_scope('log_probabilities'):\n reduction_indices = len(logits.shape.as_list()) - 1\n max_logits = tf.reduce_max(\n logits, reduction_indices=reduction_indices, keep_dims=True)\n safe_logits = tf.subtract(logits, max_logits)\n sum_exp = tf.reduce_sum(\n tf.exp(safe_logits),\n reduction_indices=reduction_indices,\n keep_dims=True)\n log_probs = tf.subtract(safe_logits, tf.log(sum_exp))\n return log_probs","function_tokens":["def","logits_to_log_prob","(","logits",")",":","with","tf",".","variable_scope","(","'log_probabilities'",")",":","reduction_indices","=","len","(","logits",".","shape",".","as_list","(",")",")","-","1","max_logits","=","tf",".","reduce_max","(","logits",",","reduction_indices","=","reduction_indices",",","keep_dims","=","True",")","safe_logits","=","tf",".","subtract","(","logits",",","max_logits",")","sum_exp","=","tf",".","reduce_sum","(","tf",".","exp","(","safe_logits",")",",","reduction_indices","=","reduction_indices",",","keep_dims","=","True",")","log_probs","=","tf",".","subtract","(","safe_logits",",","tf",".","log","(","sum_exp",")",")","return","log_probs"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/utils.py#L22-L50"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/utils.py","language":"python","identifier":"variables_to_restore","parameters":"(scope=None, strip_scope=False)","argument_list":"","return_statement":"","docstring":"Returns a list of variables to restore for the specified list of methods.\n\n It is supposed that variable name starts with the method's scope (a prefix\n returned by _method_scope function).\n\n Args:\n methods_names: a list of names of configurable methods.\n strip_scope: if True will return variable names without method's scope.\n If methods_names is None will return names unchanged.\n model_scope: a scope for a whole model.\n\n Returns:\n a dictionary mapping variable names to variables for restore.","docstring_summary":"Returns a list of variables to restore for the specified list of methods.","docstring_tokens":["Returns","a","list","of","variables","to","restore","for","the","specified","list","of","methods","."],"function":"def variables_to_restore(scope=None, strip_scope=False):\n \"\"\"Returns a list of variables to restore for the specified list of methods.\n\n It is supposed that variable name starts with the method's scope (a prefix\n returned by _method_scope function).\n\n Args:\n methods_names: a list of names of configurable methods.\n strip_scope: if True will return variable names without method's scope.\n If methods_names is None will return names unchanged.\n model_scope: a scope for a whole model.\n\n Returns:\n a dictionary mapping variable names to variables for restore.\n \"\"\"\n if scope:\n variable_map = {}\n method_variables = slim.get_variables_to_restore(include=[scope])\n for var in method_variables:\n if strip_scope:\n var_name = var.op.name[len(scope) + 1:]\n else:\n var_name = var.op.name\n variable_map[var_name] = var\n\n return variable_map\n else:\n return {v.op.name: v for v in slim.get_variables_to_restore()}","function_tokens":["def","variables_to_restore","(","scope","=","None",",","strip_scope","=","False",")",":","if","scope",":","variable_map","=","{","}","method_variables","=","slim",".","get_variables_to_restore","(","include","=","[","scope","]",")","for","var","in","method_variables",":","if","strip_scope",":","var_name","=","var",".","op",".","name","[","len","(","scope",")","+","1",":","]","else",":","var_name","=","var",".","op",".","name","variable_map","[","var_name","]","=","var","return","variable_map","else",":","return","{","v",".","op",".","name",":","v","for","v","in","slim",".","get_variables_to_restore","(",")","}"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/utils.py#L53-L80"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/common_flags.py","language":"python","identifier":"define","parameters":"()","argument_list":"","return_statement":"","docstring":"Define common flags.","docstring_summary":"Define common flags.","docstring_tokens":["Define","common","flags","."],"function":"def define():\n \"\"\"Define common flags.\"\"\"\n # yapf: disable\n flags.DEFINE_integer('batch_size', 32,\n 'Batch size.')\n\n flags.DEFINE_integer('crop_width', None,\n 'Width of the central crop for images.')\n\n flags.DEFINE_integer('crop_height', None,\n 'Height of the central crop for images.')\n\n flags.DEFINE_string('train_log_dir', '\/home\/ucmed\/opt\/python\/models-master\/research\/attention_ocr\/python\/logs',\n 'Directory where to write event logs.')\n\n flags.DEFINE_string('dataset_name', 'fsns',\n 'Name of the dataset. Supported: fsns')\n\n flags.DEFINE_string('split_name', 'train',\n 'Dataset split name to run evaluation for: test,train.')\n\n flags.DEFINE_string('dataset_dir', None,\n 'Dataset root folder.')\n\n flags.DEFINE_string('checkpoint', '',\n 'Path for checkpoint to restore weights from.')\n\n flags.DEFINE_string('master',\n '',\n 'BNS name of the TensorFlow master to use.')\n\n # Model hyper parameters\n flags.DEFINE_float('learning_rate', 0.004,\n 'learning rate')\n\n flags.DEFINE_string('optimizer', 'momentum',\n 'the optimizer to use')\n\n flags.DEFINE_string('momentum', 0.9,\n 'momentum value for the momentum optimizer if used')\n\n flags.DEFINE_bool('use_augment_input', True,\n 'If True will use image augmentation')\n\n # Method hyper parameters\n # conv_tower_fn\n flags.DEFINE_string('final_endpoint', 'Mixed_5d',\n 'Endpoint to cut inception tower')\n\n # sequence_logit_fn\n flags.DEFINE_bool('use_attention', True,\n 'If True will use the attention mechanism')\n\n flags.DEFINE_bool('use_autoregression', True,\n 'If True will use autoregression (a feedback link)')\n\n flags.DEFINE_integer('num_lstm_units', 256,\n 'number of LSTM units for sequence LSTM')\n\n flags.DEFINE_float('weight_decay', 0.00004,\n 'weight decay for char prediction FC layers')\n\n flags.DEFINE_float('lstm_state_clip_value', 10.0,\n 'cell state is clipped by this value prior to the cell'\n ' output activation')\n\n # 'sequence_loss_fn'\n flags.DEFINE_float('label_smoothing', 0.1,\n 'weight for label smoothing')\n\n flags.DEFINE_bool('ignore_nulls', True,\n 'ignore null characters for computing the loss')\n\n flags.DEFINE_bool('average_across_timesteps', False,\n 'divide the returned cost by the total label weight')","function_tokens":["def","define","(",")",":","# yapf: disable","flags",".","DEFINE_integer","(","'batch_size'",",","32",",","'Batch size.'",")","flags",".","DEFINE_integer","(","'crop_width'",",","None",",","'Width of the central crop for images.'",")","flags",".","DEFINE_integer","(","'crop_height'",",","None",",","'Height of the central crop for images.'",")","flags",".","DEFINE_string","(","'train_log_dir'",",","'\/home\/ucmed\/opt\/python\/models-master\/research\/attention_ocr\/python\/logs'",",","'Directory where to write event logs.'",")","flags",".","DEFINE_string","(","'dataset_name'",",","'fsns'",",","'Name of the dataset. Supported: fsns'",")","flags",".","DEFINE_string","(","'split_name'",",","'train'",",","'Dataset split name to run evaluation for: test,train.'",")","flags",".","DEFINE_string","(","'dataset_dir'",",","None",",","'Dataset root folder.'",")","flags",".","DEFINE_string","(","'checkpoint'",",","''",",","'Path for checkpoint to restore weights from.'",")","flags",".","DEFINE_string","(","'master'",",","''",",","'BNS name of the TensorFlow master to use.'",")","# Model hyper parameters","flags",".","DEFINE_float","(","'learning_rate'",",","0.004",",","'learning rate'",")","flags",".","DEFINE_string","(","'optimizer'",",","'momentum'",",","'the optimizer to use'",")","flags",".","DEFINE_string","(","'momentum'",",","0.9",",","'momentum value for the momentum optimizer if used'",")","flags",".","DEFINE_bool","(","'use_augment_input'",",","True",",","'If True will use image augmentation'",")","# Method hyper parameters","# conv_tower_fn","flags",".","DEFINE_string","(","'final_endpoint'",",","'Mixed_5d'",",","'Endpoint to cut inception tower'",")","# sequence_logit_fn","flags",".","DEFINE_bool","(","'use_attention'",",","True",",","'If True will use the attention mechanism'",")","flags",".","DEFINE_bool","(","'use_autoregression'",",","True",",","'If True will use autoregression (a feedback link)'",")","flags",".","DEFINE_integer","(","'num_lstm_units'",",","256",",","'number of LSTM units for sequence LSTM'",")","flags",".","DEFINE_float","(","'weight_decay'",",","0.00004",",","'weight decay for char prediction FC layers'",")","flags",".","DEFINE_float","(","'lstm_state_clip_value'",",","10.0",",","'cell state is clipped by this value prior to the cell'","' output activation'",")","# 'sequence_loss_fn'","flags",".","DEFINE_float","(","'label_smoothing'",",","0.1",",","'weight for label smoothing'",")","flags",".","DEFINE_bool","(","'ignore_nulls'",",","True",",","'ignore null characters for computing the loss'",")","flags",".","DEFINE_bool","(","'average_across_timesteps'",",","False",",","'divide the returned cost by the total label weight'",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/common_flags.py#L38-L112"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"get_softmax_loss_fn","parameters":"(label_smoothing)","argument_list":"","return_statement":"return loss_fn","docstring":"Returns sparse or dense loss function depending on the label_smoothing.\n\n Args:\n label_smoothing: weight for label smoothing\n\n Returns:\n a function which takes labels and predictions as arguments and returns\n a softmax loss for the selected type of labels (sparse or dense).","docstring_summary":"Returns sparse or dense loss function depending on the label_smoothing.","docstring_tokens":["Returns","sparse","or","dense","loss","function","depending","on","the","label_smoothing","."],"function":"def get_softmax_loss_fn(label_smoothing):\n \"\"\"Returns sparse or dense loss function depending on the label_smoothing.\n\n Args:\n label_smoothing: weight for label smoothing\n\n Returns:\n a function which takes labels and predictions as arguments and returns\n a softmax loss for the selected type of labels (sparse or dense).\n \"\"\"\n if label_smoothing > 0:\n\n def loss_fn(labels, logits):\n return (tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=labels))\n else:\n\n def loss_fn(labels, logits):\n return tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits, labels=labels)\n\n return loss_fn","function_tokens":["def","get_softmax_loss_fn","(","label_smoothing",")",":","if","label_smoothing",">","0",":","def","loss_fn","(","labels",",","logits",")",":","return","(","tf",".","nn",".","softmax_cross_entropy_with_logits","(","logits","=","logits",",","labels","=","labels",")",")","else",":","def","loss_fn","(","labels",",","logits",")",":","return","tf",".","nn",".","sparse_softmax_cross_entropy_with_logits","(","logits","=","logits",",","labels","=","labels",")","return","loss_fn"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L100-L121"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"CharsetMapper.__init__","parameters":"(self, charset, default_character='?')","argument_list":"","return_statement":"","docstring":"Creates a lookup table.\n\n Args:\n charset: a dictionary with id-to-character mapping.","docstring_summary":"Creates a lookup table.","docstring_tokens":["Creates","a","lookup","table","."],"function":"def __init__(self, charset, default_character='?'):\n \"\"\"Creates a lookup table.\n\n Args:\n charset: a dictionary with id-to-character mapping.\n \"\"\"\n mapping_strings = tf.constant(_dict_to_array(charset, default_character))\n self.table = tf.contrib.lookup.index_to_string_table_from_tensor(\n mapping=mapping_strings, default_value=default_character)","function_tokens":["def","__init__","(","self",",","charset",",","default_character","=","'?'",")",":","mapping_strings","=","tf",".","constant","(","_dict_to_array","(","charset",",","default_character",")",")","self",".","table","=","tf",".","contrib",".","lookup",".","index_to_string_table_from_tensor","(","mapping","=","mapping_strings",",","default_value","=","default_character",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L80-L88"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"CharsetMapper.get_text","parameters":"(self, ids)","argument_list":"","return_statement":"return tf.reduce_join(\n self.table.lookup(tf.to_int64(ids)), reduction_indices=1)","docstring":"Returns a string corresponding to a sequence of character ids.\n\n Args:\n ids: a tensor with shape [batch_size, max_sequence_length]","docstring_summary":"Returns a string corresponding to a sequence of character ids.","docstring_tokens":["Returns","a","string","corresponding","to","a","sequence","of","character","ids","."],"function":"def get_text(self, ids):\n \"\"\"Returns a string corresponding to a sequence of character ids.\n\n Args:\n ids: a tensor with shape [batch_size, max_sequence_length]\n \"\"\"\n return tf.reduce_join(\n self.table.lookup(tf.to_int64(ids)), reduction_indices=1)","function_tokens":["def","get_text","(","self",",","ids",")",":","return","tf",".","reduce_join","(","self",".","table",".","lookup","(","tf",".","to_int64","(","ids",")",")",",","reduction_indices","=","1",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L90-L97"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.__init__","parameters":"(self,\n num_char_classes,\n seq_length,\n num_views,\n null_code,\n mparams=None,\n charset=None)","argument_list":"","return_statement":"","docstring":"Initialized model parameters.\n\n Args:\n num_char_classes: size of character set.\n seq_length: number of characters in a sequence.\n num_views: Number of views (conv towers) to use.\n null_code: A character code corresponding to a character which\n indicates end of a sequence.\n mparams: a dictionary with hyper parameters for methods, keys -\n function names, values - corresponding namedtuples.\n charset: an optional dictionary with a mapping between character ids and\n utf8 strings. If specified the OutputEndpoints.predicted_text will\n utf8 encoded strings corresponding to the character ids returned by\n OutputEndpoints.predicted_chars (by default the predicted_text contains\n an empty vector). \n NOTE: Make sure you call tf.tables_initializer().run() if the charset\n specified.","docstring_summary":"Initialized model parameters.","docstring_tokens":["Initialized","model","parameters","."],"function":"def __init__(self,\n num_char_classes,\n seq_length,\n num_views,\n null_code,\n mparams=None,\n charset=None):\n \"\"\"Initialized model parameters.\n\n Args:\n num_char_classes: size of character set.\n seq_length: number of characters in a sequence.\n num_views: Number of views (conv towers) to use.\n null_code: A character code corresponding to a character which\n indicates end of a sequence.\n mparams: a dictionary with hyper parameters for methods, keys -\n function names, values - corresponding namedtuples.\n charset: an optional dictionary with a mapping between character ids and\n utf8 strings. If specified the OutputEndpoints.predicted_text will\n utf8 encoded strings corresponding to the character ids returned by\n OutputEndpoints.predicted_chars (by default the predicted_text contains\n an empty vector). \n NOTE: Make sure you call tf.tables_initializer().run() if the charset\n specified.\n \"\"\"\n super(Model, self).__init__()\n self._params = ModelParams(\n num_char_classes=num_char_classes,\n seq_length=seq_length,\n num_views=num_views,\n null_code=null_code)\n self._mparams = self.default_mparams()\n if mparams:\n self._mparams.update(mparams)\n self._charset = charset","function_tokens":["def","__init__","(","self",",","num_char_classes",",","seq_length",",","num_views",",","null_code",",","mparams","=","None",",","charset","=","None",")",":","super","(","Model",",","self",")",".","__init__","(",")","self",".","_params","=","ModelParams","(","num_char_classes","=","num_char_classes",",","seq_length","=","seq_length",",","num_views","=","num_views",",","null_code","=","null_code",")","self",".","_mparams","=","self",".","default_mparams","(",")","if","mparams",":","self",".","_mparams",".","update","(","mparams",")","self",".","_charset","=","charset"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L127-L161"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.conv_tower_fn","parameters":"(self, images, is_training=True, reuse=None)","argument_list":"","return_statement":"","docstring":"Computes convolutional features using the InceptionV3 model.\n\n Args:\n images: A tensor of shape [batch_size, height, width, channels].\n is_training: whether is training or not.\n reuse: whether or not the network and its variables should be reused. To\n be able to reuse 'scope' must be given.\n\n Returns:\n A tensor of shape [batch_size, OH, OW, N], where OWxOH is resolution of\n output feature map and N is number of output features (depends on the\n network architecture).","docstring_summary":"Computes convolutional features using the InceptionV3 model.","docstring_tokens":["Computes","convolutional","features","using","the","InceptionV3","model","."],"function":"def conv_tower_fn(self, images, is_training=True, reuse=None):\n \"\"\"Computes convolutional features using the InceptionV3 model.\n\n Args:\n images: A tensor of shape [batch_size, height, width, channels].\n is_training: whether is training or not.\n reuse: whether or not the network and its variables should be reused. To\n be able to reuse 'scope' must be given.\n\n Returns:\n A tensor of shape [batch_size, OH, OW, N], where OWxOH is resolution of\n output feature map and N is number of output features (depends on the\n network architecture).\n \"\"\"\n mparams = self._mparams['conv_tower_fn']\n logging.debug('Using final_endpoint=%s', mparams.final_endpoint)\n with tf.variable_scope('conv_tower_fn\/INCE'):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n with slim.arg_scope(inception.inception_v3_arg_scope()):\n with slim.arg_scope([slim.batch_norm, slim.dropout],\n is_training=is_training):\n net, _ = inception.inception_v3_base(\n images, final_endpoint=mparams.final_endpoint)\n return net","function_tokens":["def","conv_tower_fn","(","self",",","images",",","is_training","=","True",",","reuse","=","None",")",":","mparams","=","self",".","_mparams","[","'conv_tower_fn'","]","logging",".","debug","(","'Using final_endpoint=%s'",",","mparams",".","final_endpoint",")","with","tf",".","variable_scope","(","'conv_tower_fn\/INCE'",")",":","if","reuse",":","tf",".","get_variable_scope","(",")",".","reuse_variables","(",")","with","slim",".","arg_scope","(","inception",".","inception_v3_arg_scope","(",")",")",":","with","slim",".","arg_scope","(","[","slim",".","batch_norm",",","slim",".","dropout","]",",","is_training","=","is_training",")",":","net",",","_","=","inception",".","inception_v3_base","(","images",",","final_endpoint","=","mparams",".","final_endpoint",")","return","net"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L185-L209"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model._create_lstm_inputs","parameters":"(self, net)","argument_list":"","return_statement":"return tf.unstack(net, axis=1)","docstring":"Splits an input tensor into a list of tensors (features).\n\n Args:\n net: A feature map of shape [batch_size, num_features, feature_size].\n\n Raises:\n AssertionError: if num_features is less than seq_length.\n\n Returns:\n A list with seq_length tensors of shape [batch_size, feature_size]","docstring_summary":"Splits an input tensor into a list of tensors (features).","docstring_tokens":["Splits","an","input","tensor","into","a","list","of","tensors","(","features",")","."],"function":"def _create_lstm_inputs(self, net):\n \"\"\"Splits an input tensor into a list of tensors (features).\n\n Args:\n net: A feature map of shape [batch_size, num_features, feature_size].\n\n Raises:\n AssertionError: if num_features is less than seq_length.\n\n Returns:\n A list with seq_length tensors of shape [batch_size, feature_size]\n \"\"\"\n num_features = net.get_shape().dims[1].value\n if num_features < self._params.seq_length:\n raise AssertionError('Incorrect dimension #1 of input tensor'\n ' %d should be bigger than %d (shape=%s)' %\n (num_features, self._params.seq_length,\n net.get_shape()))\n elif num_features > self._params.seq_length:\n logging.warning('Ignoring some features: use %d of %d (shape=%s)',\n self._params.seq_length, num_features, net.get_shape())\n net = tf.slice(net, [0, 0, 0], [-1, self._params.seq_length, -1])\n\n return tf.unstack(net, axis=1)","function_tokens":["def","_create_lstm_inputs","(","self",",","net",")",":","num_features","=","net",".","get_shape","(",")",".","dims","[","1","]",".","value","if","num_features","<","self",".","_params",".","seq_length",":","raise","AssertionError","(","'Incorrect dimension #1 of input tensor'","' %d should be bigger than %d (shape=%s)'","%","(","num_features",",","self",".","_params",".","seq_length",",","net",".","get_shape","(",")",")",")","elif","num_features",">","self",".","_params",".","seq_length",":","logging",".","warning","(","'Ignoring some features: use %d of %d (shape=%s)'",",","self",".","_params",".","seq_length",",","num_features",",","net",".","get_shape","(",")",")","net","=","tf",".","slice","(","net",",","[","0",",","0",",","0","]",",","[","-","1",",","self",".","_params",".","seq_length",",","-","1","]",")","return","tf",".","unstack","(","net",",","axis","=","1",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L211-L234"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.max_pool_views","parameters":"(self, nets_list)","argument_list":"","return_statement":"return net","docstring":"Max pool across all nets in spatial dimensions.\n\n Args:\n nets_list: A list of 4D tensors with identical size.\n\n Returns:\n A tensor with the same size as any input tensors.","docstring_summary":"Max pool across all nets in spatial dimensions.","docstring_tokens":["Max","pool","across","all","nets","in","spatial","dimensions","."],"function":"def max_pool_views(self, nets_list):\n \"\"\"Max pool across all nets in spatial dimensions.\n\n Args:\n nets_list: A list of 4D tensors with identical size.\n\n Returns:\n A tensor with the same size as any input tensors.\n \"\"\"\n batch_size, height, width, num_features = [\n d.value for d in nets_list[0].get_shape().dims\n ]\n xy_flat_shape = (batch_size, 1, height * width, num_features)\n nets_for_merge = []\n with tf.variable_scope('max_pool_views', values=nets_list):\n for net in nets_list:\n nets_for_merge.append(tf.reshape(net, xy_flat_shape))\n merged_net = tf.concat(nets_for_merge, 1)\n net = slim.max_pool2d(\n merged_net, kernel_size=[len(nets_list), 1], stride=1)\n net = tf.reshape(net, (batch_size, height, width, num_features))\n return net","function_tokens":["def","max_pool_views","(","self",",","nets_list",")",":","batch_size",",","height",",","width",",","num_features","=","[","d",".","value","for","d","in","nets_list","[","0","]",".","get_shape","(",")",".","dims","]","xy_flat_shape","=","(","batch_size",",","1",",","height","*","width",",","num_features",")","nets_for_merge","=","[","]","with","tf",".","variable_scope","(","'max_pool_views'",",","values","=","nets_list",")",":","for","net","in","nets_list",":","nets_for_merge",".","append","(","tf",".","reshape","(","net",",","xy_flat_shape",")",")","merged_net","=","tf",".","concat","(","nets_for_merge",",","1",")","net","=","slim",".","max_pool2d","(","merged_net",",","kernel_size","=","[","len","(","nets_list",")",",","1","]",",","stride","=","1",")","net","=","tf",".","reshape","(","net",",","(","batch_size",",","height",",","width",",","num_features",")",")","return","net"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L245-L266"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.pool_views_fn","parameters":"(self, nets)","argument_list":"","return_statement":"","docstring":"Combines output of multiple convolutional towers into a single tensor.\n\n It stacks towers one on top another (in height dim) in a 4x1 grid.\n The order is arbitrary design choice and shouldn't matter much.\n\n Args:\n nets: list of tensors of shape=[batch_size, height, width, num_features].\n\n Returns:\n A tensor of shape [batch_size, seq_length, features_size].","docstring_summary":"Combines output of multiple convolutional towers into a single tensor.","docstring_tokens":["Combines","output","of","multiple","convolutional","towers","into","a","single","tensor","."],"function":"def pool_views_fn(self, nets):\n \"\"\"Combines output of multiple convolutional towers into a single tensor.\n\n It stacks towers one on top another (in height dim) in a 4x1 grid.\n The order is arbitrary design choice and shouldn't matter much.\n\n Args:\n nets: list of tensors of shape=[batch_size, height, width, num_features].\n\n Returns:\n A tensor of shape [batch_size, seq_length, features_size].\n \"\"\"\n with tf.variable_scope('pool_views_fn\/STCK'):\n net = tf.concat(nets, 1)\n batch_size = net.get_shape().dims[0].value\n feature_size = net.get_shape().dims[3].value\n return tf.reshape(net, [batch_size, -1, feature_size])","function_tokens":["def","pool_views_fn","(","self",",","nets",")",":","with","tf",".","variable_scope","(","'pool_views_fn\/STCK'",")",":","net","=","tf",".","concat","(","nets",",","1",")","batch_size","=","net",".","get_shape","(",")",".","dims","[","0","]",".","value","feature_size","=","net",".","get_shape","(",")",".","dims","[","3","]",".","value","return","tf",".","reshape","(","net",",","[","batch_size",",","-","1",",","feature_size","]",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L268-L284"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.char_predictions","parameters":"(self, chars_logit)","argument_list":"","return_statement":"return ids, log_prob, scores","docstring":"Returns confidence scores (softmax values) for predicted characters.\n\n Args:\n chars_logit: chars logits, a tensor with shape\n [batch_size x seq_length x num_char_classes]\n\n Returns:\n A tuple (ids, log_prob, scores), where:\n ids - predicted characters, a int32 tensor with shape\n [batch_size x seq_length];\n log_prob - a log probability of all characters, a float tensor with\n shape [batch_size, seq_length, num_char_classes];\n scores - corresponding confidence scores for characters, a float\n tensor\n with shape [batch_size x seq_length].","docstring_summary":"Returns confidence scores (softmax values) for predicted characters.","docstring_tokens":["Returns","confidence","scores","(","softmax","values",")","for","predicted","characters","."],"function":"def char_predictions(self, chars_logit):\n \"\"\"Returns confidence scores (softmax values) for predicted characters.\n\n Args:\n chars_logit: chars logits, a tensor with shape\n [batch_size x seq_length x num_char_classes]\n\n Returns:\n A tuple (ids, log_prob, scores), where:\n ids - predicted characters, a int32 tensor with shape\n [batch_size x seq_length];\n log_prob - a log probability of all characters, a float tensor with\n shape [batch_size, seq_length, num_char_classes];\n scores - corresponding confidence scores for characters, a float\n tensor\n with shape [batch_size x seq_length].\n \"\"\"\n log_prob = utils.logits_to_log_prob(chars_logit)\n ids = tf.to_int32(tf.argmax(log_prob, axis=2), name='predicted_chars')\n mask = tf.cast(\n slim.one_hot_encoding(ids, self._params.num_char_classes), tf.bool)\n all_scores = tf.nn.softmax(chars_logit)\n selected_scores = tf.boolean_mask(all_scores, mask, name='char_scores')\n scores = tf.reshape(selected_scores, shape=(-1, self._params.seq_length))\n return ids, log_prob, scores","function_tokens":["def","char_predictions","(","self",",","chars_logit",")",":","log_prob","=","utils",".","logits_to_log_prob","(","chars_logit",")","ids","=","tf",".","to_int32","(","tf",".","argmax","(","log_prob",",","axis","=","2",")",",","name","=","'predicted_chars'",")","mask","=","tf",".","cast","(","slim",".","one_hot_encoding","(","ids",",","self",".","_params",".","num_char_classes",")",",","tf",".","bool",")","all_scores","=","tf",".","nn",".","softmax","(","chars_logit",")","selected_scores","=","tf",".","boolean_mask","(","all_scores",",","mask",",","name","=","'char_scores'",")","scores","=","tf",".","reshape","(","selected_scores",",","shape","=","(","-","1",",","self",".","_params",".","seq_length",")",")","return","ids",",","log_prob",",","scores"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L286-L310"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.encode_coordinates_fn","parameters":"(self, net)","argument_list":"","return_statement":"","docstring":"Adds one-hot encoding of coordinates to different views in the networks.\n\n For each \"pixel\" of a feature map it adds a onehot encoded x and y\n coordinates.\n\n Args:\n net: a tensor of shape=[batch_size, height, width, num_features]\n\n Returns:\n a tensor with the same height and width, but altered feature_size.","docstring_summary":"Adds one-hot encoding of coordinates to different views in the networks.","docstring_tokens":["Adds","one","-","hot","encoding","of","coordinates","to","different","views","in","the","networks","."],"function":"def encode_coordinates_fn(self, net):\n \"\"\"Adds one-hot encoding of coordinates to different views in the networks.\n\n For each \"pixel\" of a feature map it adds a onehot encoded x and y\n coordinates.\n\n Args:\n net: a tensor of shape=[batch_size, height, width, num_features]\n\n Returns:\n a tensor with the same height and width, but altered feature_size.\n \"\"\"\n mparams = self._mparams['encode_coordinates_fn']\n if mparams.enabled:\n batch_size, h, w, _ = net.shape.as_list()\n x, y = tf.meshgrid(tf.range(w), tf.range(h))\n w_loc = slim.one_hot_encoding(x, num_classes=w)\n h_loc = slim.one_hot_encoding(y, num_classes=h)\n loc = tf.concat([h_loc, w_loc], 2)\n loc = tf.tile(tf.expand_dims(loc, 0), [batch_size, 1, 1, 1])\n return tf.concat([net, loc], 3)\n else:\n return net","function_tokens":["def","encode_coordinates_fn","(","self",",","net",")",":","mparams","=","self",".","_mparams","[","'encode_coordinates_fn'","]","if","mparams",".","enabled",":","batch_size",",","h",",","w",",","_","=","net",".","shape",".","as_list","(",")","x",",","y","=","tf",".","meshgrid","(","tf",".","range","(","w",")",",","tf",".","range","(","h",")",")","w_loc","=","slim",".","one_hot_encoding","(","x",",","num_classes","=","w",")","h_loc","=","slim",".","one_hot_encoding","(","y",",","num_classes","=","h",")","loc","=","tf",".","concat","(","[","h_loc",",","w_loc","]",",","2",")","loc","=","tf",".","tile","(","tf",".","expand_dims","(","loc",",","0",")",",","[","batch_size",",","1",",","1",",","1","]",")","return","tf",".","concat","(","[","net",",","loc","]",",","3",")","else",":","return","net"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L312-L334"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.create_base","parameters":"(self,\n images,\n labels_one_hot,\n scope='AttentionOcr_v1',\n reuse=None)","argument_list":"","return_statement":"return OutputEndpoints(\n chars_logit=chars_logit,\n chars_log_prob=chars_log_prob,\n predicted_chars=predicted_chars,\n predicted_scores=predicted_scores,\n predicted_text=predicted_text)","docstring":"Creates a base part of the Model (no gradients, losses or summaries).\n\n Args:\n images: A tensor of shape [batch_size, height, width, channels].\n labels_one_hot: Optional (can be None) one-hot encoding for ground truth\n labels. If provided the function will create a model for training.\n scope: Optional variable_scope.\n reuse: whether or not the network and its variables should be reused. To\n be able to reuse 'scope' must be given.\n\n Returns:\n A named tuple OutputEndpoints.","docstring_summary":"Creates a base part of the Model (no gradients, losses or summaries).","docstring_tokens":["Creates","a","base","part","of","the","Model","(","no","gradients","losses","or","summaries",")","."],"function":"def create_base(self,\n images,\n labels_one_hot,\n scope='AttentionOcr_v1',\n reuse=None):\n \"\"\"Creates a base part of the Model (no gradients, losses or summaries).\n\n Args:\n images: A tensor of shape [batch_size, height, width, channels].\n labels_one_hot: Optional (can be None) one-hot encoding for ground truth\n labels. If provided the function will create a model for training.\n scope: Optional variable_scope.\n reuse: whether or not the network and its variables should be reused. To\n be able to reuse 'scope' must be given.\n\n Returns:\n A named tuple OutputEndpoints.\n \"\"\"\n logging.debug('images: %s', images)\n is_training = labels_one_hot is not None\n \n with tf.variable_scope(scope, reuse=reuse):\n views = tf.split(\n value=images, num_or_size_splits=self._params.num_views, axis=2)\n logging.debug('Views=%d single view: %s', len(views), views[0])\n\n nets = [\n self.conv_tower_fn(v, is_training, reuse=(i != 0))\n for i, v in enumerate(views)\n ]\n logging.debug('Conv tower: %s', nets[0])\n\n nets = [self.encode_coordinates_fn(net) for net in nets]\n logging.debug('Conv tower w\/ encoded coordinates: %s', nets[0])\n\n net = self.pool_views_fn(nets)\n logging.debug('Pooled views: %s', net)\n\n chars_logit = self.sequence_logit_fn(net, labels_one_hot)\n logging.debug('chars_logit: %s', chars_logit)\n\n predicted_chars, chars_log_prob, predicted_scores = (\n self.char_predictions(chars_logit))\n if self._charset:\n character_mapper = CharsetMapper(self._charset)\n predicted_text = character_mapper.get_text(predicted_chars)\n else:\n predicted_text = tf.constant([])\n return OutputEndpoints(\n chars_logit=chars_logit,\n chars_log_prob=chars_log_prob,\n predicted_chars=predicted_chars,\n predicted_scores=predicted_scores,\n predicted_text=predicted_text)","function_tokens":["def","create_base","(","self",",","images",",","labels_one_hot",",","scope","=","'AttentionOcr_v1'",",","reuse","=","None",")",":","logging",".","debug","(","'images: %s'",",","images",")","is_training","=","labels_one_hot","is","not","None","with","tf",".","variable_scope","(","scope",",","reuse","=","reuse",")",":","views","=","tf",".","split","(","value","=","images",",","num_or_size_splits","=","self",".","_params",".","num_views",",","axis","=","2",")","logging",".","debug","(","'Views=%d single view: %s'",",","len","(","views",")",",","views","[","0","]",")","nets","=","[","self",".","conv_tower_fn","(","v",",","is_training",",","reuse","=","(","i","!=","0",")",")","for","i",",","v","in","enumerate","(","views",")","]","logging",".","debug","(","'Conv tower: %s'",",","nets","[","0","]",")","nets","=","[","self",".","encode_coordinates_fn","(","net",")","for","net","in","nets","]","logging",".","debug","(","'Conv tower w\/ encoded coordinates: %s'",",","nets","[","0","]",")","net","=","self",".","pool_views_fn","(","nets",")","logging",".","debug","(","'Pooled views: %s'",",","net",")","chars_logit","=","self",".","sequence_logit_fn","(","net",",","labels_one_hot",")","logging",".","debug","(","'chars_logit: %s'",",","chars_logit",")","predicted_chars",",","chars_log_prob",",","predicted_scores","=","(","self",".","char_predictions","(","chars_logit",")",")","if","self",".","_charset",":","character_mapper","=","CharsetMapper","(","self",".","_charset",")","predicted_text","=","character_mapper",".","get_text","(","predicted_chars",")","else",":","predicted_text","=","tf",".","constant","(","[","]",")","return","OutputEndpoints","(","chars_logit","=","chars_logit",",","chars_log_prob","=","chars_log_prob",",","predicted_chars","=","predicted_chars",",","predicted_scores","=","predicted_scores",",","predicted_text","=","predicted_text",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L336-L389"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.create_loss","parameters":"(self, data, endpoints)","argument_list":"","return_statement":"return total_loss","docstring":"Creates all losses required to train the model.\n\n Args:\n data: InputEndpoints namedtuple.\n endpoints: Model namedtuple.\n\n Returns:\n Total loss.","docstring_summary":"Creates all losses required to train the model.","docstring_tokens":["Creates","all","losses","required","to","train","the","model","."],"function":"def create_loss(self, data, endpoints):\n \"\"\"Creates all losses required to train the model.\n\n Args:\n data: InputEndpoints namedtuple.\n endpoints: Model namedtuple.\n\n Returns:\n Total loss.\n \"\"\"\n # NOTE: the return value of ModelLoss is not used directly for the\n # gradient computation because under the hood it calls slim.losses.AddLoss,\n # which registers the loss in an internal collection and later returns it\n # as part of GetTotalLoss. We need to use total loss because model may have\n # multiple losses including regularization losses.\n self.sequence_loss_fn(endpoints.chars_logit, data.labels)\n total_loss = slim.losses.get_total_loss()\n tf.summary.scalar('TotalLoss', total_loss)\n return total_loss","function_tokens":["def","create_loss","(","self",",","data",",","endpoints",")",":","# NOTE: the return value of ModelLoss is not used directly for the","# gradient computation because under the hood it calls slim.losses.AddLoss,","# which registers the loss in an internal collection and later returns it","# as part of GetTotalLoss. We need to use total loss because model may have","# multiple losses including regularization losses.","self",".","sequence_loss_fn","(","endpoints",".","chars_logit",",","data",".","labels",")","total_loss","=","slim",".","losses",".","get_total_loss","(",")","tf",".","summary",".","scalar","(","'TotalLoss'",",","total_loss",")","return","total_loss"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L391-L409"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.label_smoothing_regularization","parameters":"(self, chars_labels, weight=0.1)","argument_list":"","return_statement":"return one_hot_labels * pos_weight + neg_weight","docstring":"Applies a label smoothing regularization.\n\n Uses the same method as in https:\/\/arxiv.org\/abs\/1512.00567.\n\n Args:\n chars_labels: ground truth ids of charactes,\n shape=[batch_size, seq_length];\n weight: label-smoothing regularization weight.\n\n Returns:\n A sensor with the same shape as the input.","docstring_summary":"Applies a label smoothing regularization.","docstring_tokens":["Applies","a","label","smoothing","regularization","."],"function":"def label_smoothing_regularization(self, chars_labels, weight=0.1):\n \"\"\"Applies a label smoothing regularization.\n\n Uses the same method as in https:\/\/arxiv.org\/abs\/1512.00567.\n\n Args:\n chars_labels: ground truth ids of charactes,\n shape=[batch_size, seq_length];\n weight: label-smoothing regularization weight.\n\n Returns:\n A sensor with the same shape as the input.\n \"\"\"\n one_hot_labels = tf.one_hot(\n chars_labels, depth=self._params.num_char_classes, axis=-1)\n pos_weight = 1.0 - weight\n neg_weight = weight \/ self._params.num_char_classes\n return one_hot_labels * pos_weight + neg_weight","function_tokens":["def","label_smoothing_regularization","(","self",",","chars_labels",",","weight","=","0.1",")",":","one_hot_labels","=","tf",".","one_hot","(","chars_labels",",","depth","=","self",".","_params",".","num_char_classes",",","axis","=","-","1",")","pos_weight","=","1.0","-","weight","neg_weight","=","weight","\/","self",".","_params",".","num_char_classes","return","one_hot_labels","*","pos_weight","+","neg_weight"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L411-L428"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.sequence_loss_fn","parameters":"(self, chars_logits, chars_labels)","argument_list":"","return_statement":"","docstring":"Loss function for char sequence.\n\n Depending on values of hyper parameters it applies label smoothing and can\n also ignore all null chars after the first one.\n\n Args:\n chars_logits: logits for predicted characters,\n shape=[batch_size, seq_length, num_char_classes];\n chars_labels: ground truth ids of characters,\n shape=[batch_size, seq_length];\n mparams: method hyper parameters.\n\n Returns:\n A Tensor with shape [batch_size] - the log-perplexity for each sequence.","docstring_summary":"Loss function for char sequence.","docstring_tokens":["Loss","function","for","char","sequence","."],"function":"def sequence_loss_fn(self, chars_logits, chars_labels):\n \"\"\"Loss function for char sequence.\n\n Depending on values of hyper parameters it applies label smoothing and can\n also ignore all null chars after the first one.\n\n Args:\n chars_logits: logits for predicted characters,\n shape=[batch_size, seq_length, num_char_classes];\n chars_labels: ground truth ids of characters,\n shape=[batch_size, seq_length];\n mparams: method hyper parameters.\n\n Returns:\n A Tensor with shape [batch_size] - the log-perplexity for each sequence.\n \"\"\"\n mparams = self._mparams['sequence_loss_fn']\n with tf.variable_scope('sequence_loss_fn\/SLF'):\n if mparams.label_smoothing > 0:\n smoothed_one_hot_labels = self.label_smoothing_regularization(\n chars_labels, mparams.label_smoothing)\n labels_list = tf.unstack(smoothed_one_hot_labels, axis=1)\n else:\n # NOTE: in case of sparse softmax we are not using one-hot\n # encoding.\n labels_list = tf.unstack(chars_labels, axis=1)\n\n batch_size, seq_length, _ = chars_logits.shape.as_list()\n if mparams.ignore_nulls:\n weights = tf.ones((batch_size, seq_length), dtype=tf.float32)\n else:\n # Suppose that reject character is the last in the charset.\n reject_char = tf.constant(\n self._params.num_char_classes - 1,\n shape=(batch_size, seq_length),\n dtype=tf.int64)\n known_char = tf.not_equal(chars_labels, reject_char)\n weights = tf.to_float(known_char)\n\n logits_list = tf.unstack(chars_logits, axis=1)\n weights_list = tf.unstack(weights, axis=1)\n loss = tf.contrib.legacy_seq2seq.sequence_loss(\n logits_list,\n labels_list,\n weights_list,\n softmax_loss_function=get_softmax_loss_fn(mparams.label_smoothing),\n average_across_timesteps=mparams.average_across_timesteps)\n tf.losses.add_loss(loss)\n return loss","function_tokens":["def","sequence_loss_fn","(","self",",","chars_logits",",","chars_labels",")",":","mparams","=","self",".","_mparams","[","'sequence_loss_fn'","]","with","tf",".","variable_scope","(","'sequence_loss_fn\/SLF'",")",":","if","mparams",".","label_smoothing",">","0",":","smoothed_one_hot_labels","=","self",".","label_smoothing_regularization","(","chars_labels",",","mparams",".","label_smoothing",")","labels_list","=","tf",".","unstack","(","smoothed_one_hot_labels",",","axis","=","1",")","else",":","# NOTE: in case of sparse softmax we are not using one-hot","# encoding.","labels_list","=","tf",".","unstack","(","chars_labels",",","axis","=","1",")","batch_size",",","seq_length",",","_","=","chars_logits",".","shape",".","as_list","(",")","if","mparams",".","ignore_nulls",":","weights","=","tf",".","ones","(","(","batch_size",",","seq_length",")",",","dtype","=","tf",".","float32",")","else",":","# Suppose that reject character is the last in the charset.","reject_char","=","tf",".","constant","(","self",".","_params",".","num_char_classes","-","1",",","shape","=","(","batch_size",",","seq_length",")",",","dtype","=","tf",".","int64",")","known_char","=","tf",".","not_equal","(","chars_labels",",","reject_char",")","weights","=","tf",".","to_float","(","known_char",")","logits_list","=","tf",".","unstack","(","chars_logits",",","axis","=","1",")","weights_list","=","tf",".","unstack","(","weights",",","axis","=","1",")","loss","=","tf",".","contrib",".","legacy_seq2seq",".","sequence_loss","(","logits_list",",","labels_list",",","weights_list",",","softmax_loss_function","=","get_softmax_loss_fn","(","mparams",".","label_smoothing",")",",","average_across_timesteps","=","mparams",".","average_across_timesteps",")","tf",".","losses",".","add_loss","(","loss",")","return","loss"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L430-L478"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.create_summaries","parameters":"(self, data, endpoints, charset, is_training)","argument_list":"","return_statement":"","docstring":"Creates all summaries for the model.\n\n Args:\n data: InputEndpoints namedtuple.\n endpoints: OutputEndpoints namedtuple.\n charset: A dictionary with mapping between character codes and\n unicode characters. Use the one provided by a dataset.charset.\n is_training: If True will create summary prefixes for training job,\n otherwise - for evaluation.\n\n Returns:\n A list of evaluation ops","docstring_summary":"Creates all summaries for the model.","docstring_tokens":["Creates","all","summaries","for","the","model","."],"function":"def create_summaries(self, data, endpoints, charset, is_training):\n \"\"\"Creates all summaries for the model.\n\n Args:\n data: InputEndpoints namedtuple.\n endpoints: OutputEndpoints namedtuple.\n charset: A dictionary with mapping between character codes and\n unicode characters. Use the one provided by a dataset.charset.\n is_training: If True will create summary prefixes for training job,\n otherwise - for evaluation.\n\n Returns:\n A list of evaluation ops\n \"\"\"\n\n def sname(label):\n prefix = 'train' if is_training else 'eval'\n return '%s\/%s' % (prefix, label)\n\n max_outputs = 4\n # TODO(gorban): uncomment, when tf.summary.text released.\n charset_mapper = CharsetMapper(charset)\n pr_text = charset_mapper.get_text(\n endpoints.predicted_chars[:max_outputs,:])\n tf.summary.text(sname('text\/pr'), pr_text)\n gt_text = charset_mapper.get_text(data.labels[:max_outputs,:])\n tf.summary.text(sname('text\/gt'), gt_text)\n tf.summary.image(sname('image'), data.images, max_outputs=max_outputs)\n\n if is_training:\n tf.summary.image(\n sname('image\/orig'), data.images_orig, max_outputs=max_outputs)\n for var in tf.trainable_variables():\n tf.summary.histogram(var.op.name, var)\n return None\n\n else:\n names_to_values = {}\n names_to_updates = {}\n\n def use_metric(name, value_update_tuple):\n names_to_values[name] = value_update_tuple[0]\n names_to_updates[name] = value_update_tuple[1]\n\n use_metric('CharacterAccuracy',\n metrics.char_accuracy(\n endpoints.predicted_chars,\n data.labels,\n streaming=True,\n rej_char=self._params.null_code))\n # Sequence accuracy computed by cutting sequence at the first null char\n use_metric('SequenceAccuracy',\n metrics.sequence_accuracy(\n endpoints.predicted_chars,\n data.labels,\n streaming=True,\n rej_char=self._params.null_code))\n\n for name, value in names_to_values.items():\n summary_name = 'eval\/' + name\n tf.summary.scalar(summary_name, tf.Print(value, [value], summary_name))\n return list(names_to_updates.values())","function_tokens":["def","create_summaries","(","self",",","data",",","endpoints",",","charset",",","is_training",")",":","def","sname","(","label",")",":","prefix","=","'train'","if","is_training","else","'eval'","return","'%s\/%s'","%","(","prefix",",","label",")","max_outputs","=","4","# TODO(gorban): uncomment, when tf.summary.text released.","charset_mapper","=","CharsetMapper","(","charset",")","pr_text","=","charset_mapper",".","get_text","(","endpoints",".","predicted_chars","[",":","max_outputs",",",":","]",")","tf",".","summary",".","text","(","sname","(","'text\/pr'",")",",","pr_text",")","gt_text","=","charset_mapper",".","get_text","(","data",".","labels","[",":","max_outputs",",",":","]",")","tf",".","summary",".","text","(","sname","(","'text\/gt'",")",",","gt_text",")","tf",".","summary",".","image","(","sname","(","'image'",")",",","data",".","images",",","max_outputs","=","max_outputs",")","if","is_training",":","tf",".","summary",".","image","(","sname","(","'image\/orig'",")",",","data",".","images_orig",",","max_outputs","=","max_outputs",")","for","var","in","tf",".","trainable_variables","(",")",":","tf",".","summary",".","histogram","(","var",".","op",".","name",",","var",")","return","None","else",":","names_to_values","=","{","}","names_to_updates","=","{","}","def","use_metric","(","name",",","value_update_tuple",")",":","names_to_values","[","name","]","=","value_update_tuple","[","0","]","names_to_updates","[","name","]","=","value_update_tuple","[","1","]","use_metric","(","'CharacterAccuracy'",",","metrics",".","char_accuracy","(","endpoints",".","predicted_chars",",","data",".","labels",",","streaming","=","True",",","rej_char","=","self",".","_params",".","null_code",")",")","# Sequence accuracy computed by cutting sequence at the first null char","use_metric","(","'SequenceAccuracy'",",","metrics",".","sequence_accuracy","(","endpoints",".","predicted_chars",",","data",".","labels",",","streaming","=","True",",","rej_char","=","self",".","_params",".","null_code",")",")","for","name",",","value","in","names_to_values",".","items","(",")",":","summary_name","=","'eval\/'","+","name","tf",".","summary",".","scalar","(","summary_name",",","tf",".","Print","(","value",",","[","value","]",",","summary_name",")",")","return","list","(","names_to_updates",".","values","(",")",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L480-L541"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/model.py","language":"python","identifier":"Model.create_init_fn_to_restore","parameters":"(self, master_checkpoint,\n inception_checkpoint=None)","argument_list":"","return_statement":"return init_assign_fn","docstring":"Creates an init operations to restore weights from various checkpoints.\n\n Args:\n master_checkpoint: path to a checkpoint which contains all weights for\n the whole model.\n inception_checkpoint: path to a checkpoint which contains weights for the\n inception part only.\n\n Returns:\n a function to run initialization ops.","docstring_summary":"Creates an init operations to restore weights from various checkpoints.","docstring_tokens":["Creates","an","init","operations","to","restore","weights","from","various","checkpoints","."],"function":"def create_init_fn_to_restore(self, master_checkpoint,\n inception_checkpoint=None):\n \"\"\"Creates an init operations to restore weights from various checkpoints.\n\n Args:\n master_checkpoint: path to a checkpoint which contains all weights for\n the whole model.\n inception_checkpoint: path to a checkpoint which contains weights for the\n inception part only.\n\n Returns:\n a function to run initialization ops.\n \"\"\"\n all_assign_ops = []\n all_feed_dict = {}\n\n def assign_from_checkpoint(variables, checkpoint):\n logging.info('Request to re-store %d weights from %s',\n len(variables), checkpoint)\n if not variables:\n logging.error('Can\\'t find any variables to restore.')\n sys.exit(1)\n assign_op, feed_dict = slim.assign_from_checkpoint(checkpoint, variables)\n all_assign_ops.append(assign_op)\n all_feed_dict.update(feed_dict)\n\n logging.info('variables_to_restore:\\n%s' % utils.variables_to_restore().keys())\n logging.info('moving_average_variables:\\n%s' % [v.op.name for v in tf.moving_average_variables()])\n logging.info('trainable_variables:\\n%s' % [v.op.name for v in tf.trainable_variables()])\n if master_checkpoint:\n assign_from_checkpoint(utils.variables_to_restore(), master_checkpoint)\n\n if inception_checkpoint:\n variables = utils.variables_to_restore(\n 'AttentionOcr_v1\/conv_tower_fn\/INCE', strip_scope=True)\n assign_from_checkpoint(variables, inception_checkpoint)\n\n def init_assign_fn(sess):\n logging.info('Restoring checkpoint(s)')\n sess.run(all_assign_ops, all_feed_dict)\n\n return init_assign_fn","function_tokens":["def","create_init_fn_to_restore","(","self",",","master_checkpoint",",","inception_checkpoint","=","None",")",":","all_assign_ops","=","[","]","all_feed_dict","=","{","}","def","assign_from_checkpoint","(","variables",",","checkpoint",")",":","logging",".","info","(","'Request to re-store %d weights from %s'",",","len","(","variables",")",",","checkpoint",")","if","not","variables",":","logging",".","error","(","'Can\\'t find any variables to restore.'",")","sys",".","exit","(","1",")","assign_op",",","feed_dict","=","slim",".","assign_from_checkpoint","(","checkpoint",",","variables",")","all_assign_ops",".","append","(","assign_op",")","all_feed_dict",".","update","(","feed_dict",")","logging",".","info","(","'variables_to_restore:\\n%s'","%","utils",".","variables_to_restore","(",")",".","keys","(",")",")","logging",".","info","(","'moving_average_variables:\\n%s'","%","[","v",".","op",".","name","for","v","in","tf",".","moving_average_variables","(",")","]",")","logging",".","info","(","'trainable_variables:\\n%s'","%","[","v",".","op",".","name","for","v","in","tf",".","trainable_variables","(",")","]",")","if","master_checkpoint",":","assign_from_checkpoint","(","utils",".","variables_to_restore","(",")",",","master_checkpoint",")","if","inception_checkpoint",":","variables","=","utils",".","variables_to_restore","(","'AttentionOcr_v1\/conv_tower_fn\/INCE'",",","strip_scope","=","True",")","assign_from_checkpoint","(","variables",",","inception_checkpoint",")","def","init_assign_fn","(","sess",")",":","logging",".","info","(","'Restoring checkpoint(s)'",")","sess",".","run","(","all_assign_ops",",","all_feed_dict",")","return","init_assign_fn"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/model.py#L543-L584"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"orthogonal_initializer","parameters":"(shape, dtype=tf.float32, *args, **kwargs)","argument_list":"","return_statement":"return tf.constant(w.reshape(shape), dtype=dtype)","docstring":"Generates orthonormal matrices with random values.\n\n Orthonormal initialization is important for RNNs:\n http:\/\/arxiv.org\/abs\/1312.6120\n http:\/\/smerity.com\/articles\/2016\/orthogonal_init.html\n\n For non-square shapes the returned matrix will be semi-orthonormal: if the\n number of columns exceeds the number of rows, then the rows are orthonormal\n vectors; but if the number of rows exceeds the number of columns, then the\n columns are orthonormal vectors.\n\n We use SVD decomposition to generate an orthonormal matrix with random\n values. The same way as it is done in the Lasagne library for Theano. Note\n that both u and v returned by the svd are orthogonal and random. We just need\n to pick one with the right shape.\n\n Args:\n shape: a shape of the tensor matrix to initialize.\n dtype: a dtype of the initialized tensor.\n *args: not used.\n **kwargs: not used.\n\n Returns:\n An initialized tensor.","docstring_summary":"Generates orthonormal matrices with random values.","docstring_tokens":["Generates","orthonormal","matrices","with","random","values","."],"function":"def orthogonal_initializer(shape, dtype=tf.float32, *args, **kwargs):\n \"\"\"Generates orthonormal matrices with random values.\n\n Orthonormal initialization is important for RNNs:\n http:\/\/arxiv.org\/abs\/1312.6120\n http:\/\/smerity.com\/articles\/2016\/orthogonal_init.html\n\n For non-square shapes the returned matrix will be semi-orthonormal: if the\n number of columns exceeds the number of rows, then the rows are orthonormal\n vectors; but if the number of rows exceeds the number of columns, then the\n columns are orthonormal vectors.\n\n We use SVD decomposition to generate an orthonormal matrix with random\n values. The same way as it is done in the Lasagne library for Theano. Note\n that both u and v returned by the svd are orthogonal and random. We just need\n to pick one with the right shape.\n\n Args:\n shape: a shape of the tensor matrix to initialize.\n dtype: a dtype of the initialized tensor.\n *args: not used.\n **kwargs: not used.\n\n Returns:\n An initialized tensor.\n \"\"\"\n del args\n del kwargs\n flat_shape = (shape[0], np.prod(shape[1:]))\n w = np.random.randn(*flat_shape)\n u, _, v = np.linalg.svd(w, full_matrices=False)\n w = u if u.shape == flat_shape else v\n return tf.constant(w.reshape(shape), dtype=dtype)","function_tokens":["def","orthogonal_initializer","(","shape",",","dtype","=","tf",".","float32",",","*","args",",","*","*","kwargs",")",":","del","args","del","kwargs","flat_shape","=","(","shape","[","0","]",",","np",".","prod","(","shape","[","1",":","]",")",")","w","=","np",".","random",".","randn","(","*","flat_shape",")","u",",","_",",","v","=","np",".","linalg",".","svd","(","w",",","full_matrices","=","False",")","w","=","u","if","u",".","shape","==","flat_shape","else","v","return","tf",".","constant","(","w",".","reshape","(","shape",")",",","dtype","=","dtype",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L48-L80"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"get_layer_class","parameters":"(use_attention, use_autoregression)","argument_list":"","return_statement":"return layer_class","docstring":"A convenience function to get a layer class based on requirements.\n\n Args:\n use_attention: if True a returned class will use attention.\n use_autoregression: if True a returned class will use auto regression.\n\n Returns:\n One of available sequence layers (child classes for SequenceLayerBase).","docstring_summary":"A convenience function to get a layer class based on requirements.","docstring_tokens":["A","convenience","function","to","get","a","layer","class","based","on","requirements","."],"function":"def get_layer_class(use_attention, use_autoregression):\n \"\"\"A convenience function to get a layer class based on requirements.\n\n Args:\n use_attention: if True a returned class will use attention.\n use_autoregression: if True a returned class will use auto regression.\n\n Returns:\n One of available sequence layers (child classes for SequenceLayerBase).\n \"\"\"\n if use_attention and use_autoregression:\n layer_class = AttentionWithAutoregression\n elif use_attention and not use_autoregression:\n layer_class = Attention\n elif not use_attention and not use_autoregression:\n layer_class = NetSlice\n elif not use_attention and use_autoregression:\n layer_class = NetSliceWithAutoregression\n else:\n raise AssertionError('Unsupported sequence layer class')\n\n logging.debug('Use %s as a layer class', layer_class.__name__)\n return layer_class","function_tokens":["def","get_layer_class","(","use_attention",",","use_autoregression",")",":","if","use_attention","and","use_autoregression",":","layer_class","=","AttentionWithAutoregression","elif","use_attention","and","not","use_autoregression",":","layer_class","=","Attention","elif","not","use_attention","and","not","use_autoregression",":","layer_class","=","NetSlice","elif","not","use_attention","and","use_autoregression",":","layer_class","=","NetSliceWithAutoregression","else",":","raise","AssertionError","(","'Unsupported sequence layer class'",")","logging",".","debug","(","'Use %s as a layer class'",",","layer_class",".","__name__",")","return","layer_class"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L400-L422"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.__init__","parameters":"(self, net, labels_one_hot, model_params, method_params)","argument_list":"","return_statement":"","docstring":"Stores argument in member variable for further use.\n\n Args:\n net: A tensor with shape [batch_size, num_features, feature_size] which\n contains some extracted image features.\n labels_one_hot: An optional (can be None) ground truth labels for the\n input features. Is a tensor with shape\n [batch_size, seq_length, num_char_classes]\n model_params: A namedtuple with model parameters (model.ModelParams).\n method_params: A SequenceLayerParams instance.","docstring_summary":"Stores argument in member variable for further use.","docstring_tokens":["Stores","argument","in","member","variable","for","further","use","."],"function":"def __init__(self, net, labels_one_hot, model_params, method_params):\n \"\"\"Stores argument in member variable for further use.\n\n Args:\n net: A tensor with shape [batch_size, num_features, feature_size] which\n contains some extracted image features.\n labels_one_hot: An optional (can be None) ground truth labels for the\n input features. Is a tensor with shape\n [batch_size, seq_length, num_char_classes]\n model_params: A namedtuple with model parameters (model.ModelParams).\n method_params: A SequenceLayerParams instance.\n \"\"\"\n self._params = model_params\n self._mparams = method_params\n self._net = net\n self._labels_one_hot = labels_one_hot\n self._batch_size = net.get_shape().dims[0].value\n\n # Initialize parameters for char logits which will be computed on the fly\n # inside an LSTM decoder.\n self._char_logits = {}\n regularizer = slim.l2_regularizer(self._mparams.weight_decay)\n self._softmax_w = slim.model_variable(\n 'softmax_w',\n [self._mparams.num_lstm_units, self._params.num_char_classes],\n initializer=orthogonal_initializer,\n regularizer=regularizer)\n self._softmax_b = slim.model_variable(\n 'softmax_b', [self._params.num_char_classes],\n initializer=tf.zeros_initializer(),\n regularizer=regularizer)","function_tokens":["def","__init__","(","self",",","net",",","labels_one_hot",",","model_params",",","method_params",")",":","self",".","_params","=","model_params","self",".","_mparams","=","method_params","self",".","_net","=","net","self",".","_labels_one_hot","=","labels_one_hot","self",".","_batch_size","=","net",".","get_shape","(",")",".","dims","[","0","]",".","value","# Initialize parameters for char logits which will be computed on the fly","# inside an LSTM decoder.","self",".","_char_logits","=","{","}","regularizer","=","slim",".","l2_regularizer","(","self",".","_mparams",".","weight_decay",")","self",".","_softmax_w","=","slim",".","model_variable","(","'softmax_w'",",","[","self",".","_mparams",".","num_lstm_units",",","self",".","_params",".","num_char_classes","]",",","initializer","=","orthogonal_initializer",",","regularizer","=","regularizer",")","self",".","_softmax_b","=","slim",".","model_variable","(","'softmax_b'",",","[","self",".","_params",".","num_char_classes","]",",","initializer","=","tf",".","zeros_initializer","(",")",",","regularizer","=","regularizer",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L98-L128"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.get_train_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"","docstring":"Returns a sample to be used to predict a character during training.\n\n This function is used as a loop_function for an RNN decoder.\n\n Args:\n prev: output tensor from previous step of the RNN. A tensor with shape:\n [batch_size, num_char_classes].\n i: index of a character in the output sequence.\n\n Returns:\n A tensor with shape [batch_size, ?] - depth depends on implementation\n details.","docstring_summary":"Returns a sample to be used to predict a character during training.","docstring_tokens":["Returns","a","sample","to","be","used","to","predict","a","character","during","training","."],"function":"def get_train_input(self, prev, i):\n \"\"\"Returns a sample to be used to predict a character during training.\n\n This function is used as a loop_function for an RNN decoder.\n\n Args:\n prev: output tensor from previous step of the RNN. A tensor with shape:\n [batch_size, num_char_classes].\n i: index of a character in the output sequence.\n\n Returns:\n A tensor with shape [batch_size, ?] - depth depends on implementation\n details.\n \"\"\"\n pass","function_tokens":["def","get_train_input","(","self",",","prev",",","i",")",":","pass"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L131-L145"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.get_eval_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"","docstring":"Returns a sample to be used to predict a character during inference.\n\n This function is used as a loop_function for an RNN decoder.\n\n Args:\n prev: output tensor from previous step of the RNN. A tensor with shape:\n [batch_size, num_char_classes].\n i: index of a character in the output sequence.\n\n Returns:\n A tensor with shape [batch_size, ?] - depth depends on implementation\n details.","docstring_summary":"Returns a sample to be used to predict a character during inference.","docstring_tokens":["Returns","a","sample","to","be","used","to","predict","a","character","during","inference","."],"function":"def get_eval_input(self, prev, i):\n \"\"\"Returns a sample to be used to predict a character during inference.\n\n This function is used as a loop_function for an RNN decoder.\n\n Args:\n prev: output tensor from previous step of the RNN. A tensor with shape:\n [batch_size, num_char_classes].\n i: index of a character in the output sequence.\n\n Returns:\n A tensor with shape [batch_size, ?] - depth depends on implementation\n details.\n \"\"\"\n raise AssertionError('Not implemented')","function_tokens":["def","get_eval_input","(","self",",","prev",",","i",")",":","raise","AssertionError","(","'Not implemented'",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L148-L162"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.unroll_cell","parameters":"(self, decoder_inputs, initial_state, loop_function, cell)","argument_list":"","return_statement":"","docstring":"Unrolls an RNN cell for all inputs.\n\n This is a placeholder to call some RNN decoder. It has a similar to\n tf.seq2seq.rnn_decode interface.\n\n Args:\n decoder_inputs: A list of 2D Tensors* [batch_size x input_size]. In fact,\n most of existing decoders in presence of a loop_function use only the\n first element to determine batch_size and length of the list to\n determine number of steps.\n initial_state: 2D Tensor with shape [batch_size x cell.state_size].\n loop_function: function will be applied to the i-th output in order to\n generate the i+1-st input (see self.get_input).\n cell: rnn_cell.RNNCell defining the cell function and size.\n\n Returns:\n A tuple of the form (outputs, state), where:\n outputs: A list of character logits of the same length as\n decoder_inputs of 2D Tensors with shape [batch_size x num_characters].\n state: The state of each cell at the final time-step.\n It is a 2D Tensor of shape [batch_size x cell.state_size].","docstring_summary":"Unrolls an RNN cell for all inputs.","docstring_tokens":["Unrolls","an","RNN","cell","for","all","inputs","."],"function":"def unroll_cell(self, decoder_inputs, initial_state, loop_function, cell):\n \"\"\"Unrolls an RNN cell for all inputs.\n\n This is a placeholder to call some RNN decoder. It has a similar to\n tf.seq2seq.rnn_decode interface.\n\n Args:\n decoder_inputs: A list of 2D Tensors* [batch_size x input_size]. In fact,\n most of existing decoders in presence of a loop_function use only the\n first element to determine batch_size and length of the list to\n determine number of steps.\n initial_state: 2D Tensor with shape [batch_size x cell.state_size].\n loop_function: function will be applied to the i-th output in order to\n generate the i+1-st input (see self.get_input).\n cell: rnn_cell.RNNCell defining the cell function and size.\n\n Returns:\n A tuple of the form (outputs, state), where:\n outputs: A list of character logits of the same length as\n decoder_inputs of 2D Tensors with shape [batch_size x num_characters].\n state: The state of each cell at the final time-step.\n It is a 2D Tensor of shape [batch_size x cell.state_size].\n \"\"\"\n pass","function_tokens":["def","unroll_cell","(","self",",","decoder_inputs",",","initial_state",",","loop_function",",","cell",")",":","pass"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L165-L188"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.is_training","parameters":"(self)","argument_list":"","return_statement":"return self._labels_one_hot is not None","docstring":"Returns True if the layer is created for training stage.","docstring_summary":"Returns True if the layer is created for training stage.","docstring_tokens":["Returns","True","if","the","layer","is","created","for","training","stage","."],"function":"def is_training(self):\n \"\"\"Returns True if the layer is created for training stage.\"\"\"\n return self._labels_one_hot is not None","function_tokens":["def","is_training","(","self",")",":","return","self",".","_labels_one_hot","is","not","None"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L190-L192"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.char_logit","parameters":"(self, inputs, char_index)","argument_list":"","return_statement":"return self._char_logits[char_index]","docstring":"Creates logits for a character if required.\n\n Args:\n inputs: A tensor with shape [batch_size, ?] (depth is implementation\n dependent).\n char_index: A integer index of a character in the output sequence.\n\n Returns:\n A tensor with shape [batch_size, num_char_classes]","docstring_summary":"Creates logits for a character if required.","docstring_tokens":["Creates","logits","for","a","character","if","required","."],"function":"def char_logit(self, inputs, char_index):\n \"\"\"Creates logits for a character if required.\n\n Args:\n inputs: A tensor with shape [batch_size, ?] (depth is implementation\n dependent).\n char_index: A integer index of a character in the output sequence.\n\n Returns:\n A tensor with shape [batch_size, num_char_classes]\n \"\"\"\n if char_index not in self._char_logits:\n self._char_logits[char_index] = tf.nn.xw_plus_b(inputs, self._softmax_w,\n self._softmax_b)\n return self._char_logits[char_index]","function_tokens":["def","char_logit","(","self",",","inputs",",","char_index",")",":","if","char_index","not","in","self",".","_char_logits",":","self",".","_char_logits","[","char_index","]","=","tf",".","nn",".","xw_plus_b","(","inputs",",","self",".","_softmax_w",",","self",".","_softmax_b",")","return","self",".","_char_logits","[","char_index","]"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L194-L208"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.char_one_hot","parameters":"(self, logit)","argument_list":"","return_statement":"return slim.one_hot_encoding(prediction, self._params.num_char_classes)","docstring":"Creates one hot encoding for a logit of a character.\n\n Args:\n logit: A tensor with shape [batch_size, num_char_classes].\n\n Returns:\n A tensor with shape [batch_size, num_char_classes]","docstring_summary":"Creates one hot encoding for a logit of a character.","docstring_tokens":["Creates","one","hot","encoding","for","a","logit","of","a","character","."],"function":"def char_one_hot(self, logit):\n \"\"\"Creates one hot encoding for a logit of a character.\n\n Args:\n logit: A tensor with shape [batch_size, num_char_classes].\n\n Returns:\n A tensor with shape [batch_size, num_char_classes]\n \"\"\"\n prediction = tf.argmax(logit, axis=1)\n return slim.one_hot_encoding(prediction, self._params.num_char_classes)","function_tokens":["def","char_one_hot","(","self",",","logit",")",":","prediction","=","tf",".","argmax","(","logit",",","axis","=","1",")","return","slim",".","one_hot_encoding","(","prediction",",","self",".","_params",".","num_char_classes",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L210-L220"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.get_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"","docstring":"A wrapper for get_train_input and get_eval_input.\n\n Args:\n prev: output tensor from previous step of the RNN. A tensor with shape:\n [batch_size, num_char_classes].\n i: index of a character in the output sequence.\n\n Returns:\n A tensor with shape [batch_size, ?] - depth depends on implementation\n details.","docstring_summary":"A wrapper for get_train_input and get_eval_input.","docstring_tokens":["A","wrapper","for","get_train_input","and","get_eval_input","."],"function":"def get_input(self, prev, i):\n \"\"\"A wrapper for get_train_input and get_eval_input.\n\n Args:\n prev: output tensor from previous step of the RNN. A tensor with shape:\n [batch_size, num_char_classes].\n i: index of a character in the output sequence.\n\n Returns:\n A tensor with shape [batch_size, ?] - depth depends on implementation\n details.\n \"\"\"\n if self.is_training():\n return self.get_train_input(prev, i)\n else:\n return self.get_eval_input(prev, i)","function_tokens":["def","get_input","(","self",",","prev",",","i",")",":","if","self",".","is_training","(",")",":","return","self",".","get_train_input","(","prev",",","i",")","else",":","return","self",".","get_eval_input","(","prev",",","i",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L222-L237"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"SequenceLayerBase.create_logits","parameters":"(self)","argument_list":"","return_statement":"return tf.concat(logits_list, 1)","docstring":"Creates character sequence logits for a net specified in the constructor.\n\n A \"main\" method for the sequence layer which glues together all pieces.\n\n Returns:\n A tensor with shape [batch_size, seq_length, num_char_classes].","docstring_summary":"Creates character sequence logits for a net specified in the constructor.","docstring_tokens":["Creates","character","sequence","logits","for","a","net","specified","in","the","constructor","."],"function":"def create_logits(self):\n \"\"\"Creates character sequence logits for a net specified in the constructor.\n\n A \"main\" method for the sequence layer which glues together all pieces.\n\n Returns:\n A tensor with shape [batch_size, seq_length, num_char_classes].\n \"\"\"\n with tf.variable_scope('LSTM'):\n first_label = self.get_input(prev=None, i=0)\n decoder_inputs = [first_label] + [None] * (self._params.seq_length - 1)\n lstm_cell = tf.contrib.rnn.LSTMCell(\n self._mparams.num_lstm_units,\n use_peepholes=False,\n cell_clip=self._mparams.lstm_state_clip_value,\n state_is_tuple=True,\n initializer=orthogonal_initializer)\n lstm_outputs, _ = self.unroll_cell(\n decoder_inputs=decoder_inputs,\n initial_state=lstm_cell.zero_state(self._batch_size, tf.float32),\n loop_function=self.get_input,\n cell=lstm_cell)\n\n with tf.variable_scope('logits'):\n logits_list = [\n tf.expand_dims(self.char_logit(logit, i), dim=1)\n for i, logit in enumerate(lstm_outputs)\n ]\n\n return tf.concat(logits_list, 1)","function_tokens":["def","create_logits","(","self",")",":","with","tf",".","variable_scope","(","'LSTM'",")",":","first_label","=","self",".","get_input","(","prev","=","None",",","i","=","0",")","decoder_inputs","=","[","first_label","]","+","[","None","]","*","(","self",".","_params",".","seq_length","-","1",")","lstm_cell","=","tf",".","contrib",".","rnn",".","LSTMCell","(","self",".","_mparams",".","num_lstm_units",",","use_peepholes","=","False",",","cell_clip","=","self",".","_mparams",".","lstm_state_clip_value",",","state_is_tuple","=","True",",","initializer","=","orthogonal_initializer",")","lstm_outputs",",","_","=","self",".","unroll_cell","(","decoder_inputs","=","decoder_inputs",",","initial_state","=","lstm_cell",".","zero_state","(","self",".","_batch_size",",","tf",".","float32",")",",","loop_function","=","self",".","get_input",",","cell","=","lstm_cell",")","with","tf",".","variable_scope","(","'logits'",")",":","logits_list","=","[","tf",".","expand_dims","(","self",".","char_logit","(","logit",",","i",")",",","dim","=","1",")","for","i",",","logit","in","enumerate","(","lstm_outputs",")","]","return","tf",".","concat","(","logits_list",",","1",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L239-L268"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"NetSlice.get_image_feature","parameters":"(self, char_index)","argument_list":"","return_statement":"return feature","docstring":"Returns a subset of image features for a character.\n\n Args:\n char_index: an index of a character.\n\n Returns:\n A tensor with shape [batch_size, ?]. The output depth depends on the\n depth of input net.","docstring_summary":"Returns a subset of image features for a character.","docstring_tokens":["Returns","a","subset","of","image","features","for","a","character","."],"function":"def get_image_feature(self, char_index):\n \"\"\"Returns a subset of image features for a character.\n\n Args:\n char_index: an index of a character.\n\n Returns:\n A tensor with shape [batch_size, ?]. The output depth depends on the\n depth of input net.\n \"\"\"\n batch_size, features_num, _ = [d.value for d in self._net.get_shape()]\n slice_len = int(features_num \/ self._params.seq_length)\n # In case when features_num != seq_length, we just pick a subset of image\n # features, this choice is arbitrary and there is no intuitive geometrical\n # interpretation. If features_num is not dividable by seq_length there will\n # be unused image features.\n net_slice = self._net[:, char_index:char_index + slice_len, :]\n feature = tf.reshape(net_slice, [batch_size, -1])\n logging.debug('Image feature: %s', feature)\n return feature","function_tokens":["def","get_image_feature","(","self",",","char_index",")",":","batch_size",",","features_num",",","_","=","[","d",".","value","for","d","in","self",".","_net",".","get_shape","(",")","]","slice_len","=","int","(","features_num","\/","self",".","_params",".","seq_length",")","# In case when features_num != seq_length, we just pick a subset of image","# features, this choice is arbitrary and there is no intuitive geometrical","# interpretation. If features_num is not dividable by seq_length there will","# be unused image features.","net_slice","=","self",".","_net","[",":",",","char_index",":","char_index","+","slice_len",",",":","]","feature","=","tf",".","reshape","(","net_slice",",","[","batch_size",",","-","1","]",")","logging",".","debug","(","'Image feature: %s'",",","feature",")","return","feature"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L280-L299"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"NetSlice.get_eval_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"return self.get_image_feature(i)","docstring":"See SequenceLayerBase.get_eval_input for details.","docstring_summary":"See SequenceLayerBase.get_eval_input for details.","docstring_tokens":["See","SequenceLayerBase",".","get_eval_input","for","details","."],"function":"def get_eval_input(self, prev, i):\n \"\"\"See SequenceLayerBase.get_eval_input for details.\"\"\"\n del prev\n return self.get_image_feature(i)","function_tokens":["def","get_eval_input","(","self",",","prev",",","i",")",":","del","prev","return","self",".","get_image_feature","(","i",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L301-L304"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"NetSlice.get_train_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"return self.get_eval_input(prev, i)","docstring":"See SequenceLayerBase.get_train_input for details.","docstring_summary":"See SequenceLayerBase.get_train_input for details.","docstring_tokens":["See","SequenceLayerBase",".","get_train_input","for","details","."],"function":"def get_train_input(self, prev, i):\n \"\"\"See SequenceLayerBase.get_train_input for details.\"\"\"\n return self.get_eval_input(prev, i)","function_tokens":["def","get_train_input","(","self",",","prev",",","i",")",":","return","self",".","get_eval_input","(","prev",",","i",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L306-L308"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"NetSlice.unroll_cell","parameters":"(self, decoder_inputs, initial_state, loop_function, cell)","argument_list":"","return_statement":"return tf.contrib.legacy_seq2seq.rnn_decoder(\n decoder_inputs=decoder_inputs,\n initial_state=initial_state,\n cell=cell,\n loop_function=self.get_input)","docstring":"See SequenceLayerBase.unroll_cell for details.","docstring_summary":"See SequenceLayerBase.unroll_cell for details.","docstring_tokens":["See","SequenceLayerBase",".","unroll_cell","for","details","."],"function":"def unroll_cell(self, decoder_inputs, initial_state, loop_function, cell):\n \"\"\"See SequenceLayerBase.unroll_cell for details.\"\"\"\n return tf.contrib.legacy_seq2seq.rnn_decoder(\n decoder_inputs=decoder_inputs,\n initial_state=initial_state,\n cell=cell,\n loop_function=self.get_input)","function_tokens":["def","unroll_cell","(","self",",","decoder_inputs",",","initial_state",",","loop_function",",","cell",")",":","return","tf",".","contrib",".","legacy_seq2seq",".","rnn_decoder","(","decoder_inputs","=","decoder_inputs",",","initial_state","=","initial_state",",","cell","=","cell",",","loop_function","=","self",".","get_input",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L310-L316"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"NetSliceWithAutoregression.get_eval_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"return tf.concat([image_feature, prev], 1)","docstring":"See SequenceLayerBase.get_eval_input for details.","docstring_summary":"See SequenceLayerBase.get_eval_input for details.","docstring_tokens":["See","SequenceLayerBase",".","get_eval_input","for","details","."],"function":"def get_eval_input(self, prev, i):\n \"\"\"See SequenceLayerBase.get_eval_input for details.\"\"\"\n if i == 0:\n prev = self._zero_label\n else:\n logit = self.char_logit(prev, char_index=i - 1)\n prev = self.char_one_hot(logit)\n image_feature = self.get_image_feature(char_index=i)\n return tf.concat([image_feature, prev], 1)","function_tokens":["def","get_eval_input","(","self",",","prev",",","i",")",":","if","i","==","0",":","prev","=","self",".","_zero_label","else",":","logit","=","self",".","char_logit","(","prev",",","char_index","=","i","-","1",")","prev","=","self",".","char_one_hot","(","logit",")","image_feature","=","self",".","get_image_feature","(","char_index","=","i",")","return","tf",".","concat","(","[","image_feature",",","prev","]",",","1",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L329-L337"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"NetSliceWithAutoregression.get_train_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"return tf.concat([image_feature, prev], 1)","docstring":"See SequenceLayerBase.get_train_input for details.","docstring_summary":"See SequenceLayerBase.get_train_input for details.","docstring_tokens":["See","SequenceLayerBase",".","get_train_input","for","details","."],"function":"def get_train_input(self, prev, i):\n \"\"\"See SequenceLayerBase.get_train_input for details.\"\"\"\n if i == 0:\n prev = self._zero_label\n else:\n prev = self._labels_one_hot[:, i - 1, :]\n image_feature = self.get_image_feature(i)\n return tf.concat([image_feature, prev], 1)","function_tokens":["def","get_train_input","(","self",",","prev",",","i",")",":","if","i","==","0",":","prev","=","self",".","_zero_label","else",":","prev","=","self",".","_labels_one_hot","[",":",",","i","-","1",",",":","]","image_feature","=","self",".","get_image_feature","(","i",")","return","tf",".","concat","(","[","image_feature",",","prev","]",",","1",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L339-L346"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"Attention.get_eval_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"return self._zero_label","docstring":"See SequenceLayerBase.get_eval_input for details.","docstring_summary":"See SequenceLayerBase.get_eval_input for details.","docstring_tokens":["See","SequenceLayerBase",".","get_eval_input","for","details","."],"function":"def get_eval_input(self, prev, i):\n \"\"\"See SequenceLayerBase.get_eval_input for details.\"\"\"\n del prev, i\n # The attention_decoder will fetch image features from the net, no need for\n # extra inputs.\n return self._zero_label","function_tokens":["def","get_eval_input","(","self",",","prev",",","i",")",":","del","prev",",","i","# The attention_decoder will fetch image features from the net, no need for","# extra inputs.","return","self",".","_zero_label"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L357-L362"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"Attention.get_train_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"return self.get_eval_input(prev, i)","docstring":"See SequenceLayerBase.get_train_input for details.","docstring_summary":"See SequenceLayerBase.get_train_input for details.","docstring_tokens":["See","SequenceLayerBase",".","get_train_input","for","details","."],"function":"def get_train_input(self, prev, i):\n \"\"\"See SequenceLayerBase.get_train_input for details.\"\"\"\n return self.get_eval_input(prev, i)","function_tokens":["def","get_train_input","(","self",",","prev",",","i",")",":","return","self",".","get_eval_input","(","prev",",","i",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L364-L366"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"AttentionWithAutoregression.get_train_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"","docstring":"See SequenceLayerBase.get_train_input for details.","docstring_summary":"See SequenceLayerBase.get_train_input for details.","docstring_tokens":["See","SequenceLayerBase",".","get_train_input","for","details","."],"function":"def get_train_input(self, prev, i):\n \"\"\"See SequenceLayerBase.get_train_input for details.\"\"\"\n if i == 0:\n return self._zero_label\n else:\n # TODO(gorban): update to gradually introduce gt labels.\n return self._labels_one_hot[:, i - 1, :]","function_tokens":["def","get_train_input","(","self",",","prev",",","i",")",":","if","i","==","0",":","return","self",".","_zero_label","else",":","# TODO(gorban): update to gradually introduce gt labels.","return","self",".","_labels_one_hot","[",":",",","i","-","1",",",":","]"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L383-L389"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/sequence_layers.py","language":"python","identifier":"AttentionWithAutoregression.get_eval_input","parameters":"(self, prev, i)","argument_list":"","return_statement":"","docstring":"See SequenceLayerBase.get_eval_input for details.","docstring_summary":"See SequenceLayerBase.get_eval_input for details.","docstring_tokens":["See","SequenceLayerBase",".","get_eval_input","for","details","."],"function":"def get_eval_input(self, prev, i):\n \"\"\"See SequenceLayerBase.get_eval_input for details.\"\"\"\n if i == 0:\n return self._zero_label\n else:\n logit = self.char_logit(prev, char_index=i - 1)\n return self.char_one_hot(logit)","function_tokens":["def","get_eval_input","(","self",",","prev",",","i",")",":","if","i","==","0",":","return","self",".","_zero_label","else",":","logit","=","self",".","char_logit","(","prev",",","char_index","=","i","-","1",")","return","self",".","char_one_hot","(","logit",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/sequence_layers.py#L391-L397"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/train.py","language":"python","identifier":"create_optimizer","parameters":"(hparams)","argument_list":"","return_statement":"return optimizer","docstring":"Creates optimized based on the specified flags.","docstring_summary":"Creates optimized based on the specified flags.","docstring_tokens":["Creates","optimized","based","on","the","specified","flags","."],"function":"def create_optimizer(hparams):\n \"\"\"Creates optimized based on the specified flags.\"\"\"\n if hparams.optimizer == 'momentum':\n optimizer = tf.train.MomentumOptimizer(\n hparams.learning_rate, momentum=hparams.momentum)\n elif hparams.optimizer == 'adam':\n optimizer = tf.train.AdamOptimizer(hparams.learning_rate)\n elif hparams.optimizer == 'adadelta':\n optimizer = tf.train.AdadeltaOptimizer(hparams.learning_rate)\n elif hparams.optimizer == 'adagrad':\n optimizer = tf.train.AdagradOptimizer(hparams.learning_rate)\n elif hparams.optimizer == 'rmsprop':\n optimizer = tf.train.RMSPropOptimizer(\n hparams.learning_rate, momentum=hparams.momentum)\n return optimizer","function_tokens":["def","create_optimizer","(","hparams",")",":","if","hparams",".","optimizer","==","'momentum'",":","optimizer","=","tf",".","train",".","MomentumOptimizer","(","hparams",".","learning_rate",",","momentum","=","hparams",".","momentum",")","elif","hparams",".","optimizer","==","'adam'",":","optimizer","=","tf",".","train",".","AdamOptimizer","(","hparams",".","learning_rate",")","elif","hparams",".","optimizer","==","'adadelta'",":","optimizer","=","tf",".","train",".","AdadeltaOptimizer","(","hparams",".","learning_rate",")","elif","hparams",".","optimizer","==","'adagrad'",":","optimizer","=","tf",".","train",".","AdagradOptimizer","(","hparams",".","learning_rate",")","elif","hparams",".","optimizer","==","'rmsprop'",":","optimizer","=","tf",".","train",".","RMSPropOptimizer","(","hparams",".","learning_rate",",","momentum","=","hparams",".","momentum",")","return","optimizer"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/train.py#L98-L112"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/train.py","language":"python","identifier":"train","parameters":"(loss, init_fn, hparams)","argument_list":"","return_statement":"","docstring":"Wraps slim.learning.train to run a training loop.\n\n Args:\n loss: a loss tensor\n init_fn: A callable to be executed after all other initialization is done.\n hparams: a model hyper parameters","docstring_summary":"Wraps slim.learning.train to run a training loop.","docstring_tokens":["Wraps","slim",".","learning",".","train","to","run","a","training","loop","."],"function":"def train(loss, init_fn, hparams):\n \"\"\"Wraps slim.learning.train to run a training loop.\n\n Args:\n loss: a loss tensor\n init_fn: A callable to be executed after all other initialization is done.\n hparams: a model hyper parameters\n \"\"\"\n optimizer = create_optimizer(hparams)\n\n if FLAGS.sync_replicas:\n replica_id = tf.constant(FLAGS.task, tf.int32, shape=())\n optimizer = tf.LegacySyncReplicasOptimizer(\n opt=optimizer,\n replicas_to_aggregate=FLAGS.replicas_to_aggregate,\n replica_id=replica_id,\n total_num_replicas=FLAGS.total_num_replicas)\n sync_optimizer = optimizer\n startup_delay_steps = 0\n else:\n startup_delay_steps = 0\n sync_optimizer = None\n\n train_op = slim.learning.create_train_op(\n loss,\n optimizer,\n summarize_gradients=True,\n clip_gradient_norm=FLAGS.clip_gradient_norm)\n\n slim.learning.train(\n train_op=train_op,\n logdir=FLAGS.train_log_dir,\n graph=loss.graph,\n master=FLAGS.master,\n is_chief=(FLAGS.task == 0),\n number_of_steps=FLAGS.max_number_of_steps,\n save_summaries_secs=FLAGS.save_summaries_secs,\n save_interval_secs=FLAGS.save_interval_secs,\n startup_delay_steps=startup_delay_steps,\n sync_optimizer=sync_optimizer,\n init_fn=init_fn)","function_tokens":["def","train","(","loss",",","init_fn",",","hparams",")",":","optimizer","=","create_optimizer","(","hparams",")","if","FLAGS",".","sync_replicas",":","replica_id","=","tf",".","constant","(","FLAGS",".","task",",","tf",".","int32",",","shape","=","(",")",")","optimizer","=","tf",".","LegacySyncReplicasOptimizer","(","opt","=","optimizer",",","replicas_to_aggregate","=","FLAGS",".","replicas_to_aggregate",",","replica_id","=","replica_id",",","total_num_replicas","=","FLAGS",".","total_num_replicas",")","sync_optimizer","=","optimizer","startup_delay_steps","=","0","else",":","startup_delay_steps","=","0","sync_optimizer","=","None","train_op","=","slim",".","learning",".","create_train_op","(","loss",",","optimizer",",","summarize_gradients","=","True",",","clip_gradient_norm","=","FLAGS",".","clip_gradient_norm",")","slim",".","learning",".","train","(","train_op","=","train_op",",","logdir","=","FLAGS",".","train_log_dir",",","graph","=","loss",".","graph",",","master","=","FLAGS",".","master",",","is_chief","=","(","FLAGS",".","task","==","0",")",",","number_of_steps","=","FLAGS",".","max_number_of_steps",",","save_summaries_secs","=","FLAGS",".","save_summaries_secs",",","save_interval_secs","=","FLAGS",".","save_interval_secs",",","startup_delay_steps","=","startup_delay_steps",",","sync_optimizer","=","sync_optimizer",",","init_fn","=","init_fn",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/train.py#L115-L155"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/data_provider.py","language":"python","identifier":"augment_image","parameters":"(image)","argument_list":"","return_statement":"return distorted_image","docstring":"Augmentation the image with a random modification.\n\n Args:\n image: input Tensor image of rank 3, with the last dimension\n of size 3.\n\n Returns:\n Distorted Tensor image of the same shape.","docstring_summary":"Augmentation the image with a random modification.","docstring_tokens":["Augmentation","the","image","with","a","random","modification","."],"function":"def augment_image(image):\n \"\"\"Augmentation the image with a random modification.\n\n Args:\n image: input Tensor image of rank 3, with the last dimension\n of size 3.\n\n Returns:\n Distorted Tensor image of the same shape.\n \"\"\"\n with tf.variable_scope('AugmentImage'):\n height = image.get_shape().dims[0].value\n width = image.get_shape().dims[1].value\n\n # Random crop cut from the street sign image, resized to the same size.\n # Assures that the crop is covers at least 0.8 area of the input image.\n bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box(\n tf.shape(image),\n bounding_boxes=tf.zeros([0, 0, 4]),\n min_object_covered=0.8,\n aspect_ratio_range=[0.8, 1.2],\n area_range=[0.8, 1.0],\n use_image_if_no_bounding_boxes=True)\n distorted_image = tf.slice(image, bbox_begin, bbox_size)\n\n # Randomly chooses one of the 4 interpolation methods\n distorted_image = inception_preprocessing.apply_with_random_selector(\n distorted_image,\n lambda x, method: tf.image.resize_images(x, [height, width], method),\n num_cases=4)\n distorted_image.set_shape([height, width, 3])\n\n # Color distortion\n distorted_image = inception_preprocessing.apply_with_random_selector(\n distorted_image,\n functools.partial(\n inception_preprocessing.distort_color, fast_mode=False),\n num_cases=4)\n distorted_image = tf.clip_by_value(distorted_image, -1.5, 1.5)\n\n return distorted_image","function_tokens":["def","augment_image","(","image",")",":","with","tf",".","variable_scope","(","'AugmentImage'",")",":","height","=","image",".","get_shape","(",")",".","dims","[","0","]",".","value","width","=","image",".","get_shape","(",")",".","dims","[","1","]",".","value","# Random crop cut from the street sign image, resized to the same size.","# Assures that the crop is covers at least 0.8 area of the input image.","bbox_begin",",","bbox_size",",","_","=","tf",".","image",".","sample_distorted_bounding_box","(","tf",".","shape","(","image",")",",","bounding_boxes","=","tf",".","zeros","(","[","0",",","0",",","4","]",")",",","min_object_covered","=","0.8",",","aspect_ratio_range","=","[","0.8",",","1.2","]",",","area_range","=","[","0.8",",","1.0","]",",","use_image_if_no_bounding_boxes","=","True",")","distorted_image","=","tf",".","slice","(","image",",","bbox_begin",",","bbox_size",")","# Randomly chooses one of the 4 interpolation methods","distorted_image","=","inception_preprocessing",".","apply_with_random_selector","(","distorted_image",",","lambda","x",",","method",":","tf",".","image",".","resize_images","(","x",",","[","height",",","width","]",",","method",")",",","num_cases","=","4",")","distorted_image",".","set_shape","(","[","height",",","width",",","3","]",")","# Color distortion","distorted_image","=","inception_preprocessing",".","apply_with_random_selector","(","distorted_image",",","functools",".","partial","(","inception_preprocessing",".","distort_color",",","fast_mode","=","False",")",",","num_cases","=","4",")","distorted_image","=","tf",".","clip_by_value","(","distorted_image",",","-","1.5",",","1.5",")","return","distorted_image"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/data_provider.py#L49-L89"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/data_provider.py","language":"python","identifier":"central_crop","parameters":"(image, crop_size)","argument_list":"","return_statement":"","docstring":"Returns a central crop for the specified size of an image.\n\n Args:\n image: A tensor with shape [height, width, channels]\n crop_size: A tuple (crop_width, crop_height)\n\n Returns:\n A tensor of shape [crop_height, crop_width, channels].","docstring_summary":"Returns a central crop for the specified size of an image.","docstring_tokens":["Returns","a","central","crop","for","the","specified","size","of","an","image","."],"function":"def central_crop(image, crop_size):\n \"\"\"Returns a central crop for the specified size of an image.\n\n Args:\n image: A tensor with shape [height, width, channels]\n crop_size: A tuple (crop_width, crop_height)\n\n Returns:\n A tensor of shape [crop_height, crop_width, channels].\n \"\"\"\n with tf.variable_scope('CentralCrop'):\n target_width, target_height = crop_size\n image_height, image_width = tf.shape(image)[0], tf.shape(image)[1]\n assert_op1 = tf.Assert(\n tf.greater_equal(image_height, target_height),\n ['image_height < target_height', image_height, target_height])\n assert_op2 = tf.Assert(\n tf.greater_equal(image_width, target_width),\n ['image_width < target_width', image_width, target_width])\n with tf.control_dependencies([assert_op1, assert_op2]):\n offset_width = (image_width - target_width) \/ 2\n offset_height = (image_height - target_height) \/ 2\n return tf.image.crop_to_bounding_box(image, offset_height, offset_width,\n target_height, target_width)","function_tokens":["def","central_crop","(","image",",","crop_size",")",":","with","tf",".","variable_scope","(","'CentralCrop'",")",":","target_width",",","target_height","=","crop_size","image_height",",","image_width","=","tf",".","shape","(","image",")","[","0","]",",","tf",".","shape","(","image",")","[","1","]","assert_op1","=","tf",".","Assert","(","tf",".","greater_equal","(","image_height",",","target_height",")",",","[","'image_height < target_height'",",","image_height",",","target_height","]",")","assert_op2","=","tf",".","Assert","(","tf",".","greater_equal","(","image_width",",","target_width",")",",","[","'image_width < target_width'",",","image_width",",","target_width","]",")","with","tf",".","control_dependencies","(","[","assert_op1",",","assert_op2","]",")",":","offset_width","=","(","image_width","-","target_width",")","\/","2","offset_height","=","(","image_height","-","target_height",")","\/","2","return","tf",".","image",".","crop_to_bounding_box","(","image",",","offset_height",",","offset_width",",","target_height",",","target_width",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/data_provider.py#L92-L115"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/data_provider.py","language":"python","identifier":"preprocess_image","parameters":"(image, augment=False, central_crop_size=None,\n num_towers=4)","argument_list":"","return_statement":"return image","docstring":"Normalizes image to have values in a narrow range around zero.\n\n Args:\n image: a [H x W x 3] uint8 tensor.\n augment: optional, if True do random image distortion.\n central_crop_size: A tuple (crop_width, crop_height).\n num_towers: optional, number of shots of the same image in the input image.\n\n Returns:\n A float32 tensor of shape [H x W x 3] with RGB values in the required\n range.","docstring_summary":"Normalizes image to have values in a narrow range around zero.","docstring_tokens":["Normalizes","image","to","have","values","in","a","narrow","range","around","zero","."],"function":"def preprocess_image(image, augment=False, central_crop_size=None,\n num_towers=4):\n \"\"\"Normalizes image to have values in a narrow range around zero.\n\n Args:\n image: a [H x W x 3] uint8 tensor.\n augment: optional, if True do random image distortion.\n central_crop_size: A tuple (crop_width, crop_height).\n num_towers: optional, number of shots of the same image in the input image.\n\n Returns:\n A float32 tensor of shape [H x W x 3] with RGB values in the required\n range.\n \"\"\"\n with tf.variable_scope('PreprocessImage'):\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n if augment or central_crop_size:\n if num_towers == 1:\n images = [image]\n else:\n images = tf.split(value=image, num_or_size_splits=num_towers, axis=1)\n if central_crop_size:\n view_crop_size = (central_crop_size[0] \/ num_towers,\n central_crop_size[1])\n images = [central_crop(img, view_crop_size) for img in images]\n if augment:\n images = [augment_image(img) for img in images]\n image = tf.concat(images, 1)\n\n image = tf.subtract(image, 0.5)\n image = tf.multiply(image, 2.5)\n\n return image","function_tokens":["def","preprocess_image","(","image",",","augment","=","False",",","central_crop_size","=","None",",","num_towers","=","4",")",":","with","tf",".","variable_scope","(","'PreprocessImage'",")",":","image","=","tf",".","image",".","convert_image_dtype","(","image",",","dtype","=","tf",".","float32",")","if","augment","or","central_crop_size",":","if","num_towers","==","1",":","images","=","[","image","]","else",":","images","=","tf",".","split","(","value","=","image",",","num_or_size_splits","=","num_towers",",","axis","=","1",")","if","central_crop_size",":","view_crop_size","=","(","central_crop_size","[","0","]","\/","num_towers",",","central_crop_size","[","1","]",")","images","=","[","central_crop","(","img",",","view_crop_size",")","for","img","in","images","]","if","augment",":","images","=","[","augment_image","(","img",")","for","img","in","images","]","image","=","tf",".","concat","(","images",",","1",")","image","=","tf",".","subtract","(","image",",","0.5",")","image","=","tf",".","multiply","(","image",",","2.5",")","return","image"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/data_provider.py#L118-L150"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/data_provider.py","language":"python","identifier":"get_data","parameters":"(dataset,\n batch_size,\n augment=False,\n central_crop_size=None,\n shuffle_config=None,\n shuffle=True)","argument_list":"","return_statement":"return InputEndpoints(\n images=images,\n images_orig=images_orig,\n labels=labels,\n labels_one_hot=labels_one_hot)","docstring":"Wraps calls to DatasetDataProviders and shuffle_batch.\n\n For more details about supported Dataset objects refer to datasets\/fsns.py.\n\n Args:\n dataset: a slim.data.dataset.Dataset object.\n batch_size: number of samples per batch.\n augment: optional, if True does random image distortion.\n central_crop_size: A CharLogittuple (crop_width, crop_height).\n shuffle_config: A namedtuple ShuffleBatchConfig.\n shuffle: if True use data shuffling.\n\n Returns:","docstring_summary":"Wraps calls to DatasetDataProviders and shuffle_batch.","docstring_tokens":["Wraps","calls","to","DatasetDataProviders","and","shuffle_batch","."],"function":"def get_data(dataset,\n batch_size,\n augment=False,\n central_crop_size=None,\n shuffle_config=None,\n shuffle=True):\n \"\"\"Wraps calls to DatasetDataProviders and shuffle_batch.\n\n For more details about supported Dataset objects refer to datasets\/fsns.py.\n\n Args:\n dataset: a slim.data.dataset.Dataset object.\n batch_size: number of samples per batch.\n augment: optional, if True does random image distortion.\n central_crop_size: A CharLogittuple (crop_width, crop_height).\n shuffle_config: A namedtuple ShuffleBatchConfig.\n shuffle: if True use data shuffling.\n\n Returns:\n\n \"\"\"\n if not shuffle_config:\n shuffle_config = DEFAULT_SHUFFLE_CONFIG\n\n provider = slim.dataset_data_provider.DatasetDataProvider(\n dataset,\n shuffle=shuffle,\n common_queue_capacity=2 * batch_size,\n common_queue_min=batch_size)\n image_orig, label = provider.get(['image', 'label'])\n \n image = preprocess_image(\n image_orig, augment, central_crop_size, num_towers=dataset.num_of_views)\n label_one_hot = slim.one_hot_encoding(label, dataset.num_char_classes)\n\n images, images_orig, labels, labels_one_hot = (tf.train.shuffle_batch(\n [image, image_orig, label, label_one_hot],\n batch_size=batch_size,\n num_threads=shuffle_config.num_batching_threads,\n capacity=shuffle_config.queue_capacity,\n min_after_dequeue=shuffle_config.min_after_dequeue))\n\n return InputEndpoints(\n images=images,\n images_orig=images_orig,\n labels=labels,\n labels_one_hot=labels_one_hot)","function_tokens":["def","get_data","(","dataset",",","batch_size",",","augment","=","False",",","central_crop_size","=","None",",","shuffle_config","=","None",",","shuffle","=","True",")",":","if","not","shuffle_config",":","shuffle_config","=","DEFAULT_SHUFFLE_CONFIG","provider","=","slim",".","dataset_data_provider",".","DatasetDataProvider","(","dataset",",","shuffle","=","shuffle",",","common_queue_capacity","=","2","*","batch_size",",","common_queue_min","=","batch_size",")","image_orig",",","label","=","provider",".","get","(","[","'image'",",","'label'","]",")","image","=","preprocess_image","(","image_orig",",","augment",",","central_crop_size",",","num_towers","=","dataset",".","num_of_views",")","label_one_hot","=","slim",".","one_hot_encoding","(","label",",","dataset",".","num_char_classes",")","images",",","images_orig",",","labels",",","labels_one_hot","=","(","tf",".","train",".","shuffle_batch","(","[","image",",","image_orig",",","label",",","label_one_hot","]",",","batch_size","=","batch_size",",","num_threads","=","shuffle_config",".","num_batching_threads",",","capacity","=","shuffle_config",".","queue_capacity",",","min_after_dequeue","=","shuffle_config",".","min_after_dequeue",")",")","return","InputEndpoints","(","images","=","images",",","images_orig","=","images_orig",",","labels","=","labels",",","labels_one_hot","=","labels_one_hot",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/data_provider.py#L153-L199"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/metrics.py","language":"python","identifier":"char_accuracy","parameters":"(predictions, targets, rej_char, streaming=False)","argument_list":"","return_statement":"","docstring":"Computes character level accuracy.\n\n Both predictions and targets should have the same shape\n [batch_size x seq_length].\n\n Args:\n predictions: predicted characters ids.\n targets: ground truth character ids.\n rej_char: the character id used to mark an empty element (end of sequence).\n streaming: if True, uses the streaming mean from the slim.metric module.\n\n Returns:\n a update_ops for execution and value tensor whose value on evaluation\n returns the total character accuracy.","docstring_summary":"Computes character level accuracy.","docstring_tokens":["Computes","character","level","accuracy","."],"function":"def char_accuracy(predictions, targets, rej_char, streaming=False):\n \"\"\"Computes character level accuracy.\n\n Both predictions and targets should have the same shape\n [batch_size x seq_length].\n\n Args:\n predictions: predicted characters ids.\n targets: ground truth character ids.\n rej_char: the character id used to mark an empty element (end of sequence).\n streaming: if True, uses the streaming mean from the slim.metric module.\n\n Returns:\n a update_ops for execution and value tensor whose value on evaluation\n returns the total character accuracy.\n \"\"\"\n with tf.variable_scope('CharAccuracy'):\n predictions.get_shape().assert_is_compatible_with(targets.get_shape())\n\n targets = tf.to_int32(targets)\n const_rej_char = tf.constant(rej_char, shape=targets.get_shape())\n weights = tf.to_float(tf.not_equal(targets, const_rej_char))\n correct_chars = tf.to_float(tf.equal(predictions, targets))\n accuracy_per_example = tf.div(\n tf.reduce_sum(tf.multiply(correct_chars, weights), 1),\n tf.reduce_sum(weights, 1))\n if streaming:\n return tf.contrib.metrics.streaming_mean(accuracy_per_example)\n else:\n return tf.reduce_mean(accuracy_per_example)","function_tokens":["def","char_accuracy","(","predictions",",","targets",",","rej_char",",","streaming","=","False",")",":","with","tf",".","variable_scope","(","'CharAccuracy'",")",":","predictions",".","get_shape","(",")",".","assert_is_compatible_with","(","targets",".","get_shape","(",")",")","targets","=","tf",".","to_int32","(","targets",")","const_rej_char","=","tf",".","constant","(","rej_char",",","shape","=","targets",".","get_shape","(",")",")","weights","=","tf",".","to_float","(","tf",".","not_equal","(","targets",",","const_rej_char",")",")","correct_chars","=","tf",".","to_float","(","tf",".","equal","(","predictions",",","targets",")",")","accuracy_per_example","=","tf",".","div","(","tf",".","reduce_sum","(","tf",".","multiply","(","correct_chars",",","weights",")",",","1",")",",","tf",".","reduce_sum","(","weights",",","1",")",")","if","streaming",":","return","tf",".","contrib",".","metrics",".","streaming_mean","(","accuracy_per_example",")","else",":","return","tf",".","reduce_mean","(","accuracy_per_example",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/metrics.py#L21-L50"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/metrics.py","language":"python","identifier":"sequence_accuracy","parameters":"(predictions, targets, rej_char, streaming=False)","argument_list":"","return_statement":"","docstring":"Computes sequence level accuracy.\n\n Both input tensors should have the same shape: [batch_size x seq_length].\n\n Args:\n predictions: predicted character classes.\n targets: ground truth character classes.\n rej_char: the character id used to mark empty element (end of sequence).\n streaming: if True, uses the streaming mean from the slim.metric module.\n\n Returns:\n a update_ops for execution and value tensor whose value on evaluation\n returns the total sequence accuracy.","docstring_summary":"Computes sequence level accuracy.","docstring_tokens":["Computes","sequence","level","accuracy","."],"function":"def sequence_accuracy(predictions, targets, rej_char, streaming=False):\n \"\"\"Computes sequence level accuracy.\n\n Both input tensors should have the same shape: [batch_size x seq_length].\n\n Args:\n predictions: predicted character classes.\n targets: ground truth character classes.\n rej_char: the character id used to mark empty element (end of sequence).\n streaming: if True, uses the streaming mean from the slim.metric module.\n\n Returns:\n a update_ops for execution and value tensor whose value on evaluation\n returns the total sequence accuracy.\n \"\"\"\n\n with tf.variable_scope('SequenceAccuracy'):\n predictions.get_shape().assert_is_compatible_with(targets.get_shape())\n\n targets = tf.to_int32(targets)\n const_rej_char = tf.constant(\n rej_char, shape=targets.get_shape(), dtype=tf.int32)\n include_mask = tf.not_equal(targets, const_rej_char)\n include_predictions = tf.to_int32(\n tf.where(include_mask, predictions,\n tf.zeros_like(predictions) + rej_char))\n correct_chars = tf.to_float(tf.equal(include_predictions, targets))\n correct_chars_counts = tf.cast(\n tf.reduce_sum(correct_chars, reduction_indices=[1]), dtype=tf.int32)\n target_length = targets.get_shape().dims[1].value\n target_chars_counts = tf.constant(\n target_length, shape=correct_chars_counts.get_shape())\n accuracy_per_example = tf.to_float(\n tf.equal(correct_chars_counts, target_chars_counts))\n if streaming:\n return tf.contrib.metrics.streaming_mean(accuracy_per_example)\n else:\n return tf.reduce_mean(accuracy_per_example)","function_tokens":["def","sequence_accuracy","(","predictions",",","targets",",","rej_char",",","streaming","=","False",")",":","with","tf",".","variable_scope","(","'SequenceAccuracy'",")",":","predictions",".","get_shape","(",")",".","assert_is_compatible_with","(","targets",".","get_shape","(",")",")","targets","=","tf",".","to_int32","(","targets",")","const_rej_char","=","tf",".","constant","(","rej_char",",","shape","=","targets",".","get_shape","(",")",",","dtype","=","tf",".","int32",")","include_mask","=","tf",".","not_equal","(","targets",",","const_rej_char",")","include_predictions","=","tf",".","to_int32","(","tf",".","where","(","include_mask",",","predictions",",","tf",".","zeros_like","(","predictions",")","+","rej_char",")",")","correct_chars","=","tf",".","to_float","(","tf",".","equal","(","include_predictions",",","targets",")",")","correct_chars_counts","=","tf",".","cast","(","tf",".","reduce_sum","(","correct_chars",",","reduction_indices","=","[","1","]",")",",","dtype","=","tf",".","int32",")","target_length","=","targets",".","get_shape","(",")",".","dims","[","1","]",".","value","target_chars_counts","=","tf",".","constant","(","target_length",",","shape","=","correct_chars_counts",".","get_shape","(",")",")","accuracy_per_example","=","tf",".","to_float","(","tf",".","equal","(","correct_chars_counts",",","target_chars_counts",")",")","if","streaming",":","return","tf",".","contrib",".","metrics",".","streaming_mean","(","accuracy_per_example",")","else",":","return","tf",".","reduce_mean","(","accuracy_per_example",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/metrics.py#L53-L90"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/inception_preprocessing.py","language":"python","identifier":"apply_with_random_selector","parameters":"(x, func, num_cases)","argument_list":"","return_statement":"return control_flow_ops.merge([\n func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case)\n for case in range(num_cases)\n ])[0]","docstring":"Computes func(x, sel), with sel sampled from [0...num_cases-1].\n\n Args:\n x: input Tensor.\n func: Python function to apply.\n num_cases: Python int32, number of cases to sample sel from.\n\n Returns:\n The result of func(x, sel), where func receives the value of the\n selector as a python integer, but sel is sampled dynamically.","docstring_summary":"Computes func(x, sel), with sel sampled from [0...num_cases-1].","docstring_tokens":["Computes","func","(","x","sel",")","with","sel","sampled","from","[","0","...","num_cases","-","1","]","."],"function":"def apply_with_random_selector(x, func, num_cases):\n \"\"\"Computes func(x, sel), with sel sampled from [0...num_cases-1].\n\n Args:\n x: input Tensor.\n func: Python function to apply.\n num_cases: Python int32, number of cases to sample sel from.\n\n Returns:\n The result of func(x, sel), where func receives the value of the\n selector as a python integer, but sel is sampled dynamically.\n \"\"\"\n sel = tf.random_uniform([], maxval=num_cases, dtype=tf.int32)\n # Pass the real x only to one of the func calls.\n return control_flow_ops.merge([\n func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case)\n for case in range(num_cases)\n ])[0]","function_tokens":["def","apply_with_random_selector","(","x",",","func",",","num_cases",")",":","sel","=","tf",".","random_uniform","(","[","]",",","maxval","=","num_cases",",","dtype","=","tf",".","int32",")","# Pass the real x only to one of the func calls.","return","control_flow_ops",".","merge","(","[","func","(","control_flow_ops",".","switch","(","x",",","tf",".","equal","(","sel",",","case",")",")","[","1","]",",","case",")","for","case","in","range","(","num_cases",")","]",")","[","0","]"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/inception_preprocessing.py#L29-L46"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/inception_preprocessing.py","language":"python","identifier":"distort_color","parameters":"(image, color_ordering=0, fast_mode=True, scope=None)","argument_list":"","return_statement":"","docstring":"Distort the color of a Tensor image.\n\n Each color distortion is non-commutative and thus ordering of the color ops\n matters. Ideally we would randomly permute the ordering of the color ops.\n Rather then adding that level of complication, we select a distinct ordering\n of color ops for each preprocessing thread.\n\n Args:\n image: 3-D Tensor containing single image in [0, 1].\n color_ordering: Python int, a type of distortion (valid values: 0-3).\n fast_mode: Avoids slower ops (random_hue and random_contrast)\n scope: Optional scope for name_scope.\n Returns:\n 3-D Tensor color-distorted image on range [0, 1]\n Raises:\n ValueError: if color_ordering not in [0, 3]","docstring_summary":"Distort the color of a Tensor image.","docstring_tokens":["Distort","the","color","of","a","Tensor","image","."],"function":"def distort_color(image, color_ordering=0, fast_mode=True, scope=None):\n \"\"\"Distort the color of a Tensor image.\n\n Each color distortion is non-commutative and thus ordering of the color ops\n matters. Ideally we would randomly permute the ordering of the color ops.\n Rather then adding that level of complication, we select a distinct ordering\n of color ops for each preprocessing thread.\n\n Args:\n image: 3-D Tensor containing single image in [0, 1].\n color_ordering: Python int, a type of distortion (valid values: 0-3).\n fast_mode: Avoids slower ops (random_hue and random_contrast)\n scope: Optional scope for name_scope.\n Returns:\n 3-D Tensor color-distorted image on range [0, 1]\n Raises:\n ValueError: if color_ordering not in [0, 3]\n \"\"\"\n with tf.name_scope(scope, 'distort_color', [image]):\n if fast_mode:\n if color_ordering == 0:\n image = tf.image.random_brightness(image, max_delta=32. \/ 255.)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n else:\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_brightness(image, max_delta=32. \/ 255.)\n else:\n if color_ordering == 0:\n image = tf.image.random_brightness(image, max_delta=32. \/ 255.)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.2)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n elif color_ordering == 1:\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_brightness(image, max_delta=32. \/ 255.)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.2)\n elif color_ordering == 2:\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.2)\n image = tf.image.random_brightness(image, max_delta=32. \/ 255.)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n elif color_ordering == 3:\n image = tf.image.random_hue(image, max_delta=0.2)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n image = tf.image.random_brightness(image, max_delta=32. \/ 255.)\n else:\n raise ValueError('color_ordering must be in [0, 3]')\n\n # The random_* ops do not necessarily clamp.\n return tf.clip_by_value(image, 0.0, 1.0)","function_tokens":["def","distort_color","(","image",",","color_ordering","=","0",",","fast_mode","=","True",",","scope","=","None",")",":","with","tf",".","name_scope","(","scope",",","'distort_color'",",","[","image","]",")",":","if","fast_mode",":","if","color_ordering","==","0",":","image","=","tf",".","image",".","random_brightness","(","image",",","max_delta","=","32.","\/","255.",")","image","=","tf",".","image",".","random_saturation","(","image",",","lower","=","0.5",",","upper","=","1.5",")","else",":","image","=","tf",".","image",".","random_saturation","(","image",",","lower","=","0.5",",","upper","=","1.5",")","image","=","tf",".","image",".","random_brightness","(","image",",","max_delta","=","32.","\/","255.",")","else",":","if","color_ordering","==","0",":","image","=","tf",".","image",".","random_brightness","(","image",",","max_delta","=","32.","\/","255.",")","image","=","tf",".","image",".","random_saturation","(","image",",","lower","=","0.5",",","upper","=","1.5",")","image","=","tf",".","image",".","random_hue","(","image",",","max_delta","=","0.2",")","image","=","tf",".","image",".","random_contrast","(","image",",","lower","=","0.5",",","upper","=","1.5",")","elif","color_ordering","==","1",":","image","=","tf",".","image",".","random_saturation","(","image",",","lower","=","0.5",",","upper","=","1.5",")","image","=","tf",".","image",".","random_brightness","(","image",",","max_delta","=","32.","\/","255.",")","image","=","tf",".","image",".","random_contrast","(","image",",","lower","=","0.5",",","upper","=","1.5",")","image","=","tf",".","image",".","random_hue","(","image",",","max_delta","=","0.2",")","elif","color_ordering","==","2",":","image","=","tf",".","image",".","random_contrast","(","image",",","lower","=","0.5",",","upper","=","1.5",")","image","=","tf",".","image",".","random_hue","(","image",",","max_delta","=","0.2",")","image","=","tf",".","image",".","random_brightness","(","image",",","max_delta","=","32.","\/","255.",")","image","=","tf",".","image",".","random_saturation","(","image",",","lower","=","0.5",",","upper","=","1.5",")","elif","color_ordering","==","3",":","image","=","tf",".","image",".","random_hue","(","image",",","max_delta","=","0.2",")","image","=","tf",".","image",".","random_saturation","(","image",",","lower","=","0.5",",","upper","=","1.5",")","image","=","tf",".","image",".","random_contrast","(","image",",","lower","=","0.5",",","upper","=","1.5",")","image","=","tf",".","image",".","random_brightness","(","image",",","max_delta","=","32.","\/","255.",")","else",":","raise","ValueError","(","'color_ordering must be in [0, 3]'",")","# The random_* ops do not necessarily clamp.","return","tf",".","clip_by_value","(","image",",","0.0",",","1.0",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/inception_preprocessing.py#L49-L100"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/inception_preprocessing.py","language":"python","identifier":"distorted_bounding_box_crop","parameters":"(image,\n bbox,\n min_object_covered=0.1,\n aspect_ratio_range=(0.75, 1.33),\n area_range=(0.05, 1.0),\n max_attempts=100,\n scope=None)","argument_list":"","return_statement":"","docstring":"Generates cropped_image using a one of the bboxes randomly distorted.\n\n See `tf.image.sample_distorted_bounding_box` for more documentation.\n\n Args:\n image: 3-D Tensor of image (it will be converted to floats in [0, 1]).\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged\n as [ymin, xmin, ymax, xmax]. If num_boxes is 0 then it would use the\n whole image.\n min_object_covered: An optional `float`. Defaults to `0.1`. The cropped\n area of the image must contain at least this fraction of any bounding box\n supplied.\n aspect_ratio_range: An optional list of `floats`. The cropped area of the\n image must have an aspect ratio = width \/ height within this range.\n area_range: An optional list of `floats`. The cropped area of the image\n must contain a fraction of the supplied image within in this range.\n max_attempts: An optional `int`. Number of attempts at generating a cropped\n region of the image of the specified constraints. After `max_attempts`\n failures, return the entire image.\n scope: Optional scope for name_scope.\n Returns:\n A tuple, a 3-D Tensor cropped_image and the distorted bbox","docstring_summary":"Generates cropped_image using a one of the bboxes randomly distorted.","docstring_tokens":["Generates","cropped_image","using","a","one","of","the","bboxes","randomly","distorted","."],"function":"def distorted_bounding_box_crop(image,\n bbox,\n min_object_covered=0.1,\n aspect_ratio_range=(0.75, 1.33),\n area_range=(0.05, 1.0),\n max_attempts=100,\n scope=None):\n \"\"\"Generates cropped_image using a one of the bboxes randomly distorted.\n\n See `tf.image.sample_distorted_bounding_box` for more documentation.\n\n Args:\n image: 3-D Tensor of image (it will be converted to floats in [0, 1]).\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged\n as [ymin, xmin, ymax, xmax]. If num_boxes is 0 then it would use the\n whole image.\n min_object_covered: An optional `float`. Defaults to `0.1`. The cropped\n area of the image must contain at least this fraction of any bounding box\n supplied.\n aspect_ratio_range: An optional list of `floats`. The cropped area of the\n image must have an aspect ratio = width \/ height within this range.\n area_range: An optional list of `floats`. The cropped area of the image\n must contain a fraction of the supplied image within in this range.\n max_attempts: An optional `int`. Number of attempts at generating a cropped\n region of the image of the specified constraints. After `max_attempts`\n failures, return the entire image.\n scope: Optional scope for name_scope.\n Returns:\n A tuple, a 3-D Tensor cropped_image and the distorted bbox\n \"\"\"\n with tf.name_scope(scope, 'distorted_bounding_box_crop', [image, bbox]):\n # Each bounding box has shape [1, num_boxes, box coords] and\n # the coordinates are ordered [ymin, xmin, ymax, xmax].\n\n # A large fraction of image datasets contain a human-annotated bounding\n # box delineating the region of the image containing the object of interest.\n # We choose to create a new bounding box for the object which is a randomly\n # distorted version of the human-annotated bounding box that obeys an\n # allowed range of aspect ratios, sizes and overlap with the human-annotated\n # bounding box. If no box is supplied, then we assume the bounding box is\n # the entire image.\n sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(\n tf.shape(image),\n bounding_boxes=bbox,\n min_object_covered=min_object_covered,\n aspect_ratio_range=aspect_ratio_range,\n area_range=area_range,\n max_attempts=max_attempts,\n use_image_if_no_bounding_boxes=True)\n bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box\n\n # Crop the image to the specified bounding box.\n cropped_image = tf.slice(image, bbox_begin, bbox_size)\n return cropped_image, distort_bbox","function_tokens":["def","distorted_bounding_box_crop","(","image",",","bbox",",","min_object_covered","=","0.1",",","aspect_ratio_range","=","(","0.75",",","1.33",")",",","area_range","=","(","0.05",",","1.0",")",",","max_attempts","=","100",",","scope","=","None",")",":","with","tf",".","name_scope","(","scope",",","'distorted_bounding_box_crop'",",","[","image",",","bbox","]",")",":","# Each bounding box has shape [1, num_boxes, box coords] and","# the coordinates are ordered [ymin, xmin, ymax, xmax].","# A large fraction of image datasets contain a human-annotated bounding","# box delineating the region of the image containing the object of interest.","# We choose to create a new bounding box for the object which is a randomly","# distorted version of the human-annotated bounding box that obeys an","# allowed range of aspect ratios, sizes and overlap with the human-annotated","# bounding box. If no box is supplied, then we assume the bounding box is","# the entire image.","sample_distorted_bounding_box","=","tf",".","image",".","sample_distorted_bounding_box","(","tf",".","shape","(","image",")",",","bounding_boxes","=","bbox",",","min_object_covered","=","min_object_covered",",","aspect_ratio_range","=","aspect_ratio_range",",","area_range","=","area_range",",","max_attempts","=","max_attempts",",","use_image_if_no_bounding_boxes","=","True",")","bbox_begin",",","bbox_size",",","distort_bbox","=","sample_distorted_bounding_box","# Crop the image to the specified bounding box.","cropped_image","=","tf",".","slice","(","image",",","bbox_begin",",","bbox_size",")","return","cropped_image",",","distort_bbox"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/inception_preprocessing.py#L103-L157"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/inception_preprocessing.py","language":"python","identifier":"preprocess_for_train","parameters":"(image,\n height,\n width,\n bbox,\n fast_mode=True,\n scope=None)","argument_list":"","return_statement":"","docstring":"Distort one image for training a network.\n\n Distorting images provides a useful technique for augmenting the data\n set during training in order to make the network invariant to aspects\n of the image that do not effect the label.\n\n Additionally it would create image_summaries to display the different\n transformations applied to the image.\n\n Args:\n image: 3-D Tensor of image. If dtype is tf.float32 then the range should be\n [0, 1], otherwise it would converted to tf.float32 assuming that the range\n is [0, MAX], where MAX is largest positive representable number for\n int(8\/16\/32) data type (see `tf.image.convert_image_dtype` for details).\n height: integer\n width: integer\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged\n as [ymin, xmin, ymax, xmax].\n fast_mode: Optional boolean, if True avoids slower transformations (i.e.\n bi-cubic resizing, random_hue or random_contrast).\n scope: Optional scope for name_scope.\n Returns:\n 3-D float Tensor of distorted image used for training with range [-1, 1].","docstring_summary":"Distort one image for training a network.","docstring_tokens":["Distort","one","image","for","training","a","network","."],"function":"def preprocess_for_train(image,\n height,\n width,\n bbox,\n fast_mode=True,\n scope=None):\n \"\"\"Distort one image for training a network.\n\n Distorting images provides a useful technique for augmenting the data\n set during training in order to make the network invariant to aspects\n of the image that do not effect the label.\n\n Additionally it would create image_summaries to display the different\n transformations applied to the image.\n\n Args:\n image: 3-D Tensor of image. If dtype is tf.float32 then the range should be\n [0, 1], otherwise it would converted to tf.float32 assuming that the range\n is [0, MAX], where MAX is largest positive representable number for\n int(8\/16\/32) data type (see `tf.image.convert_image_dtype` for details).\n height: integer\n width: integer\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged\n as [ymin, xmin, ymax, xmax].\n fast_mode: Optional boolean, if True avoids slower transformations (i.e.\n bi-cubic resizing, random_hue or random_contrast).\n scope: Optional scope for name_scope.\n Returns:\n 3-D float Tensor of distorted image used for training with range [-1, 1].\n \"\"\"\n with tf.name_scope(scope, 'distort_image', [image, height, width, bbox]):\n if bbox is None:\n bbox = tf.constant(\n [0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])\n if image.dtype != tf.float32:\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n # Each bounding box has shape [1, num_boxes, box coords] and\n # the coordinates are ordered [ymin, xmin, ymax, xmax].\n image_with_box = tf.image.draw_bounding_boxes(\n tf.expand_dims(image, 0), bbox)\n tf.summary.image('image_with_bounding_boxes', image_with_box)\n\n distorted_image, distorted_bbox = distorted_bounding_box_crop(image, bbox)\n # Restore the shape since the dynamic slice based upon the bbox_size loses\n # the third dimension.\n distorted_image.set_shape([None, None, 3])\n image_with_distorted_box = tf.image.draw_bounding_boxes(\n tf.expand_dims(image, 0), distorted_bbox)\n tf.summary.image('images_with_distorted_bounding_box',\n image_with_distorted_box)\n\n # This resizing operation may distort the images because the aspect\n # ratio is not respected. We select a resize method in a round robin\n # fashion based on the thread number.\n # Note that ResizeMethod contains 4 enumerated resizing methods.\n\n # We select only 1 case for fast_mode bilinear.\n num_resize_cases = 1 if fast_mode else 4\n distorted_image = apply_with_random_selector(\n distorted_image,\n lambda x, method: tf.image.resize_images(x, [height, width], method=method),\n num_cases=num_resize_cases)\n\n tf.summary.image('cropped_resized_image',\n tf.expand_dims(distorted_image, 0))\n\n # Randomly flip the image horizontally.\n distorted_image = tf.image.random_flip_left_right(distorted_image)\n\n # Randomly distort the colors. There are 4 ways to do it.\n distorted_image = apply_with_random_selector(\n distorted_image,\n lambda x, ordering: distort_color(x, ordering, fast_mode),\n num_cases=4)\n\n tf.summary.image('final_distorted_image',\n tf.expand_dims(distorted_image, 0))\n distorted_image = tf.subtract(distorted_image, 0.5)\n distorted_image = tf.multiply(distorted_image, 2.0)\n return distorted_image","function_tokens":["def","preprocess_for_train","(","image",",","height",",","width",",","bbox",",","fast_mode","=","True",",","scope","=","None",")",":","with","tf",".","name_scope","(","scope",",","'distort_image'",",","[","image",",","height",",","width",",","bbox","]",")",":","if","bbox","is","None",":","bbox","=","tf",".","constant","(","[","0.0",",","0.0",",","1.0",",","1.0","]",",","dtype","=","tf",".","float32",",","shape","=","[","1",",","1",",","4","]",")","if","image",".","dtype","!=","tf",".","float32",":","image","=","tf",".","image",".","convert_image_dtype","(","image",",","dtype","=","tf",".","float32",")","# Each bounding box has shape [1, num_boxes, box coords] and","# the coordinates are ordered [ymin, xmin, ymax, xmax].","image_with_box","=","tf",".","image",".","draw_bounding_boxes","(","tf",".","expand_dims","(","image",",","0",")",",","bbox",")","tf",".","summary",".","image","(","'image_with_bounding_boxes'",",","image_with_box",")","distorted_image",",","distorted_bbox","=","distorted_bounding_box_crop","(","image",",","bbox",")","# Restore the shape since the dynamic slice based upon the bbox_size loses","# the third dimension.","distorted_image",".","set_shape","(","[","None",",","None",",","3","]",")","image_with_distorted_box","=","tf",".","image",".","draw_bounding_boxes","(","tf",".","expand_dims","(","image",",","0",")",",","distorted_bbox",")","tf",".","summary",".","image","(","'images_with_distorted_bounding_box'",",","image_with_distorted_box",")","# This resizing operation may distort the images because the aspect","# ratio is not respected. We select a resize method in a round robin","# fashion based on the thread number.","# Note that ResizeMethod contains 4 enumerated resizing methods.","# We select only 1 case for fast_mode bilinear.","num_resize_cases","=","1","if","fast_mode","else","4","distorted_image","=","apply_with_random_selector","(","distorted_image",",","lambda","x",",","method",":","tf",".","image",".","resize_images","(","x",",","[","height",",","width","]",",","method","=","method",")",",","num_cases","=","num_resize_cases",")","tf",".","summary",".","image","(","'cropped_resized_image'",",","tf",".","expand_dims","(","distorted_image",",","0",")",")","# Randomly flip the image horizontally.","distorted_image","=","tf",".","image",".","random_flip_left_right","(","distorted_image",")","# Randomly distort the colors. There are 4 ways to do it.","distorted_image","=","apply_with_random_selector","(","distorted_image",",","lambda","x",",","ordering",":","distort_color","(","x",",","ordering",",","fast_mode",")",",","num_cases","=","4",")","tf",".","summary",".","image","(","'final_distorted_image'",",","tf",".","expand_dims","(","distorted_image",",","0",")",")","distorted_image","=","tf",".","subtract","(","distorted_image",",","0.5",")","distorted_image","=","tf",".","multiply","(","distorted_image",",","2.0",")","return","distorted_image"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/inception_preprocessing.py#L160-L240"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/inception_preprocessing.py","language":"python","identifier":"preprocess_for_eval","parameters":"(image,\n height,\n width,\n central_fraction=0.875,\n scope=None)","argument_list":"","return_statement":"","docstring":"Prepare one image for evaluation.\n\n If height and width are specified it would output an image with that size by\n applying resize_bilinear.\n\n If central_fraction is specified it would cropt the central fraction of the\n input image.\n\n Args:\n image: 3-D Tensor of image. If dtype is tf.float32 then the range should be\n [0, 1], otherwise it would converted to tf.float32 assuming that the range\n is [0, MAX], where MAX is largest positive representable number for\n int(8\/16\/32) data type (see `tf.image.convert_image_dtype` for details)\n height: integer\n width: integer\n central_fraction: Optional Float, fraction of the image to crop.\n scope: Optional scope for name_scope.\n Returns:\n 3-D float Tensor of prepared image.","docstring_summary":"Prepare one image for evaluation.","docstring_tokens":["Prepare","one","image","for","evaluation","."],"function":"def preprocess_for_eval(image,\n height,\n width,\n central_fraction=0.875,\n scope=None):\n \"\"\"Prepare one image for evaluation.\n\n If height and width are specified it would output an image with that size by\n applying resize_bilinear.\n\n If central_fraction is specified it would cropt the central fraction of the\n input image.\n\n Args:\n image: 3-D Tensor of image. If dtype is tf.float32 then the range should be\n [0, 1], otherwise it would converted to tf.float32 assuming that the range\n is [0, MAX], where MAX is largest positive representable number for\n int(8\/16\/32) data type (see `tf.image.convert_image_dtype` for details)\n height: integer\n width: integer\n central_fraction: Optional Float, fraction of the image to crop.\n scope: Optional scope for name_scope.\n Returns:\n 3-D float Tensor of prepared image.\n \"\"\"\n with tf.name_scope(scope, 'eval_image', [image, height, width]):\n if image.dtype != tf.float32:\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n # Crop the central region of the image with an area containing 87.5% of\n # the original image.\n if central_fraction:\n image = tf.image.central_crop(image, central_fraction=central_fraction)\n\n if height and width:\n # Resize the image to the specified height and width.\n image = tf.expand_dims(image, 0)\n image = tf.image.resize_bilinear(\n image, [height, width], align_corners=False)\n image = tf.squeeze(image, [0])\n image = tf.subtract(image, 0.5)\n image = tf.multiply(image, 2.0)\n return image","function_tokens":["def","preprocess_for_eval","(","image",",","height",",","width",",","central_fraction","=","0.875",",","scope","=","None",")",":","with","tf",".","name_scope","(","scope",",","'eval_image'",",","[","image",",","height",",","width","]",")",":","if","image",".","dtype","!=","tf",".","float32",":","image","=","tf",".","image",".","convert_image_dtype","(","image",",","dtype","=","tf",".","float32",")","# Crop the central region of the image with an area containing 87.5% of","# the original image.","if","central_fraction",":","image","=","tf",".","image",".","central_crop","(","image",",","central_fraction","=","central_fraction",")","if","height","and","width",":","# Resize the image to the specified height and width.","image","=","tf",".","expand_dims","(","image",",","0",")","image","=","tf",".","image",".","resize_bilinear","(","image",",","[","height",",","width","]",",","align_corners","=","False",")","image","=","tf",".","squeeze","(","image",",","[","0","]",")","image","=","tf",".","subtract","(","image",",","0.5",")","image","=","tf",".","multiply","(","image",",","2.0",")","return","image"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/inception_preprocessing.py#L243-L284"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/inception_preprocessing.py","language":"python","identifier":"preprocess_image","parameters":"(image,\n height,\n width,\n is_training=False,\n bbox=None,\n fast_mode=True)","argument_list":"","return_statement":"","docstring":"Pre-process one image for training or evaluation.\n\n Args:\n image: 3-D Tensor [height, width, channels] with the image.\n height: integer, image expected height.\n width: integer, image expected width.\n is_training: Boolean. If true it would transform an image for train,\n otherwise it would transform it for evaluation.\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged as\n [ymin, xmin, ymax, xmax].\n fast_mode: Optional boolean, if True avoids slower transformations.\n\n Returns:\n 3-D float Tensor containing an appropriately scaled image\n\n Raises:\n ValueError: if user does not provide bounding box","docstring_summary":"Pre-process one image for training or evaluation.","docstring_tokens":["Pre","-","process","one","image","for","training","or","evaluation","."],"function":"def preprocess_image(image,\n height,\n width,\n is_training=False,\n bbox=None,\n fast_mode=True):\n \"\"\"Pre-process one image for training or evaluation.\n\n Args:\n image: 3-D Tensor [height, width, channels] with the image.\n height: integer, image expected height.\n width: integer, image expected width.\n is_training: Boolean. If true it would transform an image for train,\n otherwise it would transform it for evaluation.\n bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]\n where each coordinate is [0, 1) and the coordinates are arranged as\n [ymin, xmin, ymax, xmax].\n fast_mode: Optional boolean, if True avoids slower transformations.\n\n Returns:\n 3-D float Tensor containing an appropriately scaled image\n\n Raises:\n ValueError: if user does not provide bounding box\n \"\"\"\n if is_training:\n return preprocess_for_train(image, height, width, bbox, fast_mode)\n else:\n return preprocess_for_eval(image, height, width)","function_tokens":["def","preprocess_image","(","image",",","height",",","width",",","is_training","=","False",",","bbox","=","None",",","fast_mode","=","True",")",":","if","is_training",":","return","preprocess_for_train","(","image",",","height",",","width",",","bbox",",","fast_mode",")","else",":","return","preprocess_for_eval","(","image",",","height",",","width",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/inception_preprocessing.py#L287-L315"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/datasets\/fsns.py","language":"python","identifier":"read_charset","parameters":"(filename, null_character=u'\\u2591')","argument_list":"","return_statement":"return charset","docstring":"Reads a charset definition from a tab separated text file.\n\n charset file has to have format compatible with the FSNS dataset.\n\n Args:\n filename: a path to the charset file.\n null_character: a unicode character used to replace '<null>' character. the\n default value is a light shade block '\u2591'.\n\n Returns:\n a dictionary with keys equal to character codes and values - unicode\n characters.","docstring_summary":"Reads a charset definition from a tab separated text file.","docstring_tokens":["Reads","a","charset","definition","from","a","tab","separated","text","file","."],"function":"def read_charset(filename, null_character=u'\\u2591'):\n\n \"\"\"Reads a charset definition from a tab separated text file.\n\n charset file has to have format compatible with the FSNS dataset.\n\n Args:\n filename: a path to the charset file.\n null_character: a unicode character used to replace '<null>' character. the\n default value is a light shade block '\u2591'.\n\n Returns:\n a dictionary with keys equal to character codes and values - unicode\n characters.\n \"\"\"\n pattern = re.compile(r'(\\d+)\\t(.+)')\n charset = {}\n with tf.gfile.GFile(filename) as f:\n for i, line in enumerate(f):\n m = pattern.match(line)\n if m is None:\n logging.warning('incorrect charset file. line #%d: %s', i, line)\n continue\n code = int(m.group(1))\n #char = m.group(2).decode('utf-8')\n char = m.group(2)\n #print(char)\n if char == '<nul>':\n char = null_character\n charset[code] = char\n return charset","function_tokens":["def","read_charset","(","filename",",","null_character","=","u'\\u2591'",")",":","pattern","=","re",".","compile","(","r'(\\d+)\\t(.+)'",")","charset","=","{","}","with","tf",".","gfile",".","GFile","(","filename",")","as","f",":","for","i",",","line","in","enumerate","(","f",")",":","m","=","pattern",".","match","(","line",")","if","m","is","None",":","logging",".","warning","(","'incorrect charset file. line #%d: %s'",",","i",",","line",")","continue","code","=","int","(","m",".","group","(","1",")",")","#char = m.group(2).decode('utf-8')","char","=","m",".","group","(","2",")","#print(char)","if","char","==","'<nul>'",":","char","=","null_character","charset","[","code","]","=","char","return","charset"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/datasets\/fsns.py#L59-L89"}
{"nwo":"A-bone1\/Attention-ocr-Chinese-Version","sha":"a08d4e587e73bb013cd22eadae250dbbf9cff7d4","path":"python\/datasets\/fsns.py","language":"python","identifier":"get_split","parameters":"(split_name, dataset_dir=None, config=None)","argument_list":"","return_statement":"return slim.dataset.Dataset(\n data_sources=file_pattern,\n reader=tf.TFRecordReader,\n decoder=decoder,\n num_samples=config['splits'][split_name]['size'],\n items_to_descriptions=config['items_to_descriptions'],\n # additional parameters for convenience.\n charset=charset,\n num_char_classes=len(charset),\n num_of_views=config['num_of_views'],\n max_sequence_length=config['max_sequence_length'],\n null_code=config['null_code'])","docstring":"Returns a dataset tuple for FSNS dataset.\n\n Args:\n split_name: A train\/test split name.\n dataset_dir: The base directory of the dataset sources, by default it uses\n a predefined CNS path (see DEFAULT_DATASET_DIR).\n config: A dictionary with dataset configuration. If None - will use the\n DEFAULT_CONFIG.\n\n Returns:\n A `Dataset` namedtuple.\n\n Raises:\n ValueError: if `split_name` is not a valid train\/test split.","docstring_summary":"Returns a dataset tuple for FSNS dataset.","docstring_tokens":["Returns","a","dataset","tuple","for","FSNS","dataset","."],"function":"def get_split(split_name, dataset_dir=None, config=None):\n \"\"\"Returns a dataset tuple for FSNS dataset.\n\n Args:\n split_name: A train\/test split name.\n dataset_dir: The base directory of the dataset sources, by default it uses\n a predefined CNS path (see DEFAULT_DATASET_DIR).\n config: A dictionary with dataset configuration. If None - will use the\n DEFAULT_CONFIG.\n\n Returns:\n A `Dataset` namedtuple.\n\n Raises:\n ValueError: if `split_name` is not a valid train\/test split.\n \"\"\"\n if not dataset_dir:\n dataset_dir = DEFAULT_DATASET_DIR\n\n if not config:\n config = DEFAULT_CONFIG\n\n if split_name not in config['splits']:\n raise ValueError('split name %s was not recognized.' % split_name)\n\n logging.info('Using %s dataset split_name=%s dataset_dir=%s', config['name'],\n split_name, dataset_dir)\n\n # Ignores the 'image\/height' feature.\n zero = tf.zeros([1], dtype=tf.int64)\n keys_to_features = {\n 'image\/encoded':\n tf.FixedLenFeature((), tf.string, default_value=''),\n 'image\/format':\n tf.FixedLenFeature((), tf.string, default_value='png'),\n 'image\/width':\n tf.FixedLenFeature([1], tf.int64, default_value=zero),\n 'image\/orig_width':\n tf.FixedLenFeature([1], tf.int64, default_value=zero),\n 'image\/class':\n tf.FixedLenFeature([config['max_sequence_length']], tf.int64),\n 'image\/unpadded_class':\n tf.VarLenFeature(tf.int64),\n 'image\/text':\n tf.FixedLenFeature([1], tf.string, default_value=''),\n }\n items_to_handlers = {\n 'image':\n slim.tfexample_decoder.Image(\n shape=config['image_shape'],\n image_key='image\/encoded',\n format_key='image\/format'),\n 'label':\n slim.tfexample_decoder.Tensor(tensor_key='image\/class'),\n 'text':\n slim.tfexample_decoder.Tensor(tensor_key='image\/text'),\n 'num_of_views':\n _NumOfViewsHandler(\n width_key='image\/width',\n original_width_key='image\/orig_width',\n num_of_views=config['num_of_views'])\n }\n decoder = slim.tfexample_decoder.TFExampleDecoder(keys_to_features,\n items_to_handlers)\n charset_file = os.path.join(dataset_dir, config['charset_filename'])\n charset = read_charset(charset_file)\n\n print(charset)\n file_pattern = os.path.join(dataset_dir,\n config['splits'][split_name]['pattern'])\n return slim.dataset.Dataset(\n data_sources=file_pattern,\n reader=tf.TFRecordReader,\n decoder=decoder,\n num_samples=config['splits'][split_name]['size'],\n items_to_descriptions=config['items_to_descriptions'],\n # additional parameters for convenience.\n charset=charset,\n num_char_classes=len(charset),\n num_of_views=config['num_of_views'],\n max_sequence_length=config['max_sequence_length'],\n null_code=config['null_code'])","function_tokens":["def","get_split","(","split_name",",","dataset_dir","=","None",",","config","=","None",")",":","if","not","dataset_dir",":","dataset_dir","=","DEFAULT_DATASET_DIR","if","not","config",":","config","=","DEFAULT_CONFIG","if","split_name","not","in","config","[","'splits'","]",":","raise","ValueError","(","'split name %s was not recognized.'","%","split_name",")","logging",".","info","(","'Using %s dataset split_name=%s dataset_dir=%s'",",","config","[","'name'","]",",","split_name",",","dataset_dir",")","# Ignores the 'image\/height' feature.","zero","=","tf",".","zeros","(","[","1","]",",","dtype","=","tf",".","int64",")","keys_to_features","=","{","'image\/encoded'",":","tf",".","FixedLenFeature","(","(",")",",","tf",".","string",",","default_value","=","''",")",",","'image\/format'",":","tf",".","FixedLenFeature","(","(",")",",","tf",".","string",",","default_value","=","'png'",")",",","'image\/width'",":","tf",".","FixedLenFeature","(","[","1","]",",","tf",".","int64",",","default_value","=","zero",")",",","'image\/orig_width'",":","tf",".","FixedLenFeature","(","[","1","]",",","tf",".","int64",",","default_value","=","zero",")",",","'image\/class'",":","tf",".","FixedLenFeature","(","[","config","[","'max_sequence_length'","]","]",",","tf",".","int64",")",",","'image\/unpadded_class'",":","tf",".","VarLenFeature","(","tf",".","int64",")",",","'image\/text'",":","tf",".","FixedLenFeature","(","[","1","]",",","tf",".","string",",","default_value","=","''",")",",","}","items_to_handlers","=","{","'image'",":","slim",".","tfexample_decoder",".","Image","(","shape","=","config","[","'image_shape'","]",",","image_key","=","'image\/encoded'",",","format_key","=","'image\/format'",")",",","'label'",":","slim",".","tfexample_decoder",".","Tensor","(","tensor_key","=","'image\/class'",")",",","'text'",":","slim",".","tfexample_decoder",".","Tensor","(","tensor_key","=","'image\/text'",")",",","'num_of_views'",":","_NumOfViewsHandler","(","width_key","=","'image\/width'",",","original_width_key","=","'image\/orig_width'",",","num_of_views","=","config","[","'num_of_views'","]",")","}","decoder","=","slim",".","tfexample_decoder",".","TFExampleDecoder","(","keys_to_features",",","items_to_handlers",")","charset_file","=","os",".","path",".","join","(","dataset_dir",",","config","[","'charset_filename'","]",")","charset","=","read_charset","(","charset_file",")","print","(","charset",")","file_pattern","=","os",".","path",".","join","(","dataset_dir",",","config","[","'splits'","]","[","split_name","]","[","'pattern'","]",")","return","slim",".","dataset",".","Dataset","(","data_sources","=","file_pattern",",","reader","=","tf",".","TFRecordReader",",","decoder","=","decoder",",","num_samples","=","config","[","'splits'","]","[","split_name","]","[","'size'","]",",","items_to_descriptions","=","config","[","'items_to_descriptions'","]",",","# additional parameters for convenience.","charset","=","charset",",","num_char_classes","=","len","(","charset",")",",","num_of_views","=","config","[","'num_of_views'","]",",","max_sequence_length","=","config","[","'max_sequence_length'","]",",","null_code","=","config","[","'null_code'","]",")"],"url":"https:\/\/github.com\/A-bone1\/Attention-ocr-Chinese-Version\/blob\/a08d4e587e73bb013cd22eadae250dbbf9cff7d4\/python\/datasets\/fsns.py#L107-L188"}