repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
dmlc/xgboost
python-package/xgboost/core.py
_maybe_dt_array
def _maybe_dt_array(array): """ Extract numpy array from single column data table """ if not isinstance(array, DataTable) or array is None: return array if array.shape[1] > 1: raise ValueError('DataTable for label or weight cannot have multiple columns') # below requires new dt version...
python
def _maybe_dt_array(array): """ Extract numpy array from single column data table """ if not isinstance(array, DataTable) or array is None: return array if array.shape[1] > 1: raise ValueError('DataTable for label or weight cannot have multiple columns') # below requires new dt version...
[ "def", "_maybe_dt_array", "(", "array", ")", ":", "if", "not", "isinstance", "(", "array", ",", "DataTable", ")", "or", "array", "is", "None", ":", "return", "array", "if", "array", ".", "shape", "[", "1", "]", ">", "1", ":", "raise", "ValueError", "...
Extract numpy array from single column data table
[ "Extract", "numpy", "array", "from", "single", "column", "data", "table" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L306-L318
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix._init_from_csr
def _init_from_csr(self, csr): """ Initialize data from a CSR matrix. """ if len(csr.indices) != len(csr.data): raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data))) handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFro...
python
def _init_from_csr(self, csr): """ Initialize data from a CSR matrix. """ if len(csr.indices) != len(csr.data): raise ValueError('length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data))) handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFro...
[ "def", "_init_from_csr", "(", "self", ",", "csr", ")", ":", "if", "len", "(", "csr", ".", "indices", ")", "!=", "len", "(", "csr", ".", "data", ")", ":", "raise", "ValueError", "(", "'length mismatch: {} vs {}'", ".", "format", "(", "len", "(", "csr", ...
Initialize data from a CSR matrix.
[ "Initialize", "data", "from", "a", "CSR", "matrix", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L429-L443
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix._init_from_csc
def _init_from_csc(self, csc): """ Initialize data from a CSC matrix. """ if len(csc.indices) != len(csc.data): raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data))) handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFro...
python
def _init_from_csc(self, csc): """ Initialize data from a CSC matrix. """ if len(csc.indices) != len(csc.data): raise ValueError('length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data))) handle = ctypes.c_void_p() _check_call(_LIB.XGDMatrixCreateFro...
[ "def", "_init_from_csc", "(", "self", ",", "csc", ")", ":", "if", "len", "(", "csc", ".", "indices", ")", "!=", "len", "(", "csc", ".", "data", ")", ":", "raise", "ValueError", "(", "'length mismatch: {} vs {}'", ".", "format", "(", "len", "(", "csc", ...
Initialize data from a CSC matrix.
[ "Initialize", "data", "from", "a", "CSC", "matrix", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L445-L459
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix._init_from_npy2d
def _init_from_npy2d(self, mat, missing, nthread): """ Initialize data from a 2-D numpy matrix. If ``mat`` does not have ``order='C'`` (aka row-major) or is not contiguous, a temporary copy will be made. If ``mat`` does not have ``dtype=numpy.float32``, a temporary copy will be...
python
def _init_from_npy2d(self, mat, missing, nthread): """ Initialize data from a 2-D numpy matrix. If ``mat`` does not have ``order='C'`` (aka row-major) or is not contiguous, a temporary copy will be made. If ``mat`` does not have ``dtype=numpy.float32``, a temporary copy will be...
[ "def", "_init_from_npy2d", "(", "self", ",", "mat", ",", "missing", ",", "nthread", ")", ":", "if", "len", "(", "mat", ".", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Input numpy.ndarray must be 2 dimensional'", ")", "# flatten the array by rows...
Initialize data from a 2-D numpy matrix. If ``mat`` does not have ``order='C'`` (aka row-major) or is not contiguous, a temporary copy will be made. If ``mat`` does not have ``dtype=numpy.float32``, a temporary copy will be made. So there could be as many as two temporary data copies;...
[ "Initialize", "data", "from", "a", "2", "-", "D", "numpy", "matrix", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L461-L496
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix._init_from_dt
def _init_from_dt(self, data, nthread): """ Initialize data from a datatable Frame. """ ptrs = (ctypes.c_void_p * data.ncols)() if hasattr(data, "internal") and hasattr(data.internal, "column"): # datatable>0.8.0 for icol in range(data.ncols): ...
python
def _init_from_dt(self, data, nthread): """ Initialize data from a datatable Frame. """ ptrs = (ctypes.c_void_p * data.ncols)() if hasattr(data, "internal") and hasattr(data.internal, "column"): # datatable>0.8.0 for icol in range(data.ncols): ...
[ "def", "_init_from_dt", "(", "self", ",", "data", ",", "nthread", ")", ":", "ptrs", "=", "(", "ctypes", ".", "c_void_p", "*", "data", ".", "ncols", ")", "(", ")", "if", "hasattr", "(", "data", ",", "\"internal\"", ")", "and", "hasattr", "(", "data", ...
Initialize data from a datatable Frame.
[ "Initialize", "data", "from", "a", "datatable", "Frame", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L498-L527
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix.set_float_info
def set_float_info(self, field, data): """Set float type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set """ if getattr(data, 'base', None) is not...
python
def set_float_info(self, field, data): """Set float type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set """ if getattr(data, 'base', None) is not...
[ "def", "set_float_info", "(", "self", ",", "field", ",", "data", ")", ":", "if", "getattr", "(", "data", ",", "'base'", ",", "None", ")", "is", "not", "None", "and", "data", ".", "base", "is", "not", "None", "and", "isinstance", "(", "data", ",", "...
Set float type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set
[ "Set", "float", "type", "property", "into", "the", "DMatrix", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L576-L596
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix.set_float_info_npy2d
def set_float_info_npy2d(self, field, data): """Set float type property into the DMatrix for numpy 2d array input Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set """ ...
python
def set_float_info_npy2d(self, field, data): """Set float type property into the DMatrix for numpy 2d array input Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set """ ...
[ "def", "set_float_info_npy2d", "(", "self", ",", "field", ",", "data", ")", ":", "if", "getattr", "(", "data", ",", "'base'", ",", "None", ")", "is", "not", "None", "and", "data", ".", "base", "is", "not", "None", "and", "isinstance", "(", "data", ",...
Set float type property into the DMatrix for numpy 2d array input Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set
[ "Set", "float", "type", "property", "into", "the", "DMatrix", "for", "numpy", "2d", "array", "input" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L598-L622
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix.set_uint_info
def set_uint_info(self, field, data): """Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set """ if getattr(data, 'base', None) is not N...
python
def set_uint_info(self, field, data): """Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set """ if getattr(data, 'base', None) is not N...
[ "def", "set_uint_info", "(", "self", ",", "field", ",", "data", ")", ":", "if", "getattr", "(", "data", ",", "'base'", ",", "None", ")", "is", "not", "None", "and", "data", ".", "base", "is", "not", "None", "and", "isinstance", "(", "data", ",", "n...
Set uint type property into the DMatrix. Parameters ---------- field: str The field name of the information data: numpy array The array of data to be set
[ "Set", "uint", "type", "property", "into", "the", "DMatrix", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L624-L646
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix.save_binary
def save_binary(self, fname, silent=True): """Save DMatrix to an XGBoost buffer. Saved binary can be later loaded by providing the path to :py:func:`xgboost.DMatrix` as input. Parameters ---------- fname : string Name of the output buffer file. silent : bool...
python
def save_binary(self, fname, silent=True): """Save DMatrix to an XGBoost buffer. Saved binary can be later loaded by providing the path to :py:func:`xgboost.DMatrix` as input. Parameters ---------- fname : string Name of the output buffer file. silent : bool...
[ "def", "save_binary", "(", "self", ",", "fname", ",", "silent", "=", "True", ")", ":", "_check_call", "(", "_LIB", ".", "XGDMatrixSaveBinary", "(", "self", ".", "handle", ",", "c_str", "(", "fname", ")", ",", "ctypes", ".", "c_int", "(", "silent", ")",...
Save DMatrix to an XGBoost buffer. Saved binary can be later loaded by providing the path to :py:func:`xgboost.DMatrix` as input. Parameters ---------- fname : string Name of the output buffer file. silent : bool (optional; default: True) If set, the out...
[ "Save", "DMatrix", "to", "an", "XGBoost", "buffer", ".", "Saved", "binary", "can", "be", "later", "loaded", "by", "providing", "the", "path", "to", ":", "py", ":", "func", ":", "xgboost", ".", "DMatrix", "as", "input", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L648-L661
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix.set_group
def set_group(self, group): """Set group size of DMatrix (used for ranking). Parameters ---------- group : array like Group size of each group """ _check_call(_LIB.XGDMatrixSetGroup(self.handle, c_array(ctypes.c_uint...
python
def set_group(self, group): """Set group size of DMatrix (used for ranking). Parameters ---------- group : array like Group size of each group """ _check_call(_LIB.XGDMatrixSetGroup(self.handle, c_array(ctypes.c_uint...
[ "def", "set_group", "(", "self", ",", "group", ")", ":", "_check_call", "(", "_LIB", ".", "XGDMatrixSetGroup", "(", "self", ".", "handle", ",", "c_array", "(", "ctypes", ".", "c_uint", ",", "group", ")", ",", "c_bst_ulong", "(", "len", "(", "group", ")...
Set group size of DMatrix (used for ranking). Parameters ---------- group : array like Group size of each group
[ "Set", "group", "size", "of", "DMatrix", "(", "used", "for", "ranking", ")", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L735-L745
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix.feature_names
def feature_names(self): """Get feature names (column labels). Returns ------- feature_names : list or None """ if self._feature_names is None: self._feature_names = ['f{0}'.format(i) for i in range(self.num_col())] return self._feature_names
python
def feature_names(self): """Get feature names (column labels). Returns ------- feature_names : list or None """ if self._feature_names is None: self._feature_names = ['f{0}'.format(i) for i in range(self.num_col())] return self._feature_names
[ "def", "feature_names", "(", "self", ")", ":", "if", "self", ".", "_feature_names", "is", "None", ":", "self", ".", "_feature_names", "=", "[", "'f{0}'", ".", "format", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "num_col", "(", ")", ...
Get feature names (column labels). Returns ------- feature_names : list or None
[ "Get", "feature", "names", "(", "column", "labels", ")", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L821-L830
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix.feature_names
def feature_names(self, feature_names): """Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names """ if feature_names is not None: # validate feature name ...
python
def feature_names(self, feature_names): """Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names """ if feature_names is not None: # validate feature name ...
[ "def", "feature_names", "(", "self", ",", "feature_names", ")", ":", "if", "feature_names", "is", "not", "None", ":", "# validate feature name", "try", ":", "if", "not", "isinstance", "(", "feature_names", ",", "str", ")", ":", "feature_names", "=", "[", "n"...
Set feature names (column labels). Parameters ---------- feature_names : list or None Labels for features. None will reset existing feature names
[ "Set", "feature", "names", "(", "column", "labels", ")", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L843-L874
train
dmlc/xgboost
python-package/xgboost/core.py
DMatrix.feature_types
def feature_types(self, feature_types): """Set feature types (column types). This is for displaying the results and unrelated to the learning process. Parameters ---------- feature_types : list or None Labels for features. None will reset existing feature na...
python
def feature_types(self, feature_types): """Set feature types (column types). This is for displaying the results and unrelated to the learning process. Parameters ---------- feature_types : list or None Labels for features. None will reset existing feature na...
[ "def", "feature_types", "(", "self", ",", "feature_types", ")", ":", "if", "feature_types", "is", "not", "None", ":", "if", "self", ".", "_feature_names", "is", "None", ":", "msg", "=", "'Unable to set feature types before setting names'", "raise", "ValueError", "...
Set feature types (column types). This is for displaying the results and unrelated to the learning process. Parameters ---------- feature_types : list or None Labels for features. None will reset existing feature names
[ "Set", "feature", "types", "(", "column", "types", ")", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L877-L913
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.load_rabit_checkpoint
def load_rabit_checkpoint(self): """Initialize the model by load from rabit checkpoint. Returns ------- version: integer The version number of the model. """ version = ctypes.c_int() _check_call(_LIB.XGBoosterLoadRabitCheckpoint( self.hand...
python
def load_rabit_checkpoint(self): """Initialize the model by load from rabit checkpoint. Returns ------- version: integer The version number of the model. """ version = ctypes.c_int() _check_call(_LIB.XGBoosterLoadRabitCheckpoint( self.hand...
[ "def", "load_rabit_checkpoint", "(", "self", ")", ":", "version", "=", "ctypes", ".", "c_int", "(", ")", "_check_call", "(", "_LIB", ".", "XGBoosterLoadRabitCheckpoint", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "version", ")", ")", ")"...
Initialize the model by load from rabit checkpoint. Returns ------- version: integer The version number of the model.
[ "Initialize", "the", "model", "by", "load", "from", "rabit", "checkpoint", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1002-L1013
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.attr
def attr(self, key): """Get attribute string from the Booster. Parameters ---------- key : str The key to get attribute from. Returns ------- value : str The attribute value of the key, returns None if attribute do not exist. """ ...
python
def attr(self, key): """Get attribute string from the Booster. Parameters ---------- key : str The key to get attribute from. Returns ------- value : str The attribute value of the key, returns None if attribute do not exist. """ ...
[ "def", "attr", "(", "self", ",", "key", ")", ":", "ret", "=", "ctypes", ".", "c_char_p", "(", ")", "success", "=", "ctypes", ".", "c_int", "(", ")", "_check_call", "(", "_LIB", ".", "XGBoosterGetAttr", "(", "self", ".", "handle", ",", "c_str", "(", ...
Get attribute string from the Booster. Parameters ---------- key : str The key to get attribute from. Returns ------- value : str The attribute value of the key, returns None if attribute do not exist.
[ "Get", "attribute", "string", "from", "the", "Booster", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1019-L1038
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.attributes
def attributes(self): """Get attributes stored in the Booster as a dictionary. Returns ------- result : dictionary of attribute_name: attribute_value pairs of strings. Returns an empty dict if there's no attributes. """ length = c_bst_ulong() sarr = ...
python
def attributes(self): """Get attributes stored in the Booster as a dictionary. Returns ------- result : dictionary of attribute_name: attribute_value pairs of strings. Returns an empty dict if there's no attributes. """ length = c_bst_ulong() sarr = ...
[ "def", "attributes", "(", "self", ")", ":", "length", "=", "c_bst_ulong", "(", ")", "sarr", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char_p", ")", "(", ")", "_check_call", "(", "_LIB", ".", "XGBoosterGetAttrNames", "(", "self", ".", "handle"...
Get attributes stored in the Booster as a dictionary. Returns ------- result : dictionary of attribute_name: attribute_value pairs of strings. Returns an empty dict if there's no attributes.
[ "Get", "attributes", "stored", "in", "the", "Booster", "as", "a", "dictionary", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1040-L1054
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.set_attr
def set_attr(self, **kwargs): """Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute. """ for key, value in kwargs.items(): if value is not None: if n...
python
def set_attr(self, **kwargs): """Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute. """ for key, value in kwargs.items(): if value is not None: if n...
[ "def", "set_attr", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", ":", "if", "not", "isinstance", "(", "value", ",", "STRING_TYPES", ")", ...
Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute.
[ "Set", "the", "attribute", "of", "the", "Booster", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1056-L1070
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.set_param
def set_param(self, params, value=None): """Set parameters into the Booster. Parameters ---------- params: dict/list/str list of key,value pairs, dict of key to value or simply str key value: optional value of the specified parameter, when params is str key...
python
def set_param(self, params, value=None): """Set parameters into the Booster. Parameters ---------- params: dict/list/str list of key,value pairs, dict of key to value or simply str key value: optional value of the specified parameter, when params is str key...
[ "def", "set_param", "(", "self", ",", "params", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "params", ",", "Mapping", ")", ":", "params", "=", "params", ".", "items", "(", ")", "elif", "isinstance", "(", "params", ",", "STRING_TYPES",...
Set parameters into the Booster. Parameters ---------- params: dict/list/str list of key,value pairs, dict of key to value or simply str key value: optional value of the specified parameter, when params is str key
[ "Set", "parameters", "into", "the", "Booster", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1072-L1087
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.eval
def eval(self, data, name='eval', iteration=0): """Evaluate the model on mat. Parameters ---------- data : DMatrix The dmatrix storing the input. name : str, optional The name of the dataset. iteration : int, optional The current ite...
python
def eval(self, data, name='eval', iteration=0): """Evaluate the model on mat. Parameters ---------- data : DMatrix The dmatrix storing the input. name : str, optional The name of the dataset. iteration : int, optional The current ite...
[ "def", "eval", "(", "self", ",", "data", ",", "name", "=", "'eval'", ",", "iteration", "=", "0", ")", ":", "self", ".", "_validate_features", "(", "data", ")", "return", "self", ".", "eval_set", "(", "[", "(", "data", ",", "name", ")", "]", ",", ...
Evaluate the model on mat. Parameters ---------- data : DMatrix The dmatrix storing the input. name : str, optional The name of the dataset. iteration : int, optional The current iteration number. Returns ------- res...
[ "Evaluate", "the", "model", "on", "mat", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1185-L1205
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.predict
def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False, pred_contribs=False, approx_contribs=False, pred_interactions=False, validate_features=True): """ Predict with data. .. note:: This function is not thread safe. For each boost...
python
def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False, pred_contribs=False, approx_contribs=False, pred_interactions=False, validate_features=True): """ Predict with data. .. note:: This function is not thread safe. For each boost...
[ "def", "predict", "(", "self", ",", "data", ",", "output_margin", "=", "False", ",", "ntree_limit", "=", "0", ",", "pred_leaf", "=", "False", ",", "pred_contribs", "=", "False", ",", "approx_contribs", "=", "False", ",", "pred_interactions", "=", "False", ...
Predict with data. .. note:: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call ``bst.copy()`` to make copies of model object and then call ``predict()``. .. not...
[ "Predict", "with", "data", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1207-L1314
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.save_model
def save_model(self, fname): """ Save the model to a file. The model is saved in an XGBoost internal binary format which is universal among the various XGBoost interfaces. Auxiliary attributes of the Python Booster object (such as feature_names) will not be saved. To pre...
python
def save_model(self, fname): """ Save the model to a file. The model is saved in an XGBoost internal binary format which is universal among the various XGBoost interfaces. Auxiliary attributes of the Python Booster object (such as feature_names) will not be saved. To pre...
[ "def", "save_model", "(", "self", ",", "fname", ")", ":", "if", "isinstance", "(", "fname", ",", "STRING_TYPES", ")", ":", "# assume file name", "_check_call", "(", "_LIB", ".", "XGBoosterSaveModel", "(", "self", ".", "handle", ",", "c_str", "(", "fname", ...
Save the model to a file. The model is saved in an XGBoost internal binary format which is universal among the various XGBoost interfaces. Auxiliary attributes of the Python Booster object (such as feature_names) will not be saved. To preserve all attributes, pickle the Booster object. ...
[ "Save", "the", "model", "to", "a", "file", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1316-L1333
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.load_model
def load_model(self, fname): """ Load the model from a file. The model is loaded from an XGBoost internal binary format which is universal among the various XGBoost interfaces. Auxiliary attributes of the Python Booster object (such as feature_names) will not be loaded. ...
python
def load_model(self, fname): """ Load the model from a file. The model is loaded from an XGBoost internal binary format which is universal among the various XGBoost interfaces. Auxiliary attributes of the Python Booster object (such as feature_names) will not be loaded. ...
[ "def", "load_model", "(", "self", ",", "fname", ")", ":", "if", "isinstance", "(", "fname", ",", "STRING_TYPES", ")", ":", "# assume file name, cannot use os.path.exist to check, file can be from URL.", "_check_call", "(", "_LIB", ".", "XGBoosterLoadModel", "(", "self",...
Load the model from a file. The model is loaded from an XGBoost internal binary format which is universal among the various XGBoost interfaces. Auxiliary attributes of the Python Booster object (such as feature_names) will not be loaded. To preserve all attributes, pickle the Booster ob...
[ "Load", "the", "model", "from", "a", "file", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1350-L1371
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.dump_model
def dump_model(self, fout, fmap='', with_stats=False, dump_format="text"): """ Dump model into a text or JSON file. Parameters ---------- fout : string Output file name. fmap : string, optional Name of the file containing feature map names. ...
python
def dump_model(self, fout, fmap='', with_stats=False, dump_format="text"): """ Dump model into a text or JSON file. Parameters ---------- fout : string Output file name. fmap : string, optional Name of the file containing feature map names. ...
[ "def", "dump_model", "(", "self", ",", "fout", ",", "fmap", "=", "''", ",", "with_stats", "=", "False", ",", "dump_format", "=", "\"text\"", ")", ":", "if", "isinstance", "(", "fout", ",", "STRING_TYPES", ")", ":", "fout", "=", "open", "(", "fout", "...
Dump model into a text or JSON file. Parameters ---------- fout : string Output file name. fmap : string, optional Name of the file containing feature map names. with_stats : bool, optional Controls whether the split statistics are output. ...
[ "Dump", "model", "into", "a", "text", "or", "JSON", "file", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1373-L1406
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.get_dump
def get_dump(self, fmap='', with_stats=False, dump_format="text"): """ Returns the model dump as a list of strings. Parameters ---------- fmap : string, optional Name of the file containing feature map names. with_stats : bool, optional Controls w...
python
def get_dump(self, fmap='', with_stats=False, dump_format="text"): """ Returns the model dump as a list of strings. Parameters ---------- fmap : string, optional Name of the file containing feature map names. with_stats : bool, optional Controls w...
[ "def", "get_dump", "(", "self", ",", "fmap", "=", "''", ",", "with_stats", "=", "False", ",", "dump_format", "=", "\"text\"", ")", ":", "length", "=", "c_bst_ulong", "(", ")", "sarr", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char_p", ")", ...
Returns the model dump as a list of strings. Parameters ---------- fmap : string, optional Name of the file containing feature map names. with_stats : bool, optional Controls whether the split statistics are output. dump_format : string, optional ...
[ "Returns", "the", "model", "dump", "as", "a", "list", "of", "strings", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1408-L1453
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.get_score
def get_score(self, fmap='', importance_type='weight'): """Get feature importance of each feature. Importance type can be defined as: * 'weight': the number of times a feature is used to split the data across all trees. * 'gain': the average gain across all splits the feature is used in...
python
def get_score(self, fmap='', importance_type='weight'): """Get feature importance of each feature. Importance type can be defined as: * 'weight': the number of times a feature is used to split the data across all trees. * 'gain': the average gain across all splits the feature is used in...
[ "def", "get_score", "(", "self", ",", "fmap", "=", "''", ",", "importance_type", "=", "'weight'", ")", ":", "if", "getattr", "(", "self", ",", "'booster'", ",", "None", ")", "is", "not", "None", "and", "self", ".", "booster", "not", "in", "{", "'gbtr...
Get feature importance of each feature. Importance type can be defined as: * 'weight': the number of times a feature is used to split the data across all trees. * 'gain': the average gain across all splits the feature is used in. * 'cover': the average coverage across all splits the fea...
[ "Get", "feature", "importance", "of", "each", "feature", ".", "Importance", "type", "can", "be", "defined", "as", ":" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1477-L1578
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.trees_to_dataframe
def trees_to_dataframe(self, fmap=''): """Parse a boosted tree model text dump into a pandas DataFrame structure. This feature is only defined when the decision tree model is chosen as base learner (`booster in {gbtree, dart}`). It is not defined for other base learner types, such as li...
python
def trees_to_dataframe(self, fmap=''): """Parse a boosted tree model text dump into a pandas DataFrame structure. This feature is only defined when the decision tree model is chosen as base learner (`booster in {gbtree, dart}`). It is not defined for other base learner types, such as li...
[ "def", "trees_to_dataframe", "(", "self", ",", "fmap", "=", "''", ")", ":", "# pylint: disable=too-many-locals", "if", "not", "PANDAS_INSTALLED", ":", "raise", "Exception", "(", "(", "'pandas must be available to use this method.'", "'Install pandas before calling again.'", ...
Parse a boosted tree model text dump into a pandas DataFrame structure. This feature is only defined when the decision tree model is chosen as base learner (`booster in {gbtree, dart}`). It is not defined for other base learner types, such as linear learners (`booster=gblinear`). Param...
[ "Parse", "a", "boosted", "tree", "model", "text", "dump", "into", "a", "pandas", "DataFrame", "structure", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1580-L1663
train
dmlc/xgboost
python-package/xgboost/core.py
Booster._validate_features
def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
python
def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
[ "def", "_validate_features", "(", "self", ",", "data", ")", ":", "if", "self", ".", "feature_names", "is", "None", ":", "self", ".", "feature_names", "=", "data", ".", "feature_names", "self", ".", "feature_types", "=", "data", ".", "feature_types", "else", ...
Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix
[ "Validate", "Booster", "and", "data", "s", "feature_names", "are", "identical", ".", "Set", "feature_names", "and", "feature_types", "from", "DMatrix" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1665-L1690
train
dmlc/xgboost
python-package/xgboost/core.py
Booster.get_split_value_histogram
def get_split_value_histogram(self, feature, fmap='', bins=None, as_pandas=True): """Get split value histogram of a feature Parameters ---------- feature: str The name of the feature. fmap: str (optional) The name of feature map file. bin: int, de...
python
def get_split_value_histogram(self, feature, fmap='', bins=None, as_pandas=True): """Get split value histogram of a feature Parameters ---------- feature: str The name of the feature. fmap: str (optional) The name of feature map file. bin: int, de...
[ "def", "get_split_value_histogram", "(", "self", ",", "feature", ",", "fmap", "=", "''", ",", "bins", "=", "None", ",", "as_pandas", "=", "True", ")", ":", "xgdump", "=", "self", ".", "get_dump", "(", "fmap", "=", "fmap", ")", "values", "=", "[", "]"...
Get split value histogram of a feature Parameters ---------- feature: str The name of the feature. fmap: str (optional) The name of feature map file. bin: int, default None The maximum number of bins. Number of bins equals number o...
[ "Get", "split", "value", "histogram", "of", "a", "feature" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1692-L1733
train
dmlc/xgboost
python-package/xgboost/plotting.py
plot_importance
def plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='F score', ylabel='Features', importance_type='weight', max_num_features=None, grid=True, show_values=True, **kwargs): """Plot im...
python
def plot_importance(booster, ax=None, height=0.2, xlim=None, ylim=None, title='Feature importance', xlabel='F score', ylabel='Features', importance_type='weight', max_num_features=None, grid=True, show_values=True, **kwargs): """Plot im...
[ "def", "plot_importance", "(", "booster", ",", "ax", "=", "None", ",", "height", "=", "0.2", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "title", "=", "'Feature importance'", ",", "xlabel", "=", "'F score'", ",", "ylabel", "=", "'Features'",...
Plot importance based on fitted trees. Parameters ---------- booster : Booster, XGBModel or dict Booster or XGBModel instance, or dict taken by Booster.get_fscore() ax : matplotlib Axes, default None Target axes instance. If None, new figure and axes will be created. grid : bool, Tu...
[ "Plot", "importance", "based", "on", "fitted", "trees", "." ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/plotting.py#L14-L117
train
dmlc/xgboost
python-package/xgboost/plotting.py
_parse_node
def _parse_node(graph, text, condition_node_params, leaf_node_params): """parse dumped node""" match = _NODEPAT.match(text) if match is not None: node = match.group(1) graph.node(node, label=match.group(2), **condition_node_params) return node match = _LEAFPAT.match(text) if ...
python
def _parse_node(graph, text, condition_node_params, leaf_node_params): """parse dumped node""" match = _NODEPAT.match(text) if match is not None: node = match.group(1) graph.node(node, label=match.group(2), **condition_node_params) return node match = _LEAFPAT.match(text) if ...
[ "def", "_parse_node", "(", "graph", ",", "text", ",", "condition_node_params", ",", "leaf_node_params", ")", ":", "match", "=", "_NODEPAT", ".", "match", "(", "text", ")", "if", "match", "is", "not", "None", ":", "node", "=", "match", ".", "group", "(", ...
parse dumped node
[ "parse", "dumped", "node" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/plotting.py#L126-L138
train
dmlc/xgboost
python-package/xgboost/plotting.py
_parse_edge
def _parse_edge(graph, node, text, yes_color='#0000FF', no_color='#FF0000'): """parse dumped edge""" try: match = _EDGEPAT.match(text) if match is not None: yes, no, missing = match.groups() if yes == missing: graph.edge(node, yes, label='yes, missing', co...
python
def _parse_edge(graph, node, text, yes_color='#0000FF', no_color='#FF0000'): """parse dumped edge""" try: match = _EDGEPAT.match(text) if match is not None: yes, no, missing = match.groups() if yes == missing: graph.edge(node, yes, label='yes, missing', co...
[ "def", "_parse_edge", "(", "graph", ",", "node", ",", "text", ",", "yes_color", "=", "'#0000FF'", ",", "no_color", "=", "'#FF0000'", ")", ":", "try", ":", "match", "=", "_EDGEPAT", ".", "match", "(", "text", ")", "if", "match", "is", "not", "None", "...
parse dumped edge
[ "parse", "dumped", "edge" ]
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/plotting.py#L141-L162
train
dmlc/xgboost
python-package/xgboost/plotting.py
to_graphviz
def to_graphviz(booster, fmap='', num_trees=0, rankdir='UT', yes_color='#0000FF', no_color='#FF0000', condition_node_params=None, leaf_node_params=None, **kwargs): """Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherw...
python
def to_graphviz(booster, fmap='', num_trees=0, rankdir='UT', yes_color='#0000FF', no_color='#FF0000', condition_node_params=None, leaf_node_params=None, **kwargs): """Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherw...
[ "def", "to_graphviz", "(", "booster", ",", "fmap", "=", "''", ",", "num_trees", "=", "0", ",", "rankdir", "=", "'UT'", ",", "yes_color", "=", "'#0000FF'", ",", "no_color", "=", "'#FF0000'", ",", "condition_node_params", "=", "None", ",", "leaf_node_params", ...
Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherwise, you should call .render() method of the returned graphiz instance. Parameters ---------- booster : Booster, XGBModel Booster or XGBModel instance fmap: str (optional) ...
[ "Convert", "specified", "tree", "to", "graphviz", "instance", ".", "IPython", "can", "automatically", "plot", "the", "returned", "graphiz", "instance", ".", "Otherwise", "you", "should", "call", ".", "render", "()", "method", "of", "the", "returned", "graphiz", ...
253fdd8a42d5ec6b819788199584d27bf9ea6253
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/plotting.py#L165-L241
train
tzutalin/labelImg
libs/utils.py
newAction
def newAction(parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, enabled=True): """Create a new action and assign callbacks, shortcuts, etc.""" a = QAction(text, parent) if icon is not None: a.setIcon(newIcon(icon)) if shortcut is not None: if isi...
python
def newAction(parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, enabled=True): """Create a new action and assign callbacks, shortcuts, etc.""" a = QAction(text, parent) if icon is not None: a.setIcon(newIcon(icon)) if shortcut is not None: if isi...
[ "def", "newAction", "(", "parent", ",", "text", ",", "slot", "=", "None", ",", "shortcut", "=", "None", ",", "icon", "=", "None", ",", "tip", "=", "None", ",", "checkable", "=", "False", ",", "enabled", "=", "True", ")", ":", "a", "=", "QAction", ...
Create a new action and assign callbacks, shortcuts, etc.
[ "Create", "a", "new", "action", "and", "assign", "callbacks", "shortcuts", "etc", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/utils.py#L29-L48
train
tzutalin/labelImg
libs/utils.py
natural_sort
def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. """ def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))] sort_key = get_alphanum_key_...
python
def natural_sort(list, key=lambda s:s): """ Sort the list into natural alphanumeric order. """ def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))] sort_key = get_alphanum_key_...
[ "def", "natural_sort", "(", "list", ",", "key", "=", "lambda", "s", ":", "s", ")", ":", "def", "get_alphanum_key_func", "(", "key", ")", ":", "convert", "=", "lambda", "text", ":", "int", "(", "text", ")", "if", "text", ".", "isdigit", "(", ")", "e...
Sort the list into natural alphanumeric order.
[ "Sort", "the", "list", "into", "natural", "alphanumeric", "order", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/utils.py#L95-L103
train
tzutalin/labelImg
libs/canvas.py
Canvas.mouseMoveEvent
def mouseMoveEvent(self, ev): """Update line with last point and current coordinates.""" pos = self.transformPos(ev.pos()) # Update coordinates in status bar if image is opened window = self.parent().window() if window.filePath is not None: self.parent().window().lab...
python
def mouseMoveEvent(self, ev): """Update line with last point and current coordinates.""" pos = self.transformPos(ev.pos()) # Update coordinates in status bar if image is opened window = self.parent().window() if window.filePath is not None: self.parent().window().lab...
[ "def", "mouseMoveEvent", "(", "self", ",", "ev", ")", ":", "pos", "=", "self", ".", "transformPos", "(", "ev", ".", "pos", "(", ")", ")", "# Update coordinates in status bar if image is opened", "window", "=", "self", ".", "parent", "(", ")", ".", "window", ...
Update line with last point and current coordinates.
[ "Update", "line", "with", "last", "point", "and", "current", "coordinates", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L104-L208
train
tzutalin/labelImg
libs/canvas.py
Canvas.selectShapePoint
def selectShapePoint(self, point): """Select the first shape created which contains this point.""" self.deSelectShape() if self.selectedVertex(): # A vertex is marked for selection. index, shape = self.hVertex, self.hShape shape.highlightVertex(index, shape.MOVE_VERTEX) ...
python
def selectShapePoint(self, point): """Select the first shape created which contains this point.""" self.deSelectShape() if self.selectedVertex(): # A vertex is marked for selection. index, shape = self.hVertex, self.hShape shape.highlightVertex(index, shape.MOVE_VERTEX) ...
[ "def", "selectShapePoint", "(", "self", ",", "point", ")", ":", "self", ".", "deSelectShape", "(", ")", "if", "self", ".", "selectedVertex", "(", ")", ":", "# A vertex is marked for selection.", "index", ",", "shape", "=", "self", ".", "hVertex", ",", "self"...
Select the first shape created which contains this point.
[ "Select", "the", "first", "shape", "created", "which", "contains", "this", "point", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L307-L319
train
tzutalin/labelImg
libs/canvas.py
Canvas.snapPointToCanvas
def snapPointToCanvas(self, x, y): """ Moves a point x,y to within the boundaries of the canvas. :return: (x,y,snapped) where snapped is True if x or y were changed, False if not. """ if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height(): x = max(x,...
python
def snapPointToCanvas(self, x, y): """ Moves a point x,y to within the boundaries of the canvas. :return: (x,y,snapped) where snapped is True if x or y were changed, False if not. """ if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height(): x = max(x,...
[ "def", "snapPointToCanvas", "(", "self", ",", "x", ",", "y", ")", ":", "if", "x", "<", "0", "or", "x", ">", "self", ".", "pixmap", ".", "width", "(", ")", "or", "y", "<", "0", "or", "y", ">", "self", ".", "pixmap", ".", "height", "(", ")", ...
Moves a point x,y to within the boundaries of the canvas. :return: (x,y,snapped) where snapped is True if x or y were changed, False if not.
[ "Moves", "a", "point", "x", "y", "to", "within", "the", "boundaries", "of", "the", "canvas", ".", ":", "return", ":", "(", "x", "y", "snapped", ")", "where", "snapped", "is", "True", "if", "x", "or", "y", "were", "changed", "False", "if", "not", "....
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L329-L341
train
tzutalin/labelImg
libs/canvas.py
Canvas.intersectingEdges
def intersectingEdges(self, x1y1, x2y2, points): """For each edge formed by `points', yield the intersection with the line segment `(x1,y1) - (x2,y2)`, if it exists. Also return the distance of `(x2,y2)' to the middle of the edge along with its index, so that the one closest can be chose...
python
def intersectingEdges(self, x1y1, x2y2, points): """For each edge formed by `points', yield the intersection with the line segment `(x1,y1) - (x2,y2)`, if it exists. Also return the distance of `(x2,y2)' to the middle of the edge along with its index, so that the one closest can be chose...
[ "def", "intersectingEdges", "(", "self", ",", "x1y1", ",", "x2y2", ",", "points", ")", ":", "x1", ",", "y1", "=", "x1y1", "x2", ",", "y2", "=", "x2y2", "for", "i", "in", "range", "(", "4", ")", ":", "x3", ",", "y3", "=", "points", "[", "i", "...
For each edge formed by `points', yield the intersection with the line segment `(x1,y1) - (x2,y2)`, if it exists. Also return the distance of `(x2,y2)' to the middle of the edge along with its index, so that the one closest can be chosen.
[ "For", "each", "edge", "formed", "by", "points", "yield", "the", "intersection", "with", "the", "line", "segment", "(", "x1", "y1", ")", "-", "(", "x2", "y2", ")", "if", "it", "exists", ".", "Also", "return", "the", "distance", "of", "(", "x2", "y2",...
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/canvas.py#L551-L575
train
tzutalin/labelImg
labelImg.py
get_main_app
def get_main_app(argv=[]): """ Standard boilerplate Qt application code. Do everything but app.exec_() -- so that we can test the application in one thread """ app = QApplication(argv) app.setApplicationName(__appname__) app.setWindowIcon(newIcon("app")) # Tzutalin 201705+: Accept extra ...
python
def get_main_app(argv=[]): """ Standard boilerplate Qt application code. Do everything but app.exec_() -- so that we can test the application in one thread """ app = QApplication(argv) app.setApplicationName(__appname__) app.setWindowIcon(newIcon("app")) # Tzutalin 201705+: Accept extra ...
[ "def", "get_main_app", "(", "argv", "=", "[", "]", ")", ":", "app", "=", "QApplication", "(", "argv", ")", "app", ".", "setApplicationName", "(", "__appname__", ")", "app", ".", "setWindowIcon", "(", "newIcon", "(", "\"app\"", ")", ")", "# Tzutalin 201705+...
Standard boilerplate Qt application code. Do everything but app.exec_() -- so that we can test the application in one thread
[ "Standard", "boilerplate", "Qt", "application", "code", ".", "Do", "everything", "but", "app", ".", "exec_", "()", "--", "so", "that", "we", "can", "test", "the", "application", "in", "one", "thread" ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L1450-L1466
train
tzutalin/labelImg
labelImg.py
MainWindow.toggleActions
def toggleActions(self, value=True): """Enable/Disable widgets which depend on an opened image.""" for z in self.actions.zoomActions: z.setEnabled(value) for action in self.actions.onLoadActive: action.setEnabled(value)
python
def toggleActions(self, value=True): """Enable/Disable widgets which depend on an opened image.""" for z in self.actions.zoomActions: z.setEnabled(value) for action in self.actions.onLoadActive: action.setEnabled(value)
[ "def", "toggleActions", "(", "self", ",", "value", "=", "True", ")", ":", "for", "z", "in", "self", ".", "actions", ".", "zoomActions", ":", "z", ".", "setEnabled", "(", "value", ")", "for", "action", "in", "self", ".", "actions", ".", "onLoadActive", ...
Enable/Disable widgets which depend on an opened image.
[ "Enable", "/", "Disable", "widgets", "which", "depend", "on", "an", "opened", "image", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L556-L561
train
tzutalin/labelImg
labelImg.py
MainWindow.toggleDrawingSensitive
def toggleDrawingSensitive(self, drawing=True): """In the middle of drawing, toggling between modes should be disabled.""" self.actions.editMode.setEnabled(not drawing) if not drawing and self.beginner(): # Cancel creation. print('Cancel creation.') self.canva...
python
def toggleDrawingSensitive(self, drawing=True): """In the middle of drawing, toggling between modes should be disabled.""" self.actions.editMode.setEnabled(not drawing) if not drawing and self.beginner(): # Cancel creation. print('Cancel creation.') self.canva...
[ "def", "toggleDrawingSensitive", "(", "self", ",", "drawing", "=", "True", ")", ":", "self", ".", "actions", ".", "editMode", ".", "setEnabled", "(", "not", "drawing", ")", "if", "not", "drawing", "and", "self", ".", "beginner", "(", ")", ":", "# Cancel ...
In the middle of drawing, toggling between modes should be disabled.
[ "In", "the", "middle", "of", "drawing", "toggling", "between", "modes", "should", "be", "disabled", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L621-L629
train
tzutalin/labelImg
labelImg.py
MainWindow.btnstate
def btnstate(self, item= None): """ Function to handle difficult examples Update on each object """ if not self.canvas.editing(): return item = self.currentItem() if not item: # If not selected Item, take the first one item = self.labelList.item(self.labe...
python
def btnstate(self, item= None): """ Function to handle difficult examples Update on each object """ if not self.canvas.editing(): return item = self.currentItem() if not item: # If not selected Item, take the first one item = self.labelList.item(self.labe...
[ "def", "btnstate", "(", "self", ",", "item", "=", "None", ")", ":", "if", "not", "self", ".", "canvas", ".", "editing", "(", ")", ":", "return", "item", "=", "self", ".", "currentItem", "(", ")", "if", "not", "item", ":", "# If not selected Item, take ...
Function to handle difficult examples Update on each object
[ "Function", "to", "handle", "difficult", "examples", "Update", "on", "each", "object" ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L685-L709
train
tzutalin/labelImg
labelImg.py
MainWindow.newShape
def newShape(self): """Pop-up and give focus to the label editor. position MUST be in global coordinates. """ if not self.useDefaultLabelCheckbox.isChecked() or not self.defaultLabelTextLine.text(): if len(self.labelHist) > 0: self.labelDialog = LabelDialog( ...
python
def newShape(self): """Pop-up and give focus to the label editor. position MUST be in global coordinates. """ if not self.useDefaultLabelCheckbox.isChecked() or not self.defaultLabelTextLine.text(): if len(self.labelHist) > 0: self.labelDialog = LabelDialog( ...
[ "def", "newShape", "(", "self", ")", ":", "if", "not", "self", ".", "useDefaultLabelCheckbox", ".", "isChecked", "(", ")", "or", "not", "self", ".", "defaultLabelTextLine", ".", "text", "(", ")", ":", "if", "len", "(", "self", ".", "labelHist", ")", ">...
Pop-up and give focus to the label editor. position MUST be in global coordinates.
[ "Pop", "-", "up", "and", "give", "focus", "to", "the", "label", "editor", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L839-L876
train
tzutalin/labelImg
labelImg.py
MainWindow.loadFile
def loadFile(self, filePath=None): """Load the specified file, or the last opened file if None.""" self.resetState() self.canvas.setEnabled(False) if filePath is None: filePath = self.settings.get(SETTING_FILENAME) # Make sure that filePath is a regular python string...
python
def loadFile(self, filePath=None): """Load the specified file, or the last opened file if None.""" self.resetState() self.canvas.setEnabled(False) if filePath is None: filePath = self.settings.get(SETTING_FILENAME) # Make sure that filePath is a regular python string...
[ "def", "loadFile", "(", "self", ",", "filePath", "=", "None", ")", ":", "self", ".", "resetState", "(", ")", "self", ".", "canvas", ".", "setEnabled", "(", "False", ")", "if", "filePath", "is", "None", ":", "filePath", "=", "self", ".", "settings", "...
Load the specified file, or the last opened file if None.
[ "Load", "the", "specified", "file", "or", "the", "last", "opened", "file", "if", "None", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L960-L1051
train
tzutalin/labelImg
labelImg.py
MainWindow.scaleFitWindow
def scaleFitWindow(self): """Figure out the size of the pixmap in order to fit the main widget.""" e = 2.0 # So that no scrollbars are generated. w1 = self.centralWidget().width() - e h1 = self.centralWidget().height() - e a1 = w1 / h1 # Calculate a new scale value based...
python
def scaleFitWindow(self): """Figure out the size of the pixmap in order to fit the main widget.""" e = 2.0 # So that no scrollbars are generated. w1 = self.centralWidget().width() - e h1 = self.centralWidget().height() - e a1 = w1 / h1 # Calculate a new scale value based...
[ "def", "scaleFitWindow", "(", "self", ")", ":", "e", "=", "2.0", "# So that no scrollbars are generated.", "w1", "=", "self", ".", "centralWidget", "(", ")", ".", "width", "(", ")", "-", "e", "h1", "=", "self", ".", "centralWidget", "(", ")", ".", "heigh...
Figure out the size of the pixmap in order to fit the main widget.
[ "Figure", "out", "the", "size", "of", "the", "pixmap", "in", "order", "to", "fit", "the", "main", "widget", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/labelImg.py#L1069-L1079
train
tzutalin/labelImg
libs/ustr.py
ustr
def ustr(x): '''py2/py3 unicode helper''' if sys.version_info < (3, 0, 0): from PyQt4.QtCore import QString if type(x) == str: return x.decode(DEFAULT_ENCODING) if type(x) == QString: #https://blog.csdn.net/friendan/article/details/51088476 #https://b...
python
def ustr(x): '''py2/py3 unicode helper''' if sys.version_info < (3, 0, 0): from PyQt4.QtCore import QString if type(x) == str: return x.decode(DEFAULT_ENCODING) if type(x) == QString: #https://blog.csdn.net/friendan/article/details/51088476 #https://b...
[ "def", "ustr", "(", "x", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ",", "0", ")", ":", "from", "PyQt4", ".", "QtCore", "import", "QString", "if", "type", "(", "x", ")", "==", "str", ":", "return", "x", ".", "decode", ...
py2/py3 unicode helper
[ "py2", "/", "py3", "unicode", "helper" ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/ustr.py#L4-L17
train
tzutalin/labelImg
libs/pascal_voc_io.py
PascalVocWriter.prettify
def prettify(self, elem): """ Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, 'utf8') root = etree.fromstring(rough_string) return etree.tostring(root, pretty_print=True, encoding=ENCODE_METHOD).replace(" ".encode(), ...
python
def prettify(self, elem): """ Return a pretty-printed XML string for the Element. """ rough_string = ElementTree.tostring(elem, 'utf8') root = etree.fromstring(rough_string) return etree.tostring(root, pretty_print=True, encoding=ENCODE_METHOD).replace(" ".encode(), ...
[ "def", "prettify", "(", "self", ",", "elem", ")", ":", "rough_string", "=", "ElementTree", ".", "tostring", "(", "elem", ",", "'utf8'", ")", "root", "=", "etree", ".", "fromstring", "(", "rough_string", ")", "return", "etree", ".", "tostring", "(", "root...
Return a pretty-printed XML string for the Element.
[ "Return", "a", "pretty", "-", "printed", "XML", "string", "for", "the", "Element", "." ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/pascal_voc_io.py#L26-L35
train
tzutalin/labelImg
libs/pascal_voc_io.py
PascalVocWriter.genXML
def genXML(self): """ Return XML root """ # Check conditions if self.filename is None or \ self.foldername is None or \ self.imgSize is None: return None top = Element('annotation') if self.verified: top...
python
def genXML(self): """ Return XML root """ # Check conditions if self.filename is None or \ self.foldername is None or \ self.imgSize is None: return None top = Element('annotation') if self.verified: top...
[ "def", "genXML", "(", "self", ")", ":", "# Check conditions", "if", "self", ".", "filename", "is", "None", "or", "self", ".", "foldername", "is", "None", "or", "self", ".", "imgSize", "is", "None", ":", "return", "None", "top", "=", "Element", "(", "'a...
Return XML root
[ "Return", "XML", "root" ]
6afd15aa88f89f41254e0004ed219b3965eb2c0d
https://github.com/tzutalin/labelImg/blob/6afd15aa88f89f41254e0004ed219b3965eb2c0d/libs/pascal_voc_io.py#L37-L78
train
ccxt/ccxt
python/ccxt/async_support/base/exchange.py
Exchange.fetch
async def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) ...
python
async def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) ...
[ "async", "def", "fetch", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "request_headers", "=", "self", ".", "prepare_request_headers", "(", "headers", ")", "url", "=", "self", "."...
Perform a HTTP request and return decoded JSON data
[ "Perform", "a", "HTTP", "request", "and", "return", "decoded", "JSON", "data" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/async_support/base/exchange.py#L117-L168
train
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.fetch2
def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing""" if self.enableRateLimit: self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method,...
python
def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing""" if self.enableRateLimit: self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method,...
[ "def", "fetch2", "(", "self", ",", "path", ",", "api", "=", "'public'", ",", "method", "=", "'GET'", ",", "params", "=", "{", "}", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "if", "self", ".", "enableRateLimit", ":", "self", ...
A better wrapper over request for deferred signing
[ "A", "better", "wrapper", "over", "request", "for", "deferred", "signing" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L423-L429
train
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.request
def request(self, path, api='public', method='GET', params={}, headers=None, body=None): """Exchange.request is the entry point for all generated methods""" return self.fetch2(path, api, method, params, headers, body)
python
def request(self, path, api='public', method='GET', params={}, headers=None, body=None): """Exchange.request is the entry point for all generated methods""" return self.fetch2(path, api, method, params, headers, body)
[ "def", "request", "(", "self", ",", "path", ",", "api", "=", "'public'", ",", "method", "=", "'GET'", ",", "params", "=", "{", "}", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "return", "self", ".", "fetch2", "(", "path", ","...
Exchange.request is the entry point for all generated methods
[ "Exchange", ".", "request", "is", "the", "entry", "point", "for", "all", "generated", "methods" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L431-L433
train
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.find_broadly_matched_key
def find_broadly_matched_key(self, broad, string): """A helper method for matching error strings exactly vs broadly""" keys = list(broad.keys()) for i in range(0, len(keys)): key = keys[i] if string.find(key) >= 0: return key return None
python
def find_broadly_matched_key(self, broad, string): """A helper method for matching error strings exactly vs broadly""" keys = list(broad.keys()) for i in range(0, len(keys)): key = keys[i] if string.find(key) >= 0: return key return None
[ "def", "find_broadly_matched_key", "(", "self", ",", "broad", ",", "string", ")", ":", "keys", "=", "list", "(", "broad", ".", "keys", "(", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "keys", ")", ")", ":", "key", "=", "keys",...
A helper method for matching error strings exactly vs broadly
[ "A", "helper", "method", "for", "matching", "error", "strings", "exactly", "vs", "broadly" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L445-L452
train
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.fetch
def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, request_headers, body) ...
python
def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, request_headers, body) ...
[ "def", "fetch", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "body", "=", "None", ")", ":", "request_headers", "=", "self", ".", "prepare_request_headers", "(", "headers", ")", "url", "=", "self", ".", "proxy"...
Perform a HTTP request and return decoded JSON data
[ "Perform", "a", "HTTP", "request", "and", "return", "decoded", "JSON", "data" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L470-L536
train
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.safe_either
def safe_either(method, dictionary, key1, key2, default_value=None): """A helper-wrapper for the safe_value_2() family.""" value = method(dictionary, key1) return value if value is not None else method(dictionary, key2, default_value)
python
def safe_either(method, dictionary, key1, key2, default_value=None): """A helper-wrapper for the safe_value_2() family.""" value = method(dictionary, key1) return value if value is not None else method(dictionary, key2, default_value)
[ "def", "safe_either", "(", "method", ",", "dictionary", ",", "key1", ",", "key2", ",", "default_value", "=", "None", ")", ":", "value", "=", "method", "(", "dictionary", ",", "key1", ")", "return", "value", "if", "value", "is", "not", "None", "else", "...
A helper-wrapper for the safe_value_2() family.
[ "A", "helper", "-", "wrapper", "for", "the", "safe_value_2", "()", "family", "." ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L616-L619
train
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.truncate
def truncate(num, precision=0): """Deprecated, use decimal_to_precision instead""" if precision > 0: decimal_precision = math.pow(10, precision) return math.trunc(num * decimal_precision) / decimal_precision return int(Exchange.truncate_to_string(num, precision))
python
def truncate(num, precision=0): """Deprecated, use decimal_to_precision instead""" if precision > 0: decimal_precision = math.pow(10, precision) return math.trunc(num * decimal_precision) / decimal_precision return int(Exchange.truncate_to_string(num, precision))
[ "def", "truncate", "(", "num", ",", "precision", "=", "0", ")", ":", "if", "precision", ">", "0", ":", "decimal_precision", "=", "math", ".", "pow", "(", "10", ",", "precision", ")", "return", "math", ".", "trunc", "(", "num", "*", "decimal_precision",...
Deprecated, use decimal_to_precision instead
[ "Deprecated", "use", "decimal_to_precision", "instead" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L622-L627
train
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.truncate_to_string
def truncate_to_string(num, precision=0): """Deprecated, todo: remove references from subclasses""" if precision > 0: parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.') decimal_digits = parts[1][:precision].rstrip('0') decimal_digits = decimal_digits if ...
python
def truncate_to_string(num, precision=0): """Deprecated, todo: remove references from subclasses""" if precision > 0: parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.') decimal_digits = parts[1][:precision].rstrip('0') decimal_digits = decimal_digits if ...
[ "def", "truncate_to_string", "(", "num", ",", "precision", "=", "0", ")", ":", "if", "precision", ">", "0", ":", "parts", "=", "(", "'{0:.%df}'", "%", "precision", ")", ".", "format", "(", "Decimal", "(", "num", ")", ")", ".", "split", "(", "'.'", ...
Deprecated, todo: remove references from subclasses
[ "Deprecated", "todo", ":", "remove", "references", "from", "subclasses" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L630-L637
train
ccxt/ccxt
python/ccxt/base/exchange.py
Exchange.check_address
def check_address(self, address): """Checks an address is not the same character repeated or an empty sequence""" if address is None: self.raise_error(InvalidAddress, details='address is None') if all(letter == address[0] for letter in address) or len(address) < self.minFundingAddres...
python
def check_address(self, address): """Checks an address is not the same character repeated or an empty sequence""" if address is None: self.raise_error(InvalidAddress, details='address is None') if all(letter == address[0] for letter in address) or len(address) < self.minFundingAddres...
[ "def", "check_address", "(", "self", ",", "address", ")", ":", "if", "address", "is", "None", ":", "self", ".", "raise_error", "(", "InvalidAddress", ",", "details", "=", "'address is None'", ")", "if", "all", "(", "letter", "==", "address", "[", "0", "]...
Checks an address is not the same character repeated or an empty sequence
[ "Checks", "an", "address", "is", "not", "the", "same", "character", "repeated", "or", "an", "empty", "sequence" ]
23062efd7a5892c79b370c9d951c03cf8c0ddf23
https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L1000-L1006
train
mozilla/DeepSpeech
bin/benchmark_plotter.py
reduce_filename
def reduce_filename(f): r''' Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb Where XXX is a variation on the model size for example And where YYY is a const related to the training dataset ''' f = os.path.basename(f).split('.') return keep_only_digits(f[-3])
python
def reduce_filename(f): r''' Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb Where XXX is a variation on the model size for example And where YYY is a const related to the training dataset ''' f = os.path.basename(f).split('.') return keep_only_digits(f[-3])
[ "def", "reduce_filename", "(", "f", ")", ":", "f", "=", "os", ".", "path", ".", "basename", "(", "f", ")", ".", "split", "(", "'.'", ")", "return", "keep_only_digits", "(", "f", "[", "-", "3", "]", ")" ]
r''' Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb Where XXX is a variation on the model size for example And where YYY is a const related to the training dataset
[ "r", "Expects", "something", "like", "/", "tmp", "/", "tmpAjry4Gdsbench", "/", "test", ".", "weights", ".", "e5", ".", "XXX", ".", "YYY", ".", "pb", "Where", "XXX", "is", "a", "variation", "on", "the", "model", "size", "for", "example", "And", "where",...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_plotter.py#L30-L38
train
mozilla/DeepSpeech
util/benchmark.py
keep_only_digits
def keep_only_digits(s): r''' local helper to just keep digits ''' fs = '' for c in s: if c.isdigit(): fs += c return int(fs)
python
def keep_only_digits(s): r''' local helper to just keep digits ''' fs = '' for c in s: if c.isdigit(): fs += c return int(fs)
[ "def", "keep_only_digits", "(", "s", ")", ":", "fs", "=", "''", "for", "c", "in", "s", ":", "if", "c", ".", "isdigit", "(", ")", ":", "fs", "+=", "c", "return", "int", "(", "fs", ")" ]
r''' local helper to just keep digits
[ "r", "local", "helper", "to", "just", "keep", "digits" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/benchmark.py#L6-L15
train
mozilla/DeepSpeech
util/stm.py
parse_stm_file
def parse_stm_file(stm_file): r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. """ stm_segments = [] with codecs.open(stm_file, encoding="utf-8") as stm_lines: for stm_line in stm_lines: stmSegment = STMSegment(stm_line) if not "ignore_time_...
python
def parse_stm_file(stm_file): r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`. """ stm_segments = [] with codecs.open(stm_file, encoding="utf-8") as stm_lines: for stm_line in stm_lines: stmSegment = STMSegment(stm_line) if not "ignore_time_...
[ "def", "parse_stm_file", "(", "stm_file", ")", ":", "stm_segments", "=", "[", "]", "with", "codecs", ".", "open", "(", "stm_file", ",", "encoding", "=", "\"utf-8\"", ")", "as", "stm_lines", ":", "for", "stm_line", "in", "stm_lines", ":", "stmSegment", "=",...
r""" Parses an STM file at ``stm_file`` into a list of :class:`STMSegment`.
[ "r", "Parses", "an", "STM", "file", "at", "stm_file", "into", "a", "list", "of", ":", "class", ":", "STMSegment", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/stm.py#L54-L64
train
mozilla/DeepSpeech
examples/vad_transcriber/wavSplit.py
read_wave
def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width ...
python
def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width ...
[ "def", "read_wave", "(", "path", ")", ":", "with", "contextlib", ".", "closing", "(", "wave", ".", "open", "(", "path", ",", "'rb'", ")", ")", "as", "wf", ":", "num_channels", "=", "wf", ".", "getnchannels", "(", ")", "assert", "num_channels", "==", ...
Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate).
[ "Reads", "a", ".", "wav", "file", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L6-L21
train
mozilla/DeepSpeech
examples/vad_transcriber/wavSplit.py
write_wave
def write_wave(path, audio, sample_rate): """Writes a .wav file. Takes path, PCM audio data, and sample rate. """ with contextlib.closing(wave.open(path, 'wb')) as wf: wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(sample_rate) wf.writeframes(audio)
python
def write_wave(path, audio, sample_rate): """Writes a .wav file. Takes path, PCM audio data, and sample rate. """ with contextlib.closing(wave.open(path, 'wb')) as wf: wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(sample_rate) wf.writeframes(audio)
[ "def", "write_wave", "(", "path", ",", "audio", ",", "sample_rate", ")", ":", "with", "contextlib", ".", "closing", "(", "wave", ".", "open", "(", "path", ",", "'wb'", ")", ")", "as", "wf", ":", "wf", ".", "setnchannels", "(", "1", ")", "wf", ".", ...
Writes a .wav file. Takes path, PCM audio data, and sample rate.
[ "Writes", "a", ".", "wav", "file", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L24-L33
train
mozilla/DeepSpeech
examples/vad_transcriber/wavSplit.py
frame_generator
def frame_generator(frame_duration_ms, audio, sample_rate): """Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. """ n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) ...
python
def frame_generator(frame_duration_ms, audio, sample_rate): """Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. """ n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) ...
[ "def", "frame_generator", "(", "frame_duration_ms", ",", "audio", ",", "sample_rate", ")", ":", "n", "=", "int", "(", "sample_rate", "*", "(", "frame_duration_ms", "/", "1000.0", ")", "*", "2", ")", "offset", "=", "0", "timestamp", "=", "0.0", "duration", ...
Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration.
[ "Generates", "audio", "frames", "from", "PCM", "audio", "data", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/wavSplit.py#L44-L59
train
mozilla/DeepSpeech
examples/vad_transcriber/audioTranscript_gui.py
Worker.run
def run(self): ''' Initialise the runner function with the passed args, kwargs ''' # Retrieve args/kwargs here; and fire up the processing using them try: transcript = self.fn(*self.args, **self.kwargs) except: traceback.print_exc() ex...
python
def run(self): ''' Initialise the runner function with the passed args, kwargs ''' # Retrieve args/kwargs here; and fire up the processing using them try: transcript = self.fn(*self.args, **self.kwargs) except: traceback.print_exc() ex...
[ "def", "run", "(", "self", ")", ":", "# Retrieve args/kwargs here; and fire up the processing using them", "try", ":", "transcript", "=", "self", ".", "fn", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", "except", ":", "traceback", ...
Initialise the runner function with the passed args, kwargs
[ "Initialise", "the", "runner", "function", "with", "the", "passed", "args", "kwargs" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/vad_transcriber/audioTranscript_gui.py#L71-L88
train
mozilla/DeepSpeech
bin/benchmark_nc.py
exec_command
def exec_command(command, cwd=None): r''' Helper to exec locally (subprocess) or remotely (paramiko) ''' rc = None stdout = stderr = None if ssh_conn is None: ld_library_path = {'LD_LIBRARY_PATH': '.:%s' % os.environ.get('LD_LIBRARY_PATH', '')} p = subprocess.Popen(command, stdo...
python
def exec_command(command, cwd=None): r''' Helper to exec locally (subprocess) or remotely (paramiko) ''' rc = None stdout = stderr = None if ssh_conn is None: ld_library_path = {'LD_LIBRARY_PATH': '.:%s' % os.environ.get('LD_LIBRARY_PATH', '')} p = subprocess.Popen(command, stdo...
[ "def", "exec_command", "(", "command", ",", "cwd", "=", "None", ")", ":", "rc", "=", "None", "stdout", "=", "stderr", "=", "None", "if", "ssh_conn", "is", "None", ":", "ld_library_path", "=", "{", "'LD_LIBRARY_PATH'", ":", "'.:%s'", "%", "os", ".", "en...
r''' Helper to exec locally (subprocess) or remotely (paramiko)
[ "r", "Helper", "to", "exec", "locally", "(", "subprocess", ")", "or", "remotely", "(", "paramiko", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L41-L61
train
mozilla/DeepSpeech
bin/benchmark_nc.py
get_arch_string
def get_arch_string(): r''' Check local or remote system arch, to produce TaskCluster proper link. ''' rc, stdout, stderr = exec_command('uname -sm') if rc > 0: raise AssertionError('Error checking OS') stdout = stdout.lower().strip() if not 'linux' in stdout: raise Assertio...
python
def get_arch_string(): r''' Check local or remote system arch, to produce TaskCluster proper link. ''' rc, stdout, stderr = exec_command('uname -sm') if rc > 0: raise AssertionError('Error checking OS') stdout = stdout.lower().strip() if not 'linux' in stdout: raise Assertio...
[ "def", "get_arch_string", "(", ")", ":", "rc", ",", "stdout", ",", "stderr", "=", "exec_command", "(", "'uname -sm'", ")", "if", "rc", ">", "0", ":", "raise", "AssertionError", "(", "'Error checking OS'", ")", "stdout", "=", "stdout", ".", "lower", "(", ...
r''' Check local or remote system arch, to produce TaskCluster proper link.
[ "r", "Check", "local", "or", "remote", "system", "arch", "to", "produce", "TaskCluster", "proper", "link", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L68-L91
train
mozilla/DeepSpeech
bin/benchmark_nc.py
extract_native_client_tarball
def extract_native_client_tarball(dir): r''' Download a native_client.tar.xz file from TaskCluster and extract it to dir. ''' assert_valid_dir(dir) target_tarball = os.path.join(dir, 'native_client.tar.xz') if os.path.isfile(target_tarball) and os.stat(target_tarball).st_size == 0: retu...
python
def extract_native_client_tarball(dir): r''' Download a native_client.tar.xz file from TaskCluster and extract it to dir. ''' assert_valid_dir(dir) target_tarball = os.path.join(dir, 'native_client.tar.xz') if os.path.isfile(target_tarball) and os.stat(target_tarball).st_size == 0: retu...
[ "def", "extract_native_client_tarball", "(", "dir", ")", ":", "assert_valid_dir", "(", "dir", ")", "target_tarball", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "'native_client.tar.xz'", ")", "if", "os", ".", "path", ".", "isfile", "(", "target_tar...
r''' Download a native_client.tar.xz file from TaskCluster and extract it to dir.
[ "r", "Download", "a", "native_client", ".", "tar", ".", "xz", "file", "from", "TaskCluster", "and", "extract", "it", "to", "dir", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L97-L110
train
mozilla/DeepSpeech
bin/benchmark_nc.py
is_zip_file
def is_zip_file(models): r''' Ensure that a path is a zip file by: - checking length is 1 - checking extension is '.zip' ''' ext = os.path.splitext(models[0])[1] return (len(models) == 1) and (ext == '.zip')
python
def is_zip_file(models): r''' Ensure that a path is a zip file by: - checking length is 1 - checking extension is '.zip' ''' ext = os.path.splitext(models[0])[1] return (len(models) == 1) and (ext == '.zip')
[ "def", "is_zip_file", "(", "models", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "models", "[", "0", "]", ")", "[", "1", "]", "return", "(", "len", "(", "models", ")", "==", "1", ")", "and", "(", "ext", "==", "'.zip'", ")" ]
r''' Ensure that a path is a zip file by: - checking length is 1 - checking extension is '.zip'
[ "r", "Ensure", "that", "a", "path", "is", "a", "zip", "file", "by", ":", "-", "checking", "length", "is", "1", "-", "checking", "extension", "is", ".", "zip" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L112-L119
train
mozilla/DeepSpeech
bin/benchmark_nc.py
maybe_inspect_zip
def maybe_inspect_zip(models): r''' Detect if models is a list of protocolbuffer files or a ZIP file. If the latter, then unzip it and return the list of protocolbuffer files that were inside. ''' if not(is_zip_file(models)): return models if len(models) > 1: return models ...
python
def maybe_inspect_zip(models): r''' Detect if models is a list of protocolbuffer files or a ZIP file. If the latter, then unzip it and return the list of protocolbuffer files that were inside. ''' if not(is_zip_file(models)): return models if len(models) > 1: return models ...
[ "def", "maybe_inspect_zip", "(", "models", ")", ":", "if", "not", "(", "is_zip_file", "(", "models", ")", ")", ":", "return", "models", "if", "len", "(", "models", ")", ">", "1", ":", "return", "models", "if", "len", "(", "models", ")", "<", "1", "...
r''' Detect if models is a list of protocolbuffer files or a ZIP file. If the latter, then unzip it and return the list of protocolbuffer files that were inside.
[ "r", "Detect", "if", "models", "is", "a", "list", "of", "protocolbuffer", "files", "or", "a", "ZIP", "file", ".", "If", "the", "latter", "then", "unzip", "it", "and", "return", "the", "list", "of", "protocolbuffer", "files", "that", "were", "inside", "."...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L121-L137
train
mozilla/DeepSpeech
bin/benchmark_nc.py
all_files
def all_files(models=[]): r''' Return a list of full path of files matching 'models', sorted in human numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000). Files are supposed to be named identically except one variable component e.g. the list, test.weights.e5.lstm1200.ldc93s1.pb ...
python
def all_files(models=[]): r''' Return a list of full path of files matching 'models', sorted in human numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000). Files are supposed to be named identically except one variable component e.g. the list, test.weights.e5.lstm1200.ldc93s1.pb ...
[ "def", "all_files", "(", "models", "=", "[", "]", ")", ":", "def", "nsort", "(", "a", ",", "b", ")", ":", "fa", "=", "os", ".", "path", ".", "basename", "(", "a", ")", ".", "split", "(", "'.'", ")", "fb", "=", "os", ".", "path", ".", "basen...
r''' Return a list of full path of files matching 'models', sorted in human numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000). Files are supposed to be named identically except one variable component e.g. the list, test.weights.e5.lstm1200.ldc93s1.pb test.weights.e5.lstm1000....
[ "r", "Return", "a", "list", "of", "full", "path", "of", "files", "matching", "models", "sorted", "in", "human", "numerical", "order", "(", "i", ".", "e", ".", "0", "1", "2", "...", "10", "11", "12", "...", "100", "...", "1000", ")", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L139-L186
train
mozilla/DeepSpeech
bin/benchmark_nc.py
setup_tempdir
def setup_tempdir(dir, models, wav, alphabet, lm_binary, trie, binaries): r''' Copy models, libs and binary to a directory (new one if dir is None) ''' if dir is None: dir = tempfile.mkdtemp(suffix='dsbench') sorted_models = all_files(models=models) if binaries is None: maybe_do...
python
def setup_tempdir(dir, models, wav, alphabet, lm_binary, trie, binaries): r''' Copy models, libs and binary to a directory (new one if dir is None) ''' if dir is None: dir = tempfile.mkdtemp(suffix='dsbench') sorted_models = all_files(models=models) if binaries is None: maybe_do...
[ "def", "setup_tempdir", "(", "dir", ",", "models", ",", "wav", ",", "alphabet", ",", "lm_binary", ",", "trie", ",", "binaries", ")", ":", "if", "dir", "is", "None", ":", "dir", "=", "tempfile", ".", "mkdtemp", "(", "suffix", "=", "'dsbench'", ")", "s...
r''' Copy models, libs and binary to a directory (new one if dir is None)
[ "r", "Copy", "models", "libs", "and", "binary", "to", "a", "directory", "(", "new", "one", "if", "dir", "is", "None", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L241-L278
train
mozilla/DeepSpeech
bin/benchmark_nc.py
teardown_tempdir
def teardown_tempdir(dir): r''' Cleanup temporary directory. ''' if ssh_conn: delete_tree(dir) assert_valid_dir(dir) shutil.rmtree(dir)
python
def teardown_tempdir(dir): r''' Cleanup temporary directory. ''' if ssh_conn: delete_tree(dir) assert_valid_dir(dir) shutil.rmtree(dir)
[ "def", "teardown_tempdir", "(", "dir", ")", ":", "if", "ssh_conn", ":", "delete_tree", "(", "dir", ")", "assert_valid_dir", "(", "dir", ")", "shutil", ".", "rmtree", "(", "dir", ")" ]
r''' Cleanup temporary directory.
[ "r", "Cleanup", "temporary", "directory", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L280-L289
train
mozilla/DeepSpeech
bin/benchmark_nc.py
get_sshconfig
def get_sshconfig(): r''' Read user's SSH configuration file ''' with open(os.path.expanduser('~/.ssh/config')) as f: cfg = paramiko.SSHConfig() cfg.parse(f) ret_dict = {} for d in cfg._config: _copy = dict(d) # Avoid buggy behavior with strange h...
python
def get_sshconfig(): r''' Read user's SSH configuration file ''' with open(os.path.expanduser('~/.ssh/config')) as f: cfg = paramiko.SSHConfig() cfg.parse(f) ret_dict = {} for d in cfg._config: _copy = dict(d) # Avoid buggy behavior with strange h...
[ "def", "get_sshconfig", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "'~/.ssh/config'", ")", ")", "as", "f", ":", "cfg", "=", "paramiko", ".", "SSHConfig", "(", ")", "cfg", ".", "parse", "(", "f", ")", "ret_dict", ...
r''' Read user's SSH configuration file
[ "r", "Read", "user", "s", "SSH", "configuration", "file" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L291-L308
train
mozilla/DeepSpeech
bin/benchmark_nc.py
establish_ssh
def establish_ssh(target=None, auto_trust=False, allow_agent=True, look_keys=True): r''' Establish a SSH connection to a remote host. It should be able to use SSH's config file Host name declarations. By default, will not automatically add trust for hosts, will use SSH agent and will try to load keys. ...
python
def establish_ssh(target=None, auto_trust=False, allow_agent=True, look_keys=True): r''' Establish a SSH connection to a remote host. It should be able to use SSH's config file Host name declarations. By default, will not automatically add trust for hosts, will use SSH agent and will try to load keys. ...
[ "def", "establish_ssh", "(", "target", "=", "None", ",", "auto_trust", "=", "False", ",", "allow_agent", "=", "True", ",", "look_keys", "=", "True", ")", ":", "def", "password_prompt", "(", "username", ",", "hostname", ")", ":", "r'''\n If the Host is r...
r''' Establish a SSH connection to a remote host. It should be able to use SSH's config file Host name declarations. By default, will not automatically add trust for hosts, will use SSH agent and will try to load keys.
[ "r", "Establish", "a", "SSH", "connection", "to", "a", "remote", "host", ".", "It", "should", "be", "able", "to", "use", "SSH", "s", "config", "file", "Host", "name", "declarations", ".", "By", "default", "will", "not", "automatically", "add", "trust", "...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L310-L375
train
mozilla/DeepSpeech
bin/benchmark_nc.py
run_benchmarks
def run_benchmarks(dir, models, wav, alphabet, lm_binary=None, trie=None, iters=-1): r''' Core of the running of the benchmarks. We will run on all of models, against the WAV file provided as wav, and the provided alphabet. ''' assert_valid_dir(dir) inference_times = [ ] for model in mode...
python
def run_benchmarks(dir, models, wav, alphabet, lm_binary=None, trie=None, iters=-1): r''' Core of the running of the benchmarks. We will run on all of models, against the WAV file provided as wav, and the provided alphabet. ''' assert_valid_dir(dir) inference_times = [ ] for model in mode...
[ "def", "run_benchmarks", "(", "dir", ",", "models", ",", "wav", ",", "alphabet", ",", "lm_binary", "=", "None", ",", "trie", "=", "None", ",", "iters", "=", "-", "1", ")", ":", "assert_valid_dir", "(", "dir", ")", "inference_times", "=", "[", "]", "f...
r''' Core of the running of the benchmarks. We will run on all of models, against the WAV file provided as wav, and the provided alphabet.
[ "r", "Core", "of", "the", "running", "of", "the", "benchmarks", ".", "We", "will", "run", "on", "all", "of", "models", "against", "the", "WAV", "file", "provided", "as", "wav", "and", "the", "provided", "alphabet", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L377-L422
train
mozilla/DeepSpeech
bin/benchmark_nc.py
produce_csv
def produce_csv(input, output): r''' Take an input dictionnary and write it to the object-file output. ''' output.write('"model","mean","std"\n') for model_data in input: output.write('"%s",%f,%f\n' % (model_data['name'], model_data['mean'], model_data['stddev'])) output.flush() outp...
python
def produce_csv(input, output): r''' Take an input dictionnary and write it to the object-file output. ''' output.write('"model","mean","std"\n') for model_data in input: output.write('"%s",%f,%f\n' % (model_data['name'], model_data['mean'], model_data['stddev'])) output.flush() outp...
[ "def", "produce_csv", "(", "input", ",", "output", ")", ":", "output", ".", "write", "(", "'\"model\",\"mean\",\"std\"\\n'", ")", "for", "model_data", "in", "input", ":", "output", ".", "write", "(", "'\"%s\",%f,%f\\n'", "%", "(", "model_data", "[", "'name'", ...
r''' Take an input dictionnary and write it to the object-file output.
[ "r", "Take", "an", "input", "dictionnary", "and", "write", "it", "to", "the", "object", "-", "file", "output", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L424-L433
train
mozilla/DeepSpeech
util/feeding.py
to_sparse_tuple
def to_sparse_tuple(sequence): r"""Creates a sparse representention of ``sequence``. Returns a tuple with (indices, values, shape) """ indices = np.asarray(list(zip([0]*len(sequence), range(len(sequence)))), dtype=np.int64) shape = np.asarray([1, len(sequence)], dtype=np.int64) return indice...
python
def to_sparse_tuple(sequence): r"""Creates a sparse representention of ``sequence``. Returns a tuple with (indices, values, shape) """ indices = np.asarray(list(zip([0]*len(sequence), range(len(sequence)))), dtype=np.int64) shape = np.asarray([1, len(sequence)], dtype=np.int64) return indice...
[ "def", "to_sparse_tuple", "(", "sequence", ")", ":", "indices", "=", "np", ".", "asarray", "(", "list", "(", "zip", "(", "[", "0", "]", "*", "len", "(", "sequence", ")", ",", "range", "(", "len", "(", "sequence", ")", ")", ")", ")", ",", "dtype",...
r"""Creates a sparse representention of ``sequence``. Returns a tuple with (indices, values, shape)
[ "r", "Creates", "a", "sparse", "representention", "of", "sequence", ".", "Returns", "a", "tuple", "with", "(", "indices", "values", "shape", ")" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/feeding.py#L57-L63
train
mozilla/DeepSpeech
bin/import_voxforge.py
_parallel_downloader
def _parallel_downloader(voxforge_url, archive_dir, total, counter): """Generate a function to download a file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param voxforge_url: the base voxforge URL :param archive_d...
python
def _parallel_downloader(voxforge_url, archive_dir, total, counter): """Generate a function to download a file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param voxforge_url: the base voxforge URL :param archive_d...
[ "def", "_parallel_downloader", "(", "voxforge_url", ",", "archive_dir", ",", "total", ",", "counter", ")", ":", "def", "download", "(", "d", ")", ":", "\"\"\"Binds voxforge_url, archive_dir, total, and counter into this scope\n Downloads the given file\n :param d: a...
Generate a function to download a file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param voxforge_url: the base voxforge URL :param archive_dir: the location to store the downloaded file :param total: the ...
[ "Generate", "a", "function", "to", "download", "a", "file", "based", "on", "given", "parameters", "This", "works", "by", "currying", "the", "above", "given", "arguments", "into", "a", "closure", "in", "the", "form", "of", "the", "following", "function", "." ...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_voxforge.py#L50-L72
train
mozilla/DeepSpeech
bin/import_voxforge.py
_parallel_extracter
def _parallel_extracter(data_dir, number_of_test, number_of_dev, total, counter): """Generate a function to extract a tar file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param data_dir: the target directory to ...
python
def _parallel_extracter(data_dir, number_of_test, number_of_dev, total, counter): """Generate a function to extract a tar file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param data_dir: the target directory to ...
[ "def", "_parallel_extracter", "(", "data_dir", ",", "number_of_test", ",", "number_of_dev", ",", "total", ",", "counter", ")", ":", "def", "extract", "(", "d", ")", ":", "\"\"\"Binds data_dir, number_of_test, number_of_dev, total, and counter into this scope\n Extracts...
Generate a function to extract a tar file based on given parameters This works by currying the above given arguments into a closure in the form of the following function. :param data_dir: the target directory to extract into :param number_of_test: the number of files to keep as the test set :...
[ "Generate", "a", "function", "to", "extract", "a", "tar", "file", "based", "on", "given", "parameters", "This", "works", "by", "currying", "the", "above", "given", "arguments", "into", "a", "closure", "in", "the", "form", "of", "the", "following", "function"...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_voxforge.py#L74-L105
train
mozilla/DeepSpeech
bin/import_voxforge.py
AtomicCounter.increment
def increment(self, amount=1): """Increments the counter by the given amount :param amount: the amount to increment by (default 1) :return: the incremented value of the counter """ self.__lock.acquire() self.__count += amount v = self.value() self.__...
python
def increment(self, amount=1): """Increments the counter by the given amount :param amount: the amount to increment by (default 1) :return: the incremented value of the counter """ self.__lock.acquire() self.__count += amount v = self.value() self.__...
[ "def", "increment", "(", "self", ",", "amount", "=", "1", ")", ":", "self", ".", "__lock", ".", "acquire", "(", ")", "self", ".", "__count", "+=", "amount", "v", "=", "self", ".", "value", "(", ")", "self", ".", "__lock", ".", "release", "(", ")"...
Increments the counter by the given amount :param amount: the amount to increment by (default 1) :return: the incremented value of the counter
[ "Increments", "the", "counter", "by", "the", "given", "amount", ":", "param", "amount", ":", "the", "amount", "to", "increment", "by", "(", "default", "1", ")", ":", "return", ":", "the", "incremented", "value", "of", "the", "counter" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_voxforge.py#L35-L44
train
mozilla/DeepSpeech
util/evaluate_tools.py
calculate_report
def calculate_report(labels, decodings, distances, losses): r''' This routine will calculate a WER report. It'll compute the `mean` WER and create ``Sample`` objects of the ``report_count`` top lowest loss items from the provided WER results tuple (only items with WER!=0 and ordered by their WER). '...
python
def calculate_report(labels, decodings, distances, losses): r''' This routine will calculate a WER report. It'll compute the `mean` WER and create ``Sample`` objects of the ``report_count`` top lowest loss items from the provided WER results tuple (only items with WER!=0 and ordered by their WER). '...
[ "def", "calculate_report", "(", "labels", ",", "decodings", ",", "distances", ",", "losses", ")", ":", "samples", "=", "pmap", "(", "process_decode_result", ",", "zip", "(", "labels", ",", "decodings", ",", "distances", ",", "losses", ")", ")", "# Getting th...
r''' This routine will calculate a WER report. It'll compute the `mean` WER and create ``Sample`` objects of the ``report_count`` top lowest loss items from the provided WER results tuple (only items with WER!=0 and ordered by their WER).
[ "r", "This", "routine", "will", "calculate", "a", "WER", "report", ".", "It", "ll", "compute", "the", "mean", "WER", "and", "create", "Sample", "objects", "of", "the", "report_count", "top", "lowest", "loss", "items", "from", "the", "provided", "WER", "res...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/evaluate_tools.py#L30-L47
train
mozilla/DeepSpeech
evaluate.py
sparse_tensor_value_to_texts
def sparse_tensor_value_to_texts(value, alphabet): r""" Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values, converting tokens to strings using ``alphabet``. """ return sparse_tuple_to_texts((value.indices, value.values, value.dense_shape), alphabet)
python
def sparse_tensor_value_to_texts(value, alphabet): r""" Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values, converting tokens to strings using ``alphabet``. """ return sparse_tuple_to_texts((value.indices, value.values, value.dense_shape), alphabet)
[ "def", "sparse_tensor_value_to_texts", "(", "value", ",", "alphabet", ")", ":", "return", "sparse_tuple_to_texts", "(", "(", "value", ".", "indices", ",", "value", ".", "values", ",", "value", ".", "dense_shape", ")", ",", "alphabet", ")" ]
r""" Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values, converting tokens to strings using ``alphabet``.
[ "r", "Given", "a", ":", "class", ":", "tf", ".", "SparseTensor", "value", "return", "an", "array", "of", "Python", "strings", "representing", "its", "values", "converting", "tokens", "to", "strings", "using", "alphabet", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/evaluate.py#L25-L30
train
mozilla/DeepSpeech
bin/import_gram_vaani.py
parse_args
def parse_args(args): """Parse command line parameters Args: args ([str]): Command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="Imports GramVaani data for Deep Speech" ...
python
def parse_args(args): """Parse command line parameters Args: args ([str]): Command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="Imports GramVaani data for Deep Speech" ...
[ "def", "parse_args", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Imports GramVaani data for Deep Speech\"", ")", "parser", ".", "add_argument", "(", "\"--version\"", ",", "action", "=", "\"version\"", ",", "...
Parse command line parameters Args: args ([str]): Command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace
[ "Parse", "command", "line", "parameters", "Args", ":", "args", "(", "[", "str", "]", ")", ":", "Command", "line", "parameters", "as", "list", "of", "strings", "Returns", ":", ":", "obj", ":", "argparse", ".", "Namespace", ":", "command", "line", "paramet...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L32-L79
train
mozilla/DeepSpeech
bin/import_gram_vaani.py
setup_logging
def setup_logging(level): """Setup basic logging Args: level (int): minimum log level for emitting messages """ format = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" logging.basicConfig( level=level, stream=sys.stdout, format=format, datefmt="%Y-%m-%d %H:%M:%S" )
python
def setup_logging(level): """Setup basic logging Args: level (int): minimum log level for emitting messages """ format = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" logging.basicConfig( level=level, stream=sys.stdout, format=format, datefmt="%Y-%m-%d %H:%M:%S" )
[ "def", "setup_logging", "(", "level", ")", ":", "format", "=", "\"[%(asctime)s] %(levelname)s:%(name)s:%(message)s\"", "logging", ".", "basicConfig", "(", "level", "=", "level", ",", "stream", "=", "sys", ".", "stdout", ",", "format", "=", "format", ",", "datefm...
Setup basic logging Args: level (int): minimum log level for emitting messages
[ "Setup", "basic", "logging", "Args", ":", "level", "(", "int", ")", ":", "minimum", "log", "level", "for", "emitting", "messages" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L81-L89
train
mozilla/DeepSpeech
bin/import_gram_vaani.py
main
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.info("Starting GramVaani importer...") _logger.info("Starting loading GramVaani csv...") csv = GramVaaniCSV(a...
python
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.info("Starting GramVaani importer...") _logger.info("Starting loading GramVaani csv...") csv = GramVaaniCSV(a...
[ "def", "main", "(", "args", ")", ":", "args", "=", "parse_args", "(", "args", ")", "setup_logging", "(", "args", ".", "loglevel", ")", "_logger", ".", "info", "(", "\"Starting GramVaani importer...\"", ")", "_logger", ".", "info", "(", "\"Starting loading Gram...
Main entry point allowing external calls Args: args ([str]): command line parameter list
[ "Main", "entry", "point", "allowing", "external", "calls", "Args", ":", "args", "(", "[", "str", "]", ")", ":", "command", "line", "parameter", "list" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L281-L300
train
mozilla/DeepSpeech
bin/import_gram_vaani.py
GramVaaniDownloader.download
def download(self): """Downloads the data associated with this instance Return: mp3_directory (os.path): The directory into which the associated mp3's were downloaded """ mp3_directory = self._pre_download() self.data.swifter.apply(func=lambda arg: self._download(*arg, ...
python
def download(self): """Downloads the data associated with this instance Return: mp3_directory (os.path): The directory into which the associated mp3's were downloaded """ mp3_directory = self._pre_download() self.data.swifter.apply(func=lambda arg: self._download(*arg, ...
[ "def", "download", "(", "self", ")", ":", "mp3_directory", "=", "self", ".", "_pre_download", "(", ")", "self", ".", "data", ".", "swifter", ".", "apply", "(", "func", "=", "lambda", "arg", ":", "self", ".", "_download", "(", "*", "arg", ",", "mp3_di...
Downloads the data associated with this instance Return: mp3_directory (os.path): The directory into which the associated mp3's were downloaded
[ "Downloads", "the", "data", "associated", "with", "this", "instance", "Return", ":", "mp3_directory", "(", "os", ".", "path", ")", ":", "The", "directory", "into", "which", "the", "associated", "mp3", "s", "were", "downloaded" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L131-L138
train
mozilla/DeepSpeech
bin/import_gram_vaani.py
GramVaaniConverter.convert
def convert(self): """Converts the mp3's associated with this instance to wav's Return: wav_directory (os.path): The directory into which the associated wav's were downloaded """ wav_directory = self._pre_convert() for mp3_filename in self.mp3_directory.glob('**/*.mp3')...
python
def convert(self): """Converts the mp3's associated with this instance to wav's Return: wav_directory (os.path): The directory into which the associated wav's were downloaded """ wav_directory = self._pre_convert() for mp3_filename in self.mp3_directory.glob('**/*.mp3')...
[ "def", "convert", "(", "self", ")", ":", "wav_directory", "=", "self", ".", "_pre_convert", "(", ")", "for", "mp3_filename", "in", "self", ".", "mp3_directory", ".", "glob", "(", "'**/*.mp3'", ")", ":", "wav_filename", "=", "path", ".", "join", "(", "wav...
Converts the mp3's associated with this instance to wav's Return: wav_directory (os.path): The directory into which the associated wav's were downloaded
[ "Converts", "the", "mp3", "s", "associated", "with", "this", "instance", "to", "wav", "s", "Return", ":", "wav_directory", "(", "os", ".", "path", ")", ":", "The", "directory", "into", "which", "the", "associated", "wav", "s", "were", "downloaded" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/import_gram_vaani.py#L174-L189
train
mozilla/DeepSpeech
util/text.py
text_to_char_array
def text_to_char_array(original, alphabet): r""" Given a Python string ``original``, remove unsupported characters, map characters to integers and return a numpy array representing the processed string. """ return np.asarray([alphabet.label_from_string(c) for c in original])
python
def text_to_char_array(original, alphabet): r""" Given a Python string ``original``, remove unsupported characters, map characters to integers and return a numpy array representing the processed string. """ return np.asarray([alphabet.label_from_string(c) for c in original])
[ "def", "text_to_char_array", "(", "original", ",", "alphabet", ")", ":", "return", "np", ".", "asarray", "(", "[", "alphabet", ".", "label_from_string", "(", "c", ")", "for", "c", "in", "original", "]", ")" ]
r""" Given a Python string ``original``, remove unsupported characters, map characters to integers and return a numpy array representing the processed string.
[ "r", "Given", "a", "Python", "string", "original", "remove", "unsupported", "characters", "map", "characters", "to", "integers", "and", "return", "a", "numpy", "array", "representing", "the", "processed", "string", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/text.py#L50-L55
train
mozilla/DeepSpeech
util/text.py
wer_cer_batch
def wer_cer_batch(originals, results): r""" The WER is defined as the editing/Levenshtein distance on word level divided by the amount of words in the original text. In case of the original having more words (N) than the result and both being totally different (all N words resulting in 1 edit operat...
python
def wer_cer_batch(originals, results): r""" The WER is defined as the editing/Levenshtein distance on word level divided by the amount of words in the original text. In case of the original having more words (N) than the result and both being totally different (all N words resulting in 1 edit operat...
[ "def", "wer_cer_batch", "(", "originals", ",", "results", ")", ":", "# The WER is calculated on word (and NOT on character) level.", "# Therefore we split the strings into words first", "assert", "len", "(", "originals", ")", "==", "len", "(", "results", ")", "total_cer", "...
r""" The WER is defined as the editing/Levenshtein distance on word level divided by the amount of words in the original text. In case of the original having more words (N) than the result and both being totally different (all N words resulting in 1 edit operation each), the WER will always be 1 (N ...
[ "r", "The", "WER", "is", "defined", "as", "the", "editing", "/", "Levenshtein", "distance", "on", "word", "level", "divided", "by", "the", "amount", "of", "words", "in", "the", "original", "text", ".", "In", "case", "of", "the", "original", "having", "mo...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/util/text.py#L58-L83
train
mozilla/DeepSpeech
DeepSpeech.py
variable_on_cpu
def variable_on_cpu(name, shape, initializer): r""" Next we concern ourselves with graph creation. However, before we do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory. """ # Use the /cpu:0 device for scoped operations with tf.device(Con...
python
def variable_on_cpu(name, shape, initializer): r""" Next we concern ourselves with graph creation. However, before we do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory. """ # Use the /cpu:0 device for scoped operations with tf.device(Con...
[ "def", "variable_on_cpu", "(", "name", ",", "shape", ",", "initializer", ")", ":", "# Use the /cpu:0 device for scoped operations", "with", "tf", ".", "device", "(", "Config", ".", "cpu_device", ")", ":", "# Create or get apropos variable", "var", "=", "tf", ".", ...
r""" Next we concern ourselves with graph creation. However, before we do so we must introduce a utility function ``variable_on_cpu()`` used to create a variable in CPU memory.
[ "r", "Next", "we", "concern", "ourselves", "with", "graph", "creation", ".", "However", "before", "we", "do", "so", "we", "must", "introduce", "a", "utility", "function", "variable_on_cpu", "()", "used", "to", "create", "a", "variable", "in", "CPU", "memory"...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L31-L41
train
mozilla/DeepSpeech
DeepSpeech.py
calculate_mean_edit_distance_and_loss
def calculate_mean_edit_distance_and_loss(iterator, dropout, reuse): r''' This routine beam search decodes a mini-batch and calculates the loss and mean edit distance. Next to total and average loss it returns the mean edit distance, the decoded result and the batch's original Y. ''' # Obtain th...
python
def calculate_mean_edit_distance_and_loss(iterator, dropout, reuse): r''' This routine beam search decodes a mini-batch and calculates the loss and mean edit distance. Next to total and average loss it returns the mean edit distance, the decoded result and the batch's original Y. ''' # Obtain th...
[ "def", "calculate_mean_edit_distance_and_loss", "(", "iterator", ",", "dropout", ",", "reuse", ")", ":", "# Obtain the next batch of data", "(", "batch_x", ",", "batch_seq_len", ")", ",", "batch_y", "=", "iterator", ".", "get_next", "(", ")", "# Calculate the logits o...
r''' This routine beam search decodes a mini-batch and calculates the loss and mean edit distance. Next to total and average loss it returns the mean edit distance, the decoded result and the batch's original Y.
[ "r", "This", "routine", "beam", "search", "decodes", "a", "mini", "-", "batch", "and", "calculates", "the", "loss", "and", "mean", "edit", "distance", ".", "Next", "to", "total", "and", "average", "loss", "it", "returns", "the", "mean", "edit", "distance",...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L176-L195
train
mozilla/DeepSpeech
DeepSpeech.py
get_tower_results
def get_tower_results(iterator, optimizer, dropout_rates): r''' With this preliminary step out of the way, we can for each GPU introduce a tower for which's batch we calculate and return the optimization gradients and the average loss across towers. ''' # To calculate the mean of the losses ...
python
def get_tower_results(iterator, optimizer, dropout_rates): r''' With this preliminary step out of the way, we can for each GPU introduce a tower for which's batch we calculate and return the optimization gradients and the average loss across towers. ''' # To calculate the mean of the losses ...
[ "def", "get_tower_results", "(", "iterator", ",", "optimizer", ",", "dropout_rates", ")", ":", "# To calculate the mean of the losses", "tower_avg_losses", "=", "[", "]", "# Tower gradients to return", "tower_gradients", "=", "[", "]", "with", "tf", ".", "variable_scope...
r''' With this preliminary step out of the way, we can for each GPU introduce a tower for which's batch we calculate and return the optimization gradients and the average loss across towers.
[ "r", "With", "this", "preliminary", "step", "out", "of", "the", "way", "we", "can", "for", "each", "GPU", "introduce", "a", "tower", "for", "which", "s", "batch", "we", "calculate", "and", "return", "the", "optimization", "gradients", "and", "the", "averag...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L231-L273
train
mozilla/DeepSpeech
DeepSpeech.py
average_gradients
def average_gradients(tower_gradients): r''' A routine for computing each variable's average of the gradients obtained from the GPUs. Note also that this code acts as a synchronization point as it requires all GPUs to be finished with their mini-batch before it can run to completion. ''' # List ...
python
def average_gradients(tower_gradients): r''' A routine for computing each variable's average of the gradients obtained from the GPUs. Note also that this code acts as a synchronization point as it requires all GPUs to be finished with their mini-batch before it can run to completion. ''' # List ...
[ "def", "average_gradients", "(", "tower_gradients", ")", ":", "# List of average gradients to return to the caller", "average_grads", "=", "[", "]", "# Run this on cpu_device to conserve GPU memory", "with", "tf", ".", "device", "(", "Config", ".", "cpu_device", ")", ":", ...
r''' A routine for computing each variable's average of the gradients obtained from the GPUs. Note also that this code acts as a synchronization point as it requires all GPUs to be finished with their mini-batch before it can run to completion.
[ "r", "A", "routine", "for", "computing", "each", "variable", "s", "average", "of", "the", "gradients", "obtained", "from", "the", "GPUs", ".", "Note", "also", "that", "this", "code", "acts", "as", "a", "synchronization", "point", "as", "it", "requires", "a...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L276-L310
train
mozilla/DeepSpeech
DeepSpeech.py
log_variable
def log_variable(variable, gradient=None): r''' We introduce a function for logging a tensor variable's current state. It logs scalar values for the mean, standard deviation, minimum and maximum. Furthermore it logs a histogram of its state and (if given) of an optimization gradient. ''' name = ...
python
def log_variable(variable, gradient=None): r''' We introduce a function for logging a tensor variable's current state. It logs scalar values for the mean, standard deviation, minimum and maximum. Furthermore it logs a histogram of its state and (if given) of an optimization gradient. ''' name = ...
[ "def", "log_variable", "(", "variable", ",", "gradient", "=", "None", ")", ":", "name", "=", "variable", ".", "name", ".", "replace", "(", "':'", ",", "'_'", ")", "mean", "=", "tf", ".", "reduce_mean", "(", "variable", ")", "tf", ".", "summary", ".",...
r''' We introduce a function for logging a tensor variable's current state. It logs scalar values for the mean, standard deviation, minimum and maximum. Furthermore it logs a histogram of its state and (if given) of an optimization gradient.
[ "r", "We", "introduce", "a", "function", "for", "logging", "a", "tensor", "variable", "s", "current", "state", ".", "It", "logs", "scalar", "values", "for", "the", "mean", "standard", "deviation", "minimum", "and", "maximum", ".", "Furthermore", "it", "logs"...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L317-L336
train
mozilla/DeepSpeech
DeepSpeech.py
export
def export(): r''' Restores the trained variables into a simpler graph that will be exported for serving. ''' log_info('Exporting the model...') from tensorflow.python.framework.ops import Tensor, Operation inputs, outputs, _ = create_inference_graph(batch_size=FLAGS.export_batch_size, n_steps=...
python
def export(): r''' Restores the trained variables into a simpler graph that will be exported for serving. ''' log_info('Exporting the model...') from tensorflow.python.framework.ops import Tensor, Operation inputs, outputs, _ = create_inference_graph(batch_size=FLAGS.export_batch_size, n_steps=...
[ "def", "export", "(", ")", ":", "log_info", "(", "'Exporting the model...'", ")", "from", "tensorflow", ".", "python", ".", "framework", ".", "ops", "import", "Tensor", ",", "Operation", "inputs", ",", "outputs", ",", "_", "=", "create_inference_graph", "(", ...
r''' Restores the trained variables into a simpler graph that will be exported for serving.
[ "r", "Restores", "the", "trained", "variables", "into", "a", "simpler", "graph", "that", "will", "be", "exported", "for", "serving", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/DeepSpeech.py#L673-L759
train
mozilla/DeepSpeech
native_client/ctcdecode/__init__.py
ctc_beam_search_decoder
def ctc_beam_search_decoder(probs_seq, alphabet, beam_size, cutoff_prob=1.0, cutoff_top_n=40, scorer=None): """Wrapper for the CTC Beam Search Decoder. :param probs_seq: 2...
python
def ctc_beam_search_decoder(probs_seq, alphabet, beam_size, cutoff_prob=1.0, cutoff_top_n=40, scorer=None): """Wrapper for the CTC Beam Search Decoder. :param probs_seq: 2...
[ "def", "ctc_beam_search_decoder", "(", "probs_seq", ",", "alphabet", ",", "beam_size", ",", "cutoff_prob", "=", "1.0", ",", "cutoff_top_n", "=", "40", ",", "scorer", "=", "None", ")", ":", "beam_results", "=", "swigwrapper", ".", "ctc_beam_search_decoder", "(", ...
Wrapper for the CTC Beam Search Decoder. :param probs_seq: 2-D list of probability distributions over each time step, with each element being a list of normalized probabilities over alphabet and blank. :type probs_seq: 2-D list :param alphabet: alphabet list. ...
[ "Wrapper", "for", "the", "CTC", "Beam", "Search", "Decoder", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/native_client/ctcdecode/__init__.py#L25-L59
train
mozilla/DeepSpeech
native_client/ctcdecode/__init__.py
ctc_beam_search_decoder_batch
def ctc_beam_search_decoder_batch(probs_seq, seq_lengths, alphabet, beam_size, num_processes, cutoff_prob=1.0, cutof...
python
def ctc_beam_search_decoder_batch(probs_seq, seq_lengths, alphabet, beam_size, num_processes, cutoff_prob=1.0, cutof...
[ "def", "ctc_beam_search_decoder_batch", "(", "probs_seq", ",", "seq_lengths", ",", "alphabet", ",", "beam_size", ",", "num_processes", ",", "cutoff_prob", "=", "1.0", ",", "cutoff_top_n", "=", "40", ",", "scorer", "=", "None", ")", ":", "batch_beam_results", "="...
Wrapper for the batched CTC beam search decoder. :param probs_seq: 3-D list with each element as an instance of 2-D list of probabilities used by ctc_beam_search_decoder(). :type probs_seq: 3-D list :param alphabet: alphabet list. :alphabet: Alphabet :param beam_size: Width fo...
[ "Wrapper", "for", "the", "batched", "CTC", "beam", "search", "decoder", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/native_client/ctcdecode/__init__.py#L62-L104
train
mozilla/DeepSpeech
examples/mic_vad_streaming/mic_vad_streaming.py
Audio.resample
def resample(self, data, input_rate): """ Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio r...
python
def resample(self, data, input_rate): """ Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio r...
[ "def", "resample", "(", "self", ",", "data", ",", "input_rate", ")", ":", "data16", "=", "np", ".", "fromstring", "(", "string", "=", "data", ",", "dtype", "=", "np", ".", "int16", ")", "resample_size", "=", "int", "(", "len", "(", "data16", ")", "...
Microphone may not support our native processing sampling rate, so resample from input_rate to RATE_PROCESS here for webrtcvad and deepspeech Args: data (binary): Input audio stream input_rate (int): Input audio rate to resample from
[ "Microphone", "may", "not", "support", "our", "native", "processing", "sampling", "rate", "so", "resample", "from", "input_rate", "to", "RATE_PROCESS", "here", "for", "webrtcvad", "and", "deepspeech" ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L52-L66
train
mozilla/DeepSpeech
examples/mic_vad_streaming/mic_vad_streaming.py
Audio.read_resampled
def read_resampled(self): """Return a block of audio data resampled to 16000hz, blocking if necessary.""" return self.resample(data=self.buffer_queue.get(), input_rate=self.input_rate)
python
def read_resampled(self): """Return a block of audio data resampled to 16000hz, blocking if necessary.""" return self.resample(data=self.buffer_queue.get(), input_rate=self.input_rate)
[ "def", "read_resampled", "(", "self", ")", ":", "return", "self", ".", "resample", "(", "data", "=", "self", ".", "buffer_queue", ".", "get", "(", ")", ",", "input_rate", "=", "self", ".", "input_rate", ")" ]
Return a block of audio data resampled to 16000hz, blocking if necessary.
[ "Return", "a", "block", "of", "audio", "data", "resampled", "to", "16000hz", "blocking", "if", "necessary", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L68-L71
train
mozilla/DeepSpeech
examples/mic_vad_streaming/mic_vad_streaming.py
VADAudio.frame_generator
def frame_generator(self): """Generator that yields all audio frames from microphone.""" if self.input_rate == self.RATE_PROCESS: while True: yield self.read() else: while True: yield self.read_resampled()
python
def frame_generator(self): """Generator that yields all audio frames from microphone.""" if self.input_rate == self.RATE_PROCESS: while True: yield self.read() else: while True: yield self.read_resampled()
[ "def", "frame_generator", "(", "self", ")", ":", "if", "self", ".", "input_rate", "==", "self", ".", "RATE_PROCESS", ":", "while", "True", ":", "yield", "self", ".", "read", "(", ")", "else", ":", "while", "True", ":", "yield", "self", ".", "read_resam...
Generator that yields all audio frames from microphone.
[ "Generator", "that", "yields", "all", "audio", "frames", "from", "microphone", "." ]
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L103-L110
train