partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
Layer.freeze
|
freeze module, if names is not None, set an array of layers that match given names
to be freezed
:param names: an array of layer names
:return:
|
pyspark/bigdl/nn/layer.py
|
def freeze(self, names=None):
"""
freeze module, if names is not None, set an array of layers that match given names
to be freezed
:param names: an array of layer names
:return:
"""
callBigDlFunc(self.bigdl_type, "freeze", self.value, names)
return self
|
def freeze(self, names=None):
"""
freeze module, if names is not None, set an array of layers that match given names
to be freezed
:param names: an array of layer names
:return:
"""
callBigDlFunc(self.bigdl_type, "freeze", self.value, names)
return self
|
[
"freeze",
"module",
"if",
"names",
"is",
"not",
"None",
"set",
"an",
"array",
"of",
"layers",
"that",
"match",
"given",
"names",
"to",
"be",
"freezed",
":",
"param",
"names",
":",
"an",
"array",
"of",
"layer",
"names",
":",
"return",
":"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L576-L584
|
[
"def",
"freeze",
"(",
"self",
",",
"names",
"=",
"None",
")",
":",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"freeze\"",
",",
"self",
".",
"value",
",",
"names",
")",
"return",
"self"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Layer.unfreeze
|
unfreeze module, if names is not None, unfreeze layers that match given names
:param names: an array of layer names
:return:
|
pyspark/bigdl/nn/layer.py
|
def unfreeze(self, names=None):
"""
unfreeze module, if names is not None, unfreeze layers that match given names
:param names: an array of layer names
:return:
"""
callBigDlFunc(self.bigdl_type, "unFreeze", self.value, names)
return self
|
def unfreeze(self, names=None):
"""
unfreeze module, if names is not None, unfreeze layers that match given names
:param names: an array of layer names
:return:
"""
callBigDlFunc(self.bigdl_type, "unFreeze", self.value, names)
return self
|
[
"unfreeze",
"module",
"if",
"names",
"is",
"not",
"None",
"unfreeze",
"layers",
"that",
"match",
"given",
"names",
":",
"param",
"names",
":",
"an",
"array",
"of",
"layer",
"names",
":",
"return",
":"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L586-L593
|
[
"def",
"unfreeze",
"(",
"self",
",",
"names",
"=",
"None",
")",
":",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"unFreeze\"",
",",
"self",
".",
"value",
",",
"names",
")",
"return",
"self"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Layer.training
|
Set this layer in the training mode or in predition mode if is_training=False
|
pyspark/bigdl/nn/layer.py
|
def training(self, is_training=True):
'''
Set this layer in the training mode or in predition mode if is_training=False
'''
if is_training:
callJavaFunc(self.value.training)
else:
callJavaFunc(self.value.evaluate)
return self
|
def training(self, is_training=True):
'''
Set this layer in the training mode or in predition mode if is_training=False
'''
if is_training:
callJavaFunc(self.value.training)
else:
callJavaFunc(self.value.evaluate)
return self
|
[
"Set",
"this",
"layer",
"in",
"the",
"training",
"mode",
"or",
"in",
"predition",
"mode",
"if",
"is_training",
"=",
"False"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L595-L603
|
[
"def",
"training",
"(",
"self",
",",
"is_training",
"=",
"True",
")",
":",
"if",
"is_training",
":",
"callJavaFunc",
"(",
"self",
".",
"value",
".",
"training",
")",
"else",
":",
"callJavaFunc",
"(",
"self",
".",
"value",
".",
"evaluate",
")",
"return",
"self"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Layer.quantize
|
Clone self and quantize it, at last return a new quantized model.
:return: A new quantized model.
>>> fc = Linear(4, 2)
creating: createLinear
>>> fc.set_weights([np.ones((2, 4)), np.ones((2,))])
>>> input = np.ones((2, 4))
>>> output = fc.forward(input)
>>> expected_output = np.array([[5., 5.], [5., 5.]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_fc = fc.quantize()
>>> quantized_output = quantized_fc.forward(input)
>>> expected_quantized_output = np.array([[5., 5.], [5., 5.]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.Linear" in quantized_fc.__str__())
>>> conv = SpatialConvolution(1, 2, 3, 3)
creating: createSpatialConvolution
>>> conv.set_weights([np.ones((2, 1, 3, 3)), np.zeros((2,))])
>>> input = np.ones((2, 1, 4, 4))
>>> output = conv.forward(input)
>>> expected_output = np.array([[[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]], [[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_conv = conv.quantize()
>>> quantized_output = quantized_conv.forward(input)
>>> expected_quantized_output = np.array([[[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]], [[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.SpatialConvolution" in quantized_conv.__str__())
>>> seq = Sequential()
creating: createSequential
>>> seq = seq.add(conv)
>>> seq = seq.add(Reshape([8, 4], False))
creating: createReshape
>>> seq = seq.add(fc)
>>> input = np.ones([1, 1, 6, 6])
>>> output = seq.forward(input)
>>> expected_output = np.array([[37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_seq = seq.quantize()
>>> quantized_output = quantized_seq.forward(input)
>>> expected_quantized_output = np.array([[37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.Linear" in quantized_seq.__str__())
>>> assert("quantized.SpatialConvolution" in quantized_seq.__str__())
|
pyspark/bigdl/nn/layer.py
|
def quantize(self):
'''
Clone self and quantize it, at last return a new quantized model.
:return: A new quantized model.
>>> fc = Linear(4, 2)
creating: createLinear
>>> fc.set_weights([np.ones((2, 4)), np.ones((2,))])
>>> input = np.ones((2, 4))
>>> output = fc.forward(input)
>>> expected_output = np.array([[5., 5.], [5., 5.]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_fc = fc.quantize()
>>> quantized_output = quantized_fc.forward(input)
>>> expected_quantized_output = np.array([[5., 5.], [5., 5.]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.Linear" in quantized_fc.__str__())
>>> conv = SpatialConvolution(1, 2, 3, 3)
creating: createSpatialConvolution
>>> conv.set_weights([np.ones((2, 1, 3, 3)), np.zeros((2,))])
>>> input = np.ones((2, 1, 4, 4))
>>> output = conv.forward(input)
>>> expected_output = np.array([[[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]], [[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_conv = conv.quantize()
>>> quantized_output = quantized_conv.forward(input)
>>> expected_quantized_output = np.array([[[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]], [[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.SpatialConvolution" in quantized_conv.__str__())
>>> seq = Sequential()
creating: createSequential
>>> seq = seq.add(conv)
>>> seq = seq.add(Reshape([8, 4], False))
creating: createReshape
>>> seq = seq.add(fc)
>>> input = np.ones([1, 1, 6, 6])
>>> output = seq.forward(input)
>>> expected_output = np.array([[37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_seq = seq.quantize()
>>> quantized_output = quantized_seq.forward(input)
>>> expected_quantized_output = np.array([[37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.Linear" in quantized_seq.__str__())
>>> assert("quantized.SpatialConvolution" in quantized_seq.__str__())
'''
quantized_model = callBigDlFunc(self.bigdl_type, "quantize", self.value)
return Layer.of(quantized_model)
|
def quantize(self):
'''
Clone self and quantize it, at last return a new quantized model.
:return: A new quantized model.
>>> fc = Linear(4, 2)
creating: createLinear
>>> fc.set_weights([np.ones((2, 4)), np.ones((2,))])
>>> input = np.ones((2, 4))
>>> output = fc.forward(input)
>>> expected_output = np.array([[5., 5.], [5., 5.]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_fc = fc.quantize()
>>> quantized_output = quantized_fc.forward(input)
>>> expected_quantized_output = np.array([[5., 5.], [5., 5.]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.Linear" in quantized_fc.__str__())
>>> conv = SpatialConvolution(1, 2, 3, 3)
creating: createSpatialConvolution
>>> conv.set_weights([np.ones((2, 1, 3, 3)), np.zeros((2,))])
>>> input = np.ones((2, 1, 4, 4))
>>> output = conv.forward(input)
>>> expected_output = np.array([[[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]], [[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_conv = conv.quantize()
>>> quantized_output = quantized_conv.forward(input)
>>> expected_quantized_output = np.array([[[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]], [[[9., 9.], [9., 9.]], [[9., 9.], [9., 9.]]]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.SpatialConvolution" in quantized_conv.__str__())
>>> seq = Sequential()
creating: createSequential
>>> seq = seq.add(conv)
>>> seq = seq.add(Reshape([8, 4], False))
creating: createReshape
>>> seq = seq.add(fc)
>>> input = np.ones([1, 1, 6, 6])
>>> output = seq.forward(input)
>>> expected_output = np.array([[37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.]])
>>> np.testing.assert_allclose(output, expected_output)
>>> quantized_seq = seq.quantize()
>>> quantized_output = quantized_seq.forward(input)
>>> expected_quantized_output = np.array([[37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.], [37., 37.]])
>>> np.testing.assert_allclose(quantized_output, expected_quantized_output)
>>> assert("quantized.Linear" in quantized_seq.__str__())
>>> assert("quantized.SpatialConvolution" in quantized_seq.__str__())
'''
quantized_model = callBigDlFunc(self.bigdl_type, "quantize", self.value)
return Layer.of(quantized_model)
|
[
"Clone",
"self",
"and",
"quantize",
"it",
"at",
"last",
"return",
"a",
"new",
"quantized",
"model",
".",
":",
"return",
":",
"A",
"new",
"quantized",
"model",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L620-L668
|
[
"def",
"quantize",
"(",
"self",
")",
":",
"quantized_model",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"quantize\"",
",",
"self",
".",
"value",
")",
"return",
"Layer",
".",
"of",
"(",
"quantized_model",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.loadModel
|
Load a pre-trained Bigdl model.
:param path: The path containing the pre-trained model.
:return: A pre-trained model.
|
pyspark/bigdl/nn/layer.py
|
def loadModel(modelPath, weightPath =None, bigdl_type="float"):
"""
Load a pre-trained Bigdl model.
:param path: The path containing the pre-trained model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadBigDLModule", modelPath, weightPath)
return Layer.of(jmodel)
|
def loadModel(modelPath, weightPath =None, bigdl_type="float"):
"""
Load a pre-trained Bigdl model.
:param path: The path containing the pre-trained model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadBigDLModule", modelPath, weightPath)
return Layer.of(jmodel)
|
[
"Load",
"a",
"pre",
"-",
"trained",
"Bigdl",
"model",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L761-L769
|
[
"def",
"loadModel",
"(",
"modelPath",
",",
"weightPath",
"=",
"None",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"jmodel",
"=",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"loadBigDLModule\"",
",",
"modelPath",
",",
"weightPath",
")",
"return",
"Layer",
".",
"of",
"(",
"jmodel",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.load_torch
|
Load a pre-trained Torch model.
:param path: The path containing the pre-trained model.
:return: A pre-trained model.
|
pyspark/bigdl/nn/layer.py
|
def load_torch(path, bigdl_type="float"):
"""
Load a pre-trained Torch model.
:param path: The path containing the pre-trained model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadTorch", path)
return Layer.of(jmodel)
|
def load_torch(path, bigdl_type="float"):
"""
Load a pre-trained Torch model.
:param path: The path containing the pre-trained model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadTorch", path)
return Layer.of(jmodel)
|
[
"Load",
"a",
"pre",
"-",
"trained",
"Torch",
"model",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L772-L780
|
[
"def",
"load_torch",
"(",
"path",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"jmodel",
"=",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"loadTorch\"",
",",
"path",
")",
"return",
"Layer",
".",
"of",
"(",
"jmodel",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.load_keras
|
Load a pre-trained Keras model.
:param json_path: The json path containing the keras model definition.
:param hdf5_path: The HDF5 path containing the pre-trained keras model weights with or without the model architecture.
:return: A bigdl model.
|
pyspark/bigdl/nn/layer.py
|
def load_keras(json_path=None, hdf5_path=None, by_name=False):
"""
Load a pre-trained Keras model.
:param json_path: The json path containing the keras model definition.
:param hdf5_path: The HDF5 path containing the pre-trained keras model weights with or without the model architecture.
:return: A bigdl model.
"""
import os
try:
import tensorflow
except ImportError:
os.environ['KERAS_BACKEND'] = "theano"
try:
# Make theano backend compatible with Python3
from theano import ifelse
except ImportError:
raise Exception("No backend is found for Keras. "
"Please install either tensorflow or theano.")
from bigdl.keras.converter import DefinitionLoader, WeightLoader
if json_path and not hdf5_path:
return DefinitionLoader.from_json_path(json_path)
elif json_path and hdf5_path:
return WeightLoader.load_weights_from_json_hdf5(json_path, hdf5_path, by_name=by_name)
elif hdf5_path and not json_path:
kmodel, bmodel = DefinitionLoader.from_hdf5_path(hdf5_path)
WeightLoader.load_weights_from_kmodel(bmodel, kmodel)
return bmodel
|
def load_keras(json_path=None, hdf5_path=None, by_name=False):
"""
Load a pre-trained Keras model.
:param json_path: The json path containing the keras model definition.
:param hdf5_path: The HDF5 path containing the pre-trained keras model weights with or without the model architecture.
:return: A bigdl model.
"""
import os
try:
import tensorflow
except ImportError:
os.environ['KERAS_BACKEND'] = "theano"
try:
# Make theano backend compatible with Python3
from theano import ifelse
except ImportError:
raise Exception("No backend is found for Keras. "
"Please install either tensorflow or theano.")
from bigdl.keras.converter import DefinitionLoader, WeightLoader
if json_path and not hdf5_path:
return DefinitionLoader.from_json_path(json_path)
elif json_path and hdf5_path:
return WeightLoader.load_weights_from_json_hdf5(json_path, hdf5_path, by_name=by_name)
elif hdf5_path and not json_path:
kmodel, bmodel = DefinitionLoader.from_hdf5_path(hdf5_path)
WeightLoader.load_weights_from_kmodel(bmodel, kmodel)
return bmodel
|
[
"Load",
"a",
"pre",
"-",
"trained",
"Keras",
"model",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L783-L810
|
[
"def",
"load_keras",
"(",
"json_path",
"=",
"None",
",",
"hdf5_path",
"=",
"None",
",",
"by_name",
"=",
"False",
")",
":",
"import",
"os",
"try",
":",
"import",
"tensorflow",
"except",
"ImportError",
":",
"os",
".",
"environ",
"[",
"'KERAS_BACKEND'",
"]",
"=",
"\"theano\"",
"try",
":",
"# Make theano backend compatible with Python3",
"from",
"theano",
"import",
"ifelse",
"except",
"ImportError",
":",
"raise",
"Exception",
"(",
"\"No backend is found for Keras. \"",
"\"Please install either tensorflow or theano.\"",
")",
"from",
"bigdl",
".",
"keras",
".",
"converter",
"import",
"DefinitionLoader",
",",
"WeightLoader",
"if",
"json_path",
"and",
"not",
"hdf5_path",
":",
"return",
"DefinitionLoader",
".",
"from_json_path",
"(",
"json_path",
")",
"elif",
"json_path",
"and",
"hdf5_path",
":",
"return",
"WeightLoader",
".",
"load_weights_from_json_hdf5",
"(",
"json_path",
",",
"hdf5_path",
",",
"by_name",
"=",
"by_name",
")",
"elif",
"hdf5_path",
"and",
"not",
"json_path",
":",
"kmodel",
",",
"bmodel",
"=",
"DefinitionLoader",
".",
"from_hdf5_path",
"(",
"hdf5_path",
")",
"WeightLoader",
".",
"load_weights_from_kmodel",
"(",
"bmodel",
",",
"kmodel",
")",
"return",
"bmodel"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.load_caffe
|
Load a pre-trained Caffe model.
:param model: A bigdl model definition \which equivalent to the pre-trained caffe model.
:param defPath: The path containing the caffe model definition.
:param modelPath: The path containing the pre-trained caffe model.
:return: A pre-trained model.
|
pyspark/bigdl/nn/layer.py
|
def load_caffe(model, defPath, modelPath, match_all=True, bigdl_type="float"):
"""
Load a pre-trained Caffe model.
:param model: A bigdl model definition \which equivalent to the pre-trained caffe model.
:param defPath: The path containing the caffe model definition.
:param modelPath: The path containing the pre-trained caffe model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadCaffe", model, defPath, modelPath, match_all)
return Layer.of(jmodel)
|
def load_caffe(model, defPath, modelPath, match_all=True, bigdl_type="float"):
"""
Load a pre-trained Caffe model.
:param model: A bigdl model definition \which equivalent to the pre-trained caffe model.
:param defPath: The path containing the caffe model definition.
:param modelPath: The path containing the pre-trained caffe model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadCaffe", model, defPath, modelPath, match_all)
return Layer.of(jmodel)
|
[
"Load",
"a",
"pre",
"-",
"trained",
"Caffe",
"model",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L813-L824
|
[
"def",
"load_caffe",
"(",
"model",
",",
"defPath",
",",
"modelPath",
",",
"match_all",
"=",
"True",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"jmodel",
"=",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"loadCaffe\"",
",",
"model",
",",
"defPath",
",",
"modelPath",
",",
"match_all",
")",
"return",
"Layer",
".",
"of",
"(",
"jmodel",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.load_caffe_model
|
Load a pre-trained Caffe model.
:param defPath: The path containing the caffe model definition.
:param modelPath: The path containing the pre-trained caffe model.
:return: A pre-trained model.
|
pyspark/bigdl/nn/layer.py
|
def load_caffe_model(defPath, modelPath, bigdl_type="float"):
"""
Load a pre-trained Caffe model.
:param defPath: The path containing the caffe model definition.
:param modelPath: The path containing the pre-trained caffe model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadCaffeModel", defPath, modelPath)
return Layer.of(jmodel)
|
def load_caffe_model(defPath, modelPath, bigdl_type="float"):
"""
Load a pre-trained Caffe model.
:param defPath: The path containing the caffe model definition.
:param modelPath: The path containing the pre-trained caffe model.
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadCaffeModel", defPath, modelPath)
return Layer.of(jmodel)
|
[
"Load",
"a",
"pre",
"-",
"trained",
"Caffe",
"model",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L827-L837
|
[
"def",
"load_caffe_model",
"(",
"defPath",
",",
"modelPath",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"jmodel",
"=",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"loadCaffeModel\"",
",",
"defPath",
",",
"modelPath",
")",
"return",
"Layer",
".",
"of",
"(",
"jmodel",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.load_tensorflow
|
Load a pre-trained Tensorflow model.
:param path: The path containing the pre-trained model.
:param inputs: The input node of this graph
:param outputs: The output node of this graph
:param byte_order: byte_order of the file, `little_endian` or `big_endian`
:param bin_file: the optional bin file produced by bigdl dump_model util function to store the weights
:param generated_backward: if generate backward graph
:return: A pre-trained model.
|
pyspark/bigdl/nn/layer.py
|
def load_tensorflow(path, inputs, outputs, byte_order = "little_endian",
bin_file = None, generated_backward = True, bigdl_type = "float"):
"""
Load a pre-trained Tensorflow model.
:param path: The path containing the pre-trained model.
:param inputs: The input node of this graph
:param outputs: The output node of this graph
:param byte_order: byte_order of the file, `little_endian` or `big_endian`
:param bin_file: the optional bin file produced by bigdl dump_model util function to store the weights
:param generated_backward: if generate backward graph
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadTF", path, inputs, outputs,
byte_order, bin_file, generated_backward)
return Model.of(jmodel)
|
def load_tensorflow(path, inputs, outputs, byte_order = "little_endian",
bin_file = None, generated_backward = True, bigdl_type = "float"):
"""
Load a pre-trained Tensorflow model.
:param path: The path containing the pre-trained model.
:param inputs: The input node of this graph
:param outputs: The output node of this graph
:param byte_order: byte_order of the file, `little_endian` or `big_endian`
:param bin_file: the optional bin file produced by bigdl dump_model util function to store the weights
:param generated_backward: if generate backward graph
:return: A pre-trained model.
"""
jmodel = callBigDlFunc(bigdl_type, "loadTF", path, inputs, outputs,
byte_order, bin_file, generated_backward)
return Model.of(jmodel)
|
[
"Load",
"a",
"pre",
"-",
"trained",
"Tensorflow",
"model",
".",
":",
"param",
"path",
":",
"The",
"path",
"containing",
"the",
"pre",
"-",
"trained",
"model",
".",
":",
"param",
"inputs",
":",
"The",
"input",
"node",
"of",
"this",
"graph",
":",
"param",
"outputs",
":",
"The",
"output",
"node",
"of",
"this",
"graph",
":",
"param",
"byte_order",
":",
"byte_order",
"of",
"the",
"file",
"little_endian",
"or",
"big_endian",
":",
"param",
"bin_file",
":",
"the",
"optional",
"bin",
"file",
"produced",
"by",
"bigdl",
"dump_model",
"util",
"function",
"to",
"store",
"the",
"weights",
":",
"param",
"generated_backward",
":",
"if",
"generate",
"backward",
"graph",
":",
"return",
":",
"A",
"pre",
"-",
"trained",
"model",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L840-L854
|
[
"def",
"load_tensorflow",
"(",
"path",
",",
"inputs",
",",
"outputs",
",",
"byte_order",
"=",
"\"little_endian\"",
",",
"bin_file",
"=",
"None",
",",
"generated_backward",
"=",
"True",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"jmodel",
"=",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"loadTF\"",
",",
"path",
",",
"inputs",
",",
"outputs",
",",
"byte_order",
",",
"bin_file",
",",
"generated_backward",
")",
"return",
"Model",
".",
"of",
"(",
"jmodel",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.stop_gradient
|
stop the input gradient of layers that match the given ```names```
their input gradient are not computed.
And they will not contributed to the input gradient computation of
layers that depend on them.
:param stop_layers: an array of layer names
:param bigdl_type:
:return:
|
pyspark/bigdl/nn/layer.py
|
def stop_gradient(self, stop_layers, bigdl_type="float"):
"""
stop the input gradient of layers that match the given ```names```
their input gradient are not computed.
And they will not contributed to the input gradient computation of
layers that depend on them.
:param stop_layers: an array of layer names
:param bigdl_type:
:return:
"""
callBigDlFunc(bigdl_type, "setStopGradient", self.value, stop_layers)
return self
|
def stop_gradient(self, stop_layers, bigdl_type="float"):
"""
stop the input gradient of layers that match the given ```names```
their input gradient are not computed.
And they will not contributed to the input gradient computation of
layers that depend on them.
:param stop_layers: an array of layer names
:param bigdl_type:
:return:
"""
callBigDlFunc(bigdl_type, "setStopGradient", self.value, stop_layers)
return self
|
[
"stop",
"the",
"input",
"gradient",
"of",
"layers",
"that",
"match",
"the",
"given",
"names",
"their",
"input",
"gradient",
"are",
"not",
"computed",
".",
"And",
"they",
"will",
"not",
"contributed",
"to",
"the",
"input",
"gradient",
"computation",
"of",
"layers",
"that",
"depend",
"on",
"them",
".",
":",
"param",
"stop_layers",
":",
"an",
"array",
"of",
"layer",
"names",
":",
"param",
"bigdl_type",
":",
":",
"return",
":"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L870-L881
|
[
"def",
"stop_gradient",
"(",
"self",
",",
"stop_layers",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"setStopGradient\"",
",",
"self",
".",
"value",
",",
"stop_layers",
")",
"return",
"self"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.node
|
Return the corresponding node has the given name. If the given name doesn't match any node,
an exception will be thrown
:param name: node name
:param bigdl_type:
:return:
|
pyspark/bigdl/nn/layer.py
|
def node(self, name, bigdl_type="float"):
"""
Return the corresponding node has the given name. If the given name doesn't match any node,
an exception will be thrown
:param name: node name
:param bigdl_type:
:return:
"""
jnode = callBigDlFunc(bigdl_type, "findGraphNode", self.value, name)
return Node.of(jnode)
|
def node(self, name, bigdl_type="float"):
"""
Return the corresponding node has the given name. If the given name doesn't match any node,
an exception will be thrown
:param name: node name
:param bigdl_type:
:return:
"""
jnode = callBigDlFunc(bigdl_type, "findGraphNode", self.value, name)
return Node.of(jnode)
|
[
"Return",
"the",
"corresponding",
"node",
"has",
"the",
"given",
"name",
".",
"If",
"the",
"given",
"name",
"doesn",
"t",
"match",
"any",
"node",
"an",
"exception",
"will",
"be",
"thrown",
":",
"param",
"name",
":",
"node",
"name",
":",
"param",
"bigdl_type",
":",
":",
"return",
":"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L883-L892
|
[
"def",
"node",
"(",
"self",
",",
"name",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"jnode",
"=",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"findGraphNode\"",
",",
"self",
".",
"value",
",",
"name",
")",
"return",
"Node",
".",
"of",
"(",
"jnode",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Model.save_graph_topology
|
save current model graph to a folder, which can be display in tensorboard by running
tensorboard --logdir logPath
:param log_path: path to save the model graph
:param bigdl_type:
:return:
|
pyspark/bigdl/nn/layer.py
|
def save_graph_topology(self, log_path, bigdl_type="float"):
"""
save current model graph to a folder, which can be display in tensorboard by running
tensorboard --logdir logPath
:param log_path: path to save the model graph
:param bigdl_type:
:return:
"""
callBigDlFunc(bigdl_type, "saveGraphTopology", self.value, log_path)
return self
|
def save_graph_topology(self, log_path, bigdl_type="float"):
"""
save current model graph to a folder, which can be display in tensorboard by running
tensorboard --logdir logPath
:param log_path: path to save the model graph
:param bigdl_type:
:return:
"""
callBigDlFunc(bigdl_type, "saveGraphTopology", self.value, log_path)
return self
|
[
"save",
"current",
"model",
"graph",
"to",
"a",
"folder",
"which",
"can",
"be",
"display",
"in",
"tensorboard",
"by",
"running",
"tensorboard",
"--",
"logdir",
"logPath",
":",
"param",
"log_path",
":",
"path",
"to",
"save",
"the",
"model",
"graph",
":",
"param",
"bigdl_type",
":",
":",
"return",
":"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L894-L903
|
[
"def",
"save_graph_topology",
"(",
"self",
",",
"log_path",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"saveGraphTopology\"",
",",
"self",
".",
"value",
",",
"log_path",
")",
"return",
"self"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Criterion.forward
|
NB: It's for debug only, please use optimizer.optimize() in production.
Takes an input object, and computes the corresponding loss of the criterion,
compared with `target`
:param input: ndarray or list of ndarray
:param target: ndarray or list of ndarray
:return: value of loss
|
pyspark/bigdl/nn/criterion.py
|
def forward(self, input, target):
"""
NB: It's for debug only, please use optimizer.optimize() in production.
Takes an input object, and computes the corresponding loss of the criterion,
compared with `target`
:param input: ndarray or list of ndarray
:param target: ndarray or list of ndarray
:return: value of loss
"""
jinput, input_is_table = Layer.check_input(input)
jtarget, target_is_table = Layer.check_input(target)
output = callBigDlFunc(self.bigdl_type,
"criterionForward",
self.value,
jinput,
input_is_table,
jtarget,
target_is_table)
return output
|
def forward(self, input, target):
"""
NB: It's for debug only, please use optimizer.optimize() in production.
Takes an input object, and computes the corresponding loss of the criterion,
compared with `target`
:param input: ndarray or list of ndarray
:param target: ndarray or list of ndarray
:return: value of loss
"""
jinput, input_is_table = Layer.check_input(input)
jtarget, target_is_table = Layer.check_input(target)
output = callBigDlFunc(self.bigdl_type,
"criterionForward",
self.value,
jinput,
input_is_table,
jtarget,
target_is_table)
return output
|
[
"NB",
":",
"It",
"s",
"for",
"debug",
"only",
"please",
"use",
"optimizer",
".",
"optimize",
"()",
"in",
"production",
".",
"Takes",
"an",
"input",
"object",
"and",
"computes",
"the",
"corresponding",
"loss",
"of",
"the",
"criterion",
"compared",
"with",
"target"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/criterion.py#L44-L63
|
[
"def",
"forward",
"(",
"self",
",",
"input",
",",
"target",
")",
":",
"jinput",
",",
"input_is_table",
"=",
"Layer",
".",
"check_input",
"(",
"input",
")",
"jtarget",
",",
"target_is_table",
"=",
"Layer",
".",
"check_input",
"(",
"target",
")",
"output",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"criterionForward\"",
",",
"self",
".",
"value",
",",
"jinput",
",",
"input_is_table",
",",
"jtarget",
",",
"target_is_table",
")",
"return",
"output"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
Criterion.of
|
Create a python Criterion by a java criterion object
:param jcriterion: A java criterion object which created by Py4j
:return: a criterion.
|
pyspark/bigdl/nn/criterion.py
|
def of(cls, jcriterion, bigdl_type="float"):
"""
Create a python Criterion by a java criterion object
:param jcriterion: A java criterion object which created by Py4j
:return: a criterion.
"""
criterion = Criterion(bigdl_type, jcriterion)
criterion.value = jcriterion
criterion.bigdl_type = bigdl_type
return criterion
|
def of(cls, jcriterion, bigdl_type="float"):
"""
Create a python Criterion by a java criterion object
:param jcriterion: A java criterion object which created by Py4j
:return: a criterion.
"""
criterion = Criterion(bigdl_type, jcriterion)
criterion.value = jcriterion
criterion.bigdl_type = bigdl_type
return criterion
|
[
"Create",
"a",
"python",
"Criterion",
"by",
"a",
"java",
"criterion",
"object"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/criterion.py#L86-L96
|
[
"def",
"of",
"(",
"cls",
",",
"jcriterion",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"criterion",
"=",
"Criterion",
"(",
"bigdl_type",
",",
"jcriterion",
")",
"criterion",
".",
"value",
"=",
"jcriterion",
"criterion",
".",
"bigdl_type",
"=",
"bigdl_type",
"return",
"criterion"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
DLImageReader.readImages
|
Read the directory of images into DataFrame from the local or remote source.
:param path Directory to the input data files, the path can be comma separated paths as the
list of inputs. Wildcards path are supported similarly to sc.binaryFiles(path).
:param min_partitions A suggestion value of the minimal splitting number for input data.
:return DataFrame with a single column "image"; Each record in the column represents one image
record: Row (uri, height, width, channels, CvType, bytes)
|
pyspark/bigdl/dlframes/dl_image_reader.py
|
def readImages(path, sc=None, minParitions = 1, bigdl_type="float"):
"""
Read the directory of images into DataFrame from the local or remote source.
:param path Directory to the input data files, the path can be comma separated paths as the
list of inputs. Wildcards path are supported similarly to sc.binaryFiles(path).
:param min_partitions A suggestion value of the minimal splitting number for input data.
:return DataFrame with a single column "image"; Each record in the column represents one image
record: Row (uri, height, width, channels, CvType, bytes)
"""
df = callBigDlFunc(bigdl_type, "dlReadImage", path, sc, minParitions)
df._sc._jsc = sc._jsc
return df
|
def readImages(path, sc=None, minParitions = 1, bigdl_type="float"):
"""
Read the directory of images into DataFrame from the local or remote source.
:param path Directory to the input data files, the path can be comma separated paths as the
list of inputs. Wildcards path are supported similarly to sc.binaryFiles(path).
:param min_partitions A suggestion value of the minimal splitting number for input data.
:return DataFrame with a single column "image"; Each record in the column represents one image
record: Row (uri, height, width, channels, CvType, bytes)
"""
df = callBigDlFunc(bigdl_type, "dlReadImage", path, sc, minParitions)
df._sc._jsc = sc._jsc
return df
|
[
"Read",
"the",
"directory",
"of",
"images",
"into",
"DataFrame",
"from",
"the",
"local",
"or",
"remote",
"source",
".",
":",
"param",
"path",
"Directory",
"to",
"the",
"input",
"data",
"files",
"the",
"path",
"can",
"be",
"comma",
"separated",
"paths",
"as",
"the",
"list",
"of",
"inputs",
".",
"Wildcards",
"path",
"are",
"supported",
"similarly",
"to",
"sc",
".",
"binaryFiles",
"(",
"path",
")",
".",
":",
"param",
"min_partitions",
"A",
"suggestion",
"value",
"of",
"the",
"minimal",
"splitting",
"number",
"for",
"input",
"data",
".",
":",
"return",
"DataFrame",
"with",
"a",
"single",
"column",
"image",
";",
"Each",
"record",
"in",
"the",
"column",
"represents",
"one",
"image",
"record",
":",
"Row",
"(",
"uri",
"height",
"width",
"channels",
"CvType",
"bytes",
")"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/dlframes/dl_image_reader.py#L31-L42
|
[
"def",
"readImages",
"(",
"path",
",",
"sc",
"=",
"None",
",",
"minParitions",
"=",
"1",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"df",
"=",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"dlReadImage\"",
",",
"path",
",",
"sc",
",",
"minParitions",
")",
"df",
".",
"_sc",
".",
"_jsc",
"=",
"sc",
".",
"_jsc",
"return",
"df"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
WeightLoader.load_weights_from_json_hdf5
|
The file path can be stored in a local file system, HDFS, S3,
or any Hadoop-supported file system.
|
pyspark/bigdl/keras/converter.py
|
def load_weights_from_json_hdf5(def_json, weights_hdf5, by_name=False):
"""
The file path can be stored in a local file system, HDFS, S3,
or any Hadoop-supported file system.
"""
bmodel = DefinitionLoader.from_json_path(def_json)
def_value = BCommon.text_from_path(def_json)
kmodel = model_from_json(def_value)
WeightLoader.load_weights_from_hdf5(bmodel, kmodel, weights_hdf5, by_name)
return bmodel
|
def load_weights_from_json_hdf5(def_json, weights_hdf5, by_name=False):
"""
The file path can be stored in a local file system, HDFS, S3,
or any Hadoop-supported file system.
"""
bmodel = DefinitionLoader.from_json_path(def_json)
def_value = BCommon.text_from_path(def_json)
kmodel = model_from_json(def_value)
WeightLoader.load_weights_from_hdf5(bmodel, kmodel, weights_hdf5, by_name)
return bmodel
|
[
"The",
"file",
"path",
"can",
"be",
"stored",
"in",
"a",
"local",
"file",
"system",
"HDFS",
"S3",
"or",
"any",
"Hadoop",
"-",
"supported",
"file",
"system",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/keras/converter.py#L54-L63
|
[
"def",
"load_weights_from_json_hdf5",
"(",
"def_json",
",",
"weights_hdf5",
",",
"by_name",
"=",
"False",
")",
":",
"bmodel",
"=",
"DefinitionLoader",
".",
"from_json_path",
"(",
"def_json",
")",
"def_value",
"=",
"BCommon",
".",
"text_from_path",
"(",
"def_json",
")",
"kmodel",
"=",
"model_from_json",
"(",
"def_value",
")",
"WeightLoader",
".",
"load_weights_from_hdf5",
"(",
"bmodel",
",",
"kmodel",
",",
"weights_hdf5",
",",
"by_name",
")",
"return",
"bmodel"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
WeightLoader.load_weights_from_hdf5
|
Loads all layer weights from a HDF5 save file.
filepath can be stored in a local file system, HDFS, S3,
or any Hadoop-supported file system.
If `by_name` is False (default) weights are loaded
based on the network's execution order topology,
meaning layers in the execution seq should be exactly the same
the architecture
If `by_name` is True, weights are loaded into layers
only if they share the same name. This is useful
for fine-tuning or transfer-learning models where
some of the layers have changed.
|
pyspark/bigdl/keras/converter.py
|
def load_weights_from_hdf5(bmodel, kmodel, filepath, by_name=False):
'''Loads all layer weights from a HDF5 save file.
filepath can be stored in a local file system, HDFS, S3,
or any Hadoop-supported file system.
If `by_name` is False (default) weights are loaded
based on the network's execution order topology,
meaning layers in the execution seq should be exactly the same
the architecture
If `by_name` is True, weights are loaded into layers
only if they share the same name. This is useful
for fine-tuning or transfer-learning models where
some of the layers have changed.
'''
local_file_path = BCommon.get_local_file(filepath)
kmodel.load_weights(filepath=local_file_path, by_name=by_name)
WeightLoader.load_weights_from_kmodel(bmodel, kmodel)
|
def load_weights_from_hdf5(bmodel, kmodel, filepath, by_name=False):
'''Loads all layer weights from a HDF5 save file.
filepath can be stored in a local file system, HDFS, S3,
or any Hadoop-supported file system.
If `by_name` is False (default) weights are loaded
based on the network's execution order topology,
meaning layers in the execution seq should be exactly the same
the architecture
If `by_name` is True, weights are loaded into layers
only if they share the same name. This is useful
for fine-tuning or transfer-learning models where
some of the layers have changed.
'''
local_file_path = BCommon.get_local_file(filepath)
kmodel.load_weights(filepath=local_file_path, by_name=by_name)
WeightLoader.load_weights_from_kmodel(bmodel, kmodel)
|
[
"Loads",
"all",
"layer",
"weights",
"from",
"a",
"HDF5",
"save",
"file",
".",
"filepath",
"can",
"be",
"stored",
"in",
"a",
"local",
"file",
"system",
"HDFS",
"S3",
"or",
"any",
"Hadoop",
"-",
"supported",
"file",
"system",
".",
"If",
"by_name",
"is",
"False",
"(",
"default",
")",
"weights",
"are",
"loaded",
"based",
"on",
"the",
"network",
"s",
"execution",
"order",
"topology",
"meaning",
"layers",
"in",
"the",
"execution",
"seq",
"should",
"be",
"exactly",
"the",
"same",
"the",
"architecture"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/keras/converter.py#L67-L83
|
[
"def",
"load_weights_from_hdf5",
"(",
"bmodel",
",",
"kmodel",
",",
"filepath",
",",
"by_name",
"=",
"False",
")",
":",
"local_file_path",
"=",
"BCommon",
".",
"get_local_file",
"(",
"filepath",
")",
"kmodel",
".",
"load_weights",
"(",
"filepath",
"=",
"local_file_path",
",",
"by_name",
"=",
"by_name",
")",
"WeightLoader",
".",
"load_weights_from_kmodel",
"(",
"bmodel",
",",
"kmodel",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
WeightsConverter.get_weights_from_kmodel
|
Convert kmodel's weights to bigdl format.
We are supposing the order is the same as the execution order.
:param kmodel: keras model
:return: list of ndarray
|
pyspark/bigdl/keras/converter.py
|
def get_weights_from_kmodel(kmodel):
"""
Convert kmodel's weights to bigdl format.
We are supposing the order is the same as the execution order.
:param kmodel: keras model
:return: list of ndarray
"""
layers_with_weights = [layer for layer in kmodel.layers if layer.weights]
bweights = []
for klayer in layers_with_weights:
# bws would be [weights, bias] or [weights]
bws = WeightsConverter.get_bigdl_weights_from_klayer(klayer)
for w in bws:
bweights.append(w)
return bweights
|
def get_weights_from_kmodel(kmodel):
"""
Convert kmodel's weights to bigdl format.
We are supposing the order is the same as the execution order.
:param kmodel: keras model
:return: list of ndarray
"""
layers_with_weights = [layer for layer in kmodel.layers if layer.weights]
bweights = []
for klayer in layers_with_weights:
# bws would be [weights, bias] or [weights]
bws = WeightsConverter.get_bigdl_weights_from_klayer(klayer)
for w in bws:
bweights.append(w)
return bweights
|
[
"Convert",
"kmodel",
"s",
"weights",
"to",
"bigdl",
"format",
".",
"We",
"are",
"supposing",
"the",
"order",
"is",
"the",
"same",
"as",
"the",
"execution",
"order",
".",
":",
"param",
"kmodel",
":",
"keras",
"model",
":",
"return",
":",
"list",
"of",
"ndarray"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/keras/converter.py#L138-L152
|
[
"def",
"get_weights_from_kmodel",
"(",
"kmodel",
")",
":",
"layers_with_weights",
"=",
"[",
"layer",
"for",
"layer",
"in",
"kmodel",
".",
"layers",
"if",
"layer",
".",
"weights",
"]",
"bweights",
"=",
"[",
"]",
"for",
"klayer",
"in",
"layers_with_weights",
":",
"# bws would be [weights, bias] or [weights]",
"bws",
"=",
"WeightsConverter",
".",
"get_bigdl_weights_from_klayer",
"(",
"klayer",
")",
"for",
"w",
"in",
"bws",
":",
"bweights",
".",
"append",
"(",
"w",
")",
"return",
"bweights"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
DefinitionLoader.__build_node_id_2_klayer
|
The result would contain all of the layers including nested layers.
:param kmodel: a keras model which can be Sequential or Model
:param node_id_to_config_layer: a container to store the result
|
pyspark/bigdl/keras/converter.py
|
def __build_node_id_2_klayer(kmodel, node_id_to_config_layer):
"""
The result would contain all of the layers including nested layers.
:param kmodel: a keras model which can be Sequential or Model
:param node_id_to_config_layer: a container to store the result
"""
node_id_to_config_layer[kmodel.name] = kmodel # include itself as well
def gather_result(layers):
if layers: # layers maybe None here.
for layer in layers:
if layer.name not in node_id_to_config_layer:
node_id_to_config_layer[layer.name] = layer
DefinitionLoader.__build_node_id_2_klayer(layer, node_id_to_config_layer)
if hasattr(kmodel, "layers"):
gather_result(kmodel.layers)
if hasattr(kmodel, "flattened_layers"):
gather_result(kmodel.flattened_layers)
|
def __build_node_id_2_klayer(kmodel, node_id_to_config_layer):
"""
The result would contain all of the layers including nested layers.
:param kmodel: a keras model which can be Sequential or Model
:param node_id_to_config_layer: a container to store the result
"""
node_id_to_config_layer[kmodel.name] = kmodel # include itself as well
def gather_result(layers):
if layers: # layers maybe None here.
for layer in layers:
if layer.name not in node_id_to_config_layer:
node_id_to_config_layer[layer.name] = layer
DefinitionLoader.__build_node_id_2_klayer(layer, node_id_to_config_layer)
if hasattr(kmodel, "layers"):
gather_result(kmodel.layers)
if hasattr(kmodel, "flattened_layers"):
gather_result(kmodel.flattened_layers)
|
[
"The",
"result",
"would",
"contain",
"all",
"of",
"the",
"layers",
"including",
"nested",
"layers",
".",
":",
"param",
"kmodel",
":",
"a",
"keras",
"model",
"which",
"can",
"be",
"Sequential",
"or",
"Model",
":",
"param",
"node_id_to_config_layer",
":",
"a",
"container",
"to",
"store",
"the",
"result"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/keras/converter.py#L292-L308
|
[
"def",
"__build_node_id_2_klayer",
"(",
"kmodel",
",",
"node_id_to_config_layer",
")",
":",
"node_id_to_config_layer",
"[",
"kmodel",
".",
"name",
"]",
"=",
"kmodel",
"# include itself as well",
"def",
"gather_result",
"(",
"layers",
")",
":",
"if",
"layers",
":",
"# layers maybe None here.",
"for",
"layer",
"in",
"layers",
":",
"if",
"layer",
".",
"name",
"not",
"in",
"node_id_to_config_layer",
":",
"node_id_to_config_layer",
"[",
"layer",
".",
"name",
"]",
"=",
"layer",
"DefinitionLoader",
".",
"__build_node_id_2_klayer",
"(",
"layer",
",",
"node_id_to_config_layer",
")",
"if",
"hasattr",
"(",
"kmodel",
",",
"\"layers\"",
")",
":",
"gather_result",
"(",
"kmodel",
".",
"layers",
")",
"if",
"hasattr",
"(",
"kmodel",
",",
"\"flattened_layers\"",
")",
":",
"gather_result",
"(",
"kmodel",
".",
"flattened_layers",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
DefinitionLoader.from_hdf5_path
|
:param hdf5_path: hdf5 path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model
|
pyspark/bigdl/keras/converter.py
|
def from_hdf5_path(cls, hdf5_path):
"""
:param hdf5_path: hdf5 path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model
"""
from keras.models import load_model
hdf5_local_path = BCommon.get_local_file(hdf5_path)
kmodel = load_model(hdf5_local_path)
return kmodel, DefinitionLoader.from_kmodel(kmodel)
|
def from_hdf5_path(cls, hdf5_path):
"""
:param hdf5_path: hdf5 path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model
"""
from keras.models import load_model
hdf5_local_path = BCommon.get_local_file(hdf5_path)
kmodel = load_model(hdf5_local_path)
return kmodel, DefinitionLoader.from_kmodel(kmodel)
|
[
":",
"param",
"hdf5_path",
":",
"hdf5",
"path",
"which",
"can",
"be",
"stored",
"in",
"a",
"local",
"file",
"system",
"HDFS",
"S3",
"or",
"any",
"Hadoop",
"-",
"supported",
"file",
"system",
".",
":",
"return",
":",
"BigDL",
"Model"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/keras/converter.py#L351-L359
|
[
"def",
"from_hdf5_path",
"(",
"cls",
",",
"hdf5_path",
")",
":",
"from",
"keras",
".",
"models",
"import",
"load_model",
"hdf5_local_path",
"=",
"BCommon",
".",
"get_local_file",
"(",
"hdf5_path",
")",
"kmodel",
"=",
"load_model",
"(",
"hdf5_local_path",
")",
"return",
"kmodel",
",",
"DefinitionLoader",
".",
"from_kmodel",
"(",
"kmodel",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
DefinitionLoader.from_json_path
|
:param json_path: definition path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model
|
pyspark/bigdl/keras/converter.py
|
def from_json_path(cls, json_path):
"""
:param json_path: definition path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model
"""
json_str = BCommon.text_from_path(json_path)
return DefinitionLoader.from_json_str(json_str)
|
def from_json_path(cls, json_path):
"""
:param json_path: definition path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model
"""
json_str = BCommon.text_from_path(json_path)
return DefinitionLoader.from_json_str(json_str)
|
[
":",
"param",
"json_path",
":",
"definition",
"path",
"which",
"can",
"be",
"stored",
"in",
"a",
"local",
"file",
"system",
"HDFS",
"S3",
"or",
"any",
"Hadoop",
"-",
"supported",
"file",
"system",
".",
":",
"return",
":",
"BigDL",
"Model"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/keras/converter.py#L362-L368
|
[
"def",
"from_json_path",
"(",
"cls",
",",
"json_path",
")",
":",
"json_str",
"=",
"BCommon",
".",
"text_from_path",
"(",
"json_path",
")",
"return",
"DefinitionLoader",
".",
"from_json_str",
"(",
"json_str",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
load_imdb
|
Load IMDB dataset
Transform input data into an RDD of Sample
|
pyspark/bigdl/examples/keras/imdb_cnn_lstm.py
|
def load_imdb():
"""
Load IMDB dataset
Transform input data into an RDD of Sample
"""
from keras.preprocessing import sequence
from keras.datasets import imdb
(X_train, y_train), (X_test, y_test) = imdb.load_data(nb_words=20000)
X_train = sequence.pad_sequences(X_train, maxlen=100)
X_test = sequence.pad_sequences(X_test, maxlen=100)
return X_train, y_train, X_test, y_test
|
def load_imdb():
"""
Load IMDB dataset
Transform input data into an RDD of Sample
"""
from keras.preprocessing import sequence
from keras.datasets import imdb
(X_train, y_train), (X_test, y_test) = imdb.load_data(nb_words=20000)
X_train = sequence.pad_sequences(X_train, maxlen=100)
X_test = sequence.pad_sequences(X_test, maxlen=100)
return X_train, y_train, X_test, y_test
|
[
"Load",
"IMDB",
"dataset",
"Transform",
"input",
"data",
"into",
"an",
"RDD",
"of",
"Sample"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/examples/keras/imdb_cnn_lstm.py#L27-L37
|
[
"def",
"load_imdb",
"(",
")",
":",
"from",
"keras",
".",
"preprocessing",
"import",
"sequence",
"from",
"keras",
".",
"datasets",
"import",
"imdb",
"(",
"X_train",
",",
"y_train",
")",
",",
"(",
"X_test",
",",
"y_test",
")",
"=",
"imdb",
".",
"load_data",
"(",
"nb_words",
"=",
"20000",
")",
"X_train",
"=",
"sequence",
".",
"pad_sequences",
"(",
"X_train",
",",
"maxlen",
"=",
"100",
")",
"X_test",
"=",
"sequence",
".",
"pad_sequences",
"(",
"X_test",
",",
"maxlen",
"=",
"100",
")",
"return",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
build_keras_model
|
Define a recurrent convolutional model in Keras 1.2.2
|
pyspark/bigdl/examples/keras/imdb_cnn_lstm.py
|
def build_keras_model():
"""
Define a recurrent convolutional model in Keras 1.2.2
"""
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM
from keras.layers import Convolution1D, MaxPooling1D
keras_model = Sequential()
keras_model.add(Embedding(20000, 128, input_length=100))
keras_model.add(Dropout(0.25))
keras_model.add(Convolution1D(nb_filter=64,
filter_length=5,
border_mode='valid',
activation='relu',
subsample_length=1))
keras_model.add(MaxPooling1D(pool_length=4))
keras_model.add(LSTM(70))
keras_model.add(Dense(1))
keras_model.add(Activation('sigmoid'))
return keras_model
|
def build_keras_model():
"""
Define a recurrent convolutional model in Keras 1.2.2
"""
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import LSTM
from keras.layers import Convolution1D, MaxPooling1D
keras_model = Sequential()
keras_model.add(Embedding(20000, 128, input_length=100))
keras_model.add(Dropout(0.25))
keras_model.add(Convolution1D(nb_filter=64,
filter_length=5,
border_mode='valid',
activation='relu',
subsample_length=1))
keras_model.add(MaxPooling1D(pool_length=4))
keras_model.add(LSTM(70))
keras_model.add(Dense(1))
keras_model.add(Activation('sigmoid'))
return keras_model
|
[
"Define",
"a",
"recurrent",
"convolutional",
"model",
"in",
"Keras",
"1",
".",
"2",
".",
"2"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/examples/keras/imdb_cnn_lstm.py#L40-L61
|
[
"def",
"build_keras_model",
"(",
")",
":",
"from",
"keras",
".",
"models",
"import",
"Sequential",
"from",
"keras",
".",
"layers",
"import",
"Dense",
",",
"Dropout",
",",
"Activation",
"from",
"keras",
".",
"layers",
"import",
"Embedding",
"from",
"keras",
".",
"layers",
"import",
"LSTM",
"from",
"keras",
".",
"layers",
"import",
"Convolution1D",
",",
"MaxPooling1D",
"keras_model",
"=",
"Sequential",
"(",
")",
"keras_model",
".",
"add",
"(",
"Embedding",
"(",
"20000",
",",
"128",
",",
"input_length",
"=",
"100",
")",
")",
"keras_model",
".",
"add",
"(",
"Dropout",
"(",
"0.25",
")",
")",
"keras_model",
".",
"add",
"(",
"Convolution1D",
"(",
"nb_filter",
"=",
"64",
",",
"filter_length",
"=",
"5",
",",
"border_mode",
"=",
"'valid'",
",",
"activation",
"=",
"'relu'",
",",
"subsample_length",
"=",
"1",
")",
")",
"keras_model",
".",
"add",
"(",
"MaxPooling1D",
"(",
"pool_length",
"=",
"4",
")",
")",
"keras_model",
".",
"add",
"(",
"LSTM",
"(",
"70",
")",
")",
"keras_model",
".",
"add",
"(",
"Dense",
"(",
"1",
")",
")",
"keras_model",
".",
"add",
"(",
"Activation",
"(",
"'sigmoid'",
")",
")",
"return",
"keras_model"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
merge
|
Functional merge. Only use this method if you are defining a graph model.
Used to merge a list of input nodes into a single output node (NOT layers!),
following some merge mode.
# Arguments
inputs: A list of node instances. Must be more than one node.
mode: Merge mode. String, must be one of: 'sum', 'mul', 'concat', 'ave', 'cos',
'dot', 'max'. Default is 'sum'.
concat_axis: Int, axis to use when concatenating nodes. Only specify this when merge mode is 'concat'.
Default is -1, meaning the last axis of the input.
name: String to set the name of the merge. If not specified, its name will by default to be a generated string.
|
pyspark/bigdl/nn/keras/layer.py
|
def merge(inputs, mode="sum", concat_axis=-1, name=None):
"""
Functional merge. Only use this method if you are defining a graph model.
Used to merge a list of input nodes into a single output node (NOT layers!),
following some merge mode.
# Arguments
inputs: A list of node instances. Must be more than one node.
mode: Merge mode. String, must be one of: 'sum', 'mul', 'concat', 'ave', 'cos',
'dot', 'max'. Default is 'sum'.
concat_axis: Int, axis to use when concatenating nodes. Only specify this when merge mode is 'concat'.
Default is -1, meaning the last axis of the input.
name: String to set the name of the merge. If not specified, its name will by default to be a generated string.
"""
return Merge(mode=mode, concat_axis=concat_axis, name=name)(list(inputs))
|
def merge(inputs, mode="sum", concat_axis=-1, name=None):
"""
Functional merge. Only use this method if you are defining a graph model.
Used to merge a list of input nodes into a single output node (NOT layers!),
following some merge mode.
# Arguments
inputs: A list of node instances. Must be more than one node.
mode: Merge mode. String, must be one of: 'sum', 'mul', 'concat', 'ave', 'cos',
'dot', 'max'. Default is 'sum'.
concat_axis: Int, axis to use when concatenating nodes. Only specify this when merge mode is 'concat'.
Default is -1, meaning the last axis of the input.
name: String to set the name of the merge. If not specified, its name will by default to be a generated string.
"""
return Merge(mode=mode, concat_axis=concat_axis, name=name)(list(inputs))
|
[
"Functional",
"merge",
".",
"Only",
"use",
"this",
"method",
"if",
"you",
"are",
"defining",
"a",
"graph",
"model",
".",
"Used",
"to",
"merge",
"a",
"list",
"of",
"input",
"nodes",
"into",
"a",
"single",
"output",
"node",
"(",
"NOT",
"layers!",
")",
"following",
"some",
"merge",
"mode",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/keras/layer.py#L337-L351
|
[
"def",
"merge",
"(",
"inputs",
",",
"mode",
"=",
"\"sum\"",
",",
"concat_axis",
"=",
"-",
"1",
",",
"name",
"=",
"None",
")",
":",
"return",
"Merge",
"(",
"mode",
"=",
"mode",
",",
"concat_axis",
"=",
"concat_axis",
",",
"name",
"=",
"name",
")",
"(",
"list",
"(",
"inputs",
")",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
InferShape.get_input_shape
|
Return a list of shape tuples if there are multiple inputs.
Return one shape tuple otherwise.
|
pyspark/bigdl/nn/keras/layer.py
|
def get_input_shape(self):
"""
Return a list of shape tuples if there are multiple inputs.
Return one shape tuple otherwise.
"""
input = callBigDlFunc(self.bigdl_type, "getInputShape",
self.value)
return self.__process_shape(input)
|
def get_input_shape(self):
"""
Return a list of shape tuples if there are multiple inputs.
Return one shape tuple otherwise.
"""
input = callBigDlFunc(self.bigdl_type, "getInputShape",
self.value)
return self.__process_shape(input)
|
[
"Return",
"a",
"list",
"of",
"shape",
"tuples",
"if",
"there",
"are",
"multiple",
"inputs",
".",
"Return",
"one",
"shape",
"tuple",
"otherwise",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/keras/layer.py#L41-L48
|
[
"def",
"get_input_shape",
"(",
"self",
")",
":",
"input",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"getInputShape\"",
",",
"self",
".",
"value",
")",
"return",
"self",
".",
"__process_shape",
"(",
"input",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
InferShape.get_output_shape
|
Return a list of shape tuples if there are multiple outputs.
Return one shape tuple otherwise.
|
pyspark/bigdl/nn/keras/layer.py
|
def get_output_shape(self):
"""
Return a list of shape tuples if there are multiple outputs.
Return one shape tuple otherwise.
"""
output = callBigDlFunc(self.bigdl_type, "getOutputShape",
self.value)
return self.__process_shape(output)
|
def get_output_shape(self):
"""
Return a list of shape tuples if there are multiple outputs.
Return one shape tuple otherwise.
"""
output = callBigDlFunc(self.bigdl_type, "getOutputShape",
self.value)
return self.__process_shape(output)
|
[
"Return",
"a",
"list",
"of",
"shape",
"tuples",
"if",
"there",
"are",
"multiple",
"outputs",
".",
"Return",
"one",
"shape",
"tuple",
"otherwise",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/keras/layer.py#L50-L57
|
[
"def",
"get_output_shape",
"(",
"self",
")",
":",
"output",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"getOutputShape\"",
",",
"self",
".",
"value",
")",
"return",
"self",
".",
"__process_shape",
"(",
"output",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
get_mnist
|
Get mnist dataset with features and label as ndarray.
Data would be downloaded automatically if it doesn't present at the specific location.
:param data_type: "train" for training data and "test" for testing data.
:param location: Location to store mnist dataset.
:return: (features: ndarray, label: ndarray)
|
pyspark/bigdl/models/local_lenet/local_lenet.py
|
def get_mnist(data_type="train", location="/tmp/mnist"):
"""
Get mnist dataset with features and label as ndarray.
Data would be downloaded automatically if it doesn't present at the specific location.
:param data_type: "train" for training data and "test" for testing data.
:param location: Location to store mnist dataset.
:return: (features: ndarray, label: ndarray)
"""
X, Y = mnist.read_data_sets(location, data_type)
return X, Y + 1
|
def get_mnist(data_type="train", location="/tmp/mnist"):
"""
Get mnist dataset with features and label as ndarray.
Data would be downloaded automatically if it doesn't present at the specific location.
:param data_type: "train" for training data and "test" for testing data.
:param location: Location to store mnist dataset.
:return: (features: ndarray, label: ndarray)
"""
X, Y = mnist.read_data_sets(location, data_type)
return X, Y + 1
|
[
"Get",
"mnist",
"dataset",
"with",
"features",
"and",
"label",
"as",
"ndarray",
".",
"Data",
"would",
"be",
"downloaded",
"automatically",
"if",
"it",
"doesn",
"t",
"present",
"at",
"the",
"specific",
"location",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/models/local_lenet/local_lenet.py#L25-L35
|
[
"def",
"get_mnist",
"(",
"data_type",
"=",
"\"train\"",
",",
"location",
"=",
"\"/tmp/mnist\"",
")",
":",
"X",
",",
"Y",
"=",
"mnist",
".",
"read_data_sets",
"(",
"location",
",",
"data_type",
")",
"return",
"X",
",",
"Y",
"+",
"1"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
read_data_sets
|
Parse or download movielens 1m data if train_dir is empty.
:param data_dir: The directory storing the movielens data
:return: a 2D numpy array with user index and item index in each row
|
pyspark/bigdl/dataset/movielens.py
|
def read_data_sets(data_dir):
"""
Parse or download movielens 1m data if train_dir is empty.
:param data_dir: The directory storing the movielens data
:return: a 2D numpy array with user index and item index in each row
"""
WHOLE_DATA = 'ml-1m.zip'
local_file = base.maybe_download(WHOLE_DATA, data_dir, SOURCE_URL + WHOLE_DATA)
zip_ref = zipfile.ZipFile(local_file, 'r')
extracted_to = os.path.join(data_dir, "ml-1m")
if not os.path.exists(extracted_to):
print("Extracting %s to %s" % (local_file, data_dir))
zip_ref.extractall(data_dir)
zip_ref.close()
rating_files = os.path.join(extracted_to,"ratings.dat")
rating_list = [i.strip().split("::") for i in open(rating_files,"r").readlines()]
movielens_data = np.array(rating_list).astype(int)
return movielens_data
|
def read_data_sets(data_dir):
"""
Parse or download movielens 1m data if train_dir is empty.
:param data_dir: The directory storing the movielens data
:return: a 2D numpy array with user index and item index in each row
"""
WHOLE_DATA = 'ml-1m.zip'
local_file = base.maybe_download(WHOLE_DATA, data_dir, SOURCE_URL + WHOLE_DATA)
zip_ref = zipfile.ZipFile(local_file, 'r')
extracted_to = os.path.join(data_dir, "ml-1m")
if not os.path.exists(extracted_to):
print("Extracting %s to %s" % (local_file, data_dir))
zip_ref.extractall(data_dir)
zip_ref.close()
rating_files = os.path.join(extracted_to,"ratings.dat")
rating_list = [i.strip().split("::") for i in open(rating_files,"r").readlines()]
movielens_data = np.array(rating_list).astype(int)
return movielens_data
|
[
"Parse",
"or",
"download",
"movielens",
"1m",
"data",
"if",
"train_dir",
"is",
"empty",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/dataset/movielens.py#L25-L44
|
[
"def",
"read_data_sets",
"(",
"data_dir",
")",
":",
"WHOLE_DATA",
"=",
"'ml-1m.zip'",
"local_file",
"=",
"base",
".",
"maybe_download",
"(",
"WHOLE_DATA",
",",
"data_dir",
",",
"SOURCE_URL",
"+",
"WHOLE_DATA",
")",
"zip_ref",
"=",
"zipfile",
".",
"ZipFile",
"(",
"local_file",
",",
"'r'",
")",
"extracted_to",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"ml-1m\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"extracted_to",
")",
":",
"print",
"(",
"\"Extracting %s to %s\"",
"%",
"(",
"local_file",
",",
"data_dir",
")",
")",
"zip_ref",
".",
"extractall",
"(",
"data_dir",
")",
"zip_ref",
".",
"close",
"(",
")",
"rating_files",
"=",
"os",
".",
"path",
".",
"join",
"(",
"extracted_to",
",",
"\"ratings.dat\"",
")",
"rating_list",
"=",
"[",
"i",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"::\"",
")",
"for",
"i",
"in",
"open",
"(",
"rating_files",
",",
"\"r\"",
")",
".",
"readlines",
"(",
")",
"]",
"movielens_data",
"=",
"np",
".",
"array",
"(",
"rating_list",
")",
".",
"astype",
"(",
"int",
")",
"return",
"movielens_data"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
get_bigdl_classpath
|
Get and return the jar path for bigdl if exists.
|
pyspark/bigdl/util/engine.py
|
def get_bigdl_classpath():
"""
Get and return the jar path for bigdl if exists.
"""
if os.getenv("BIGDL_CLASSPATH"):
return os.environ["BIGDL_CLASSPATH"]
jar_dir = os.path.abspath(__file__ + "/../../")
jar_paths = glob.glob(os.path.join(jar_dir, "share/lib/*.jar"))
if jar_paths:
assert len(jar_paths) == 1, "Expecting one jar: %s" % len(jar_paths)
return jar_paths[0]
return ""
|
def get_bigdl_classpath():
"""
Get and return the jar path for bigdl if exists.
"""
if os.getenv("BIGDL_CLASSPATH"):
return os.environ["BIGDL_CLASSPATH"]
jar_dir = os.path.abspath(__file__ + "/../../")
jar_paths = glob.glob(os.path.join(jar_dir, "share/lib/*.jar"))
if jar_paths:
assert len(jar_paths) == 1, "Expecting one jar: %s" % len(jar_paths)
return jar_paths[0]
return ""
|
[
"Get",
"and",
"return",
"the",
"jar",
"path",
"for",
"bigdl",
"if",
"exists",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/engine.py#L99-L110
|
[
"def",
"get_bigdl_classpath",
"(",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"\"BIGDL_CLASSPATH\"",
")",
":",
"return",
"os",
".",
"environ",
"[",
"\"BIGDL_CLASSPATH\"",
"]",
"jar_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
"+",
"\"/../../\"",
")",
"jar_paths",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"jar_dir",
",",
"\"share/lib/*.jar\"",
")",
")",
"if",
"jar_paths",
":",
"assert",
"len",
"(",
"jar_paths",
")",
"==",
"1",
",",
"\"Expecting one jar: %s\"",
"%",
"len",
"(",
"jar_paths",
")",
"return",
"jar_paths",
"[",
"0",
"]",
"return",
"\"\""
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
is_spark_below_2_2
|
Check if spark version is below 2.2
|
pyspark/bigdl/util/engine.py
|
def is_spark_below_2_2():
"""
Check if spark version is below 2.2
"""
import pyspark
if(hasattr(pyspark,"version")):
full_version = pyspark.version.__version__
# We only need the general spark version (eg, 1.6, 2.2).
parts = full_version.split(".")
spark_version = parts[0] + "." + parts[1]
if(compare_version(spark_version, "2.2")>=0):
return False
return True
|
def is_spark_below_2_2():
"""
Check if spark version is below 2.2
"""
import pyspark
if(hasattr(pyspark,"version")):
full_version = pyspark.version.__version__
# We only need the general spark version (eg, 1.6, 2.2).
parts = full_version.split(".")
spark_version = parts[0] + "." + parts[1]
if(compare_version(spark_version, "2.2")>=0):
return False
return True
|
[
"Check",
"if",
"spark",
"version",
"is",
"below",
"2",
".",
"2"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/engine.py#L113-L125
|
[
"def",
"is_spark_below_2_2",
"(",
")",
":",
"import",
"pyspark",
"if",
"(",
"hasattr",
"(",
"pyspark",
",",
"\"version\"",
")",
")",
":",
"full_version",
"=",
"pyspark",
".",
"version",
".",
"__version__",
"# We only need the general spark version (eg, 1.6, 2.2).",
"parts",
"=",
"full_version",
".",
"split",
"(",
"\".\"",
")",
"spark_version",
"=",
"parts",
"[",
"0",
"]",
"+",
"\".\"",
"+",
"parts",
"[",
"1",
"]",
"if",
"(",
"compare_version",
"(",
"spark_version",
",",
"\"2.2\"",
")",
">=",
"0",
")",
":",
"return",
"False",
"return",
"True"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
compare_version
|
Compare version strings.
:param version1;
:param version2;
:return: 1 if version1 is after version2; -1 if version1 is before version2; 0 if two versions are the same.
|
pyspark/bigdl/util/engine.py
|
def compare_version(version1, version2):
"""
Compare version strings.
:param version1;
:param version2;
:return: 1 if version1 is after version2; -1 if version1 is before version2; 0 if two versions are the same.
"""
v1Arr = version1.split(".")
v2Arr = version2.split(".")
len1 = len(v1Arr)
len2 = len(v2Arr)
lenMax = max(len1, len2)
for x in range(lenMax):
v1Token = 0
if x < len1:
v1Token = int(v1Arr[x])
v2Token = 0
if x < len2:
v2Token = int(v2Arr[x])
if v1Token < v2Token:
return -1
if v1Token > v2Token:
return 1
return 0
|
def compare_version(version1, version2):
"""
Compare version strings.
:param version1;
:param version2;
:return: 1 if version1 is after version2; -1 if version1 is before version2; 0 if two versions are the same.
"""
v1Arr = version1.split(".")
v2Arr = version2.split(".")
len1 = len(v1Arr)
len2 = len(v2Arr)
lenMax = max(len1, len2)
for x in range(lenMax):
v1Token = 0
if x < len1:
v1Token = int(v1Arr[x])
v2Token = 0
if x < len2:
v2Token = int(v2Arr[x])
if v1Token < v2Token:
return -1
if v1Token > v2Token:
return 1
return 0
|
[
"Compare",
"version",
"strings",
".",
":",
"param",
"version1",
";",
":",
"param",
"version2",
";",
":",
"return",
":",
"1",
"if",
"version1",
"is",
"after",
"version2",
";",
"-",
"1",
"if",
"version1",
"is",
"before",
"version2",
";",
"0",
"if",
"two",
"versions",
"are",
"the",
"same",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/engine.py#L128-L151
|
[
"def",
"compare_version",
"(",
"version1",
",",
"version2",
")",
":",
"v1Arr",
"=",
"version1",
".",
"split",
"(",
"\".\"",
")",
"v2Arr",
"=",
"version2",
".",
"split",
"(",
"\".\"",
")",
"len1",
"=",
"len",
"(",
"v1Arr",
")",
"len2",
"=",
"len",
"(",
"v2Arr",
")",
"lenMax",
"=",
"max",
"(",
"len1",
",",
"len2",
")",
"for",
"x",
"in",
"range",
"(",
"lenMax",
")",
":",
"v1Token",
"=",
"0",
"if",
"x",
"<",
"len1",
":",
"v1Token",
"=",
"int",
"(",
"v1Arr",
"[",
"x",
"]",
")",
"v2Token",
"=",
"0",
"if",
"x",
"<",
"len2",
":",
"v2Token",
"=",
"int",
"(",
"v2Arr",
"[",
"x",
"]",
")",
"if",
"v1Token",
"<",
"v2Token",
":",
"return",
"-",
"1",
"if",
"v1Token",
">",
"v2Token",
":",
"return",
"1",
"return",
"0"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
convert
|
Convert tensorflow model to bigdl model
:param input_ops: operation list used for input, should be placeholders
:param output_ops: operations list used for output
:return: bigdl model
|
pyspark/bigdl/util/tf_utils.py
|
def convert(input_ops, output_ops, byte_order, bigdl_type):
"""
Convert tensorflow model to bigdl model
:param input_ops: operation list used for input, should be placeholders
:param output_ops: operations list used for output
:return: bigdl model
"""
input_names = map(lambda x: x.name.split(":")[0], input_ops)
output_names = map(lambda x: x.name.split(":")[0], output_ops)
temp = tempfile.mkdtemp()
dump_model(path=temp)
model_path = temp + '/model.pb'
bin_path = temp + '/model.bin'
model = Model.load_tensorflow(model_path, input_names, output_names,
byte_order, bin_path, bigdl_type)
try:
shutil.rmtree(temp)
except OSError as e:
if e.errno != errno.ENOENT:
raise
return model
|
def convert(input_ops, output_ops, byte_order, bigdl_type):
"""
Convert tensorflow model to bigdl model
:param input_ops: operation list used for input, should be placeholders
:param output_ops: operations list used for output
:return: bigdl model
"""
input_names = map(lambda x: x.name.split(":")[0], input_ops)
output_names = map(lambda x: x.name.split(":")[0], output_ops)
temp = tempfile.mkdtemp()
dump_model(path=temp)
model_path = temp + '/model.pb'
bin_path = temp + '/model.bin'
model = Model.load_tensorflow(model_path, input_names, output_names,
byte_order, bin_path, bigdl_type)
try:
shutil.rmtree(temp)
except OSError as e:
if e.errno != errno.ENOENT:
raise
return model
|
[
"Convert",
"tensorflow",
"model",
"to",
"bigdl",
"model",
":",
"param",
"input_ops",
":",
"operation",
"list",
"used",
"for",
"input",
"should",
"be",
"placeholders",
":",
"param",
"output_ops",
":",
"operations",
"list",
"used",
"for",
"output",
":",
"return",
":",
"bigdl",
"model"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/tf_utils.py#L55-L80
|
[
"def",
"convert",
"(",
"input_ops",
",",
"output_ops",
",",
"byte_order",
",",
"bigdl_type",
")",
":",
"input_names",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
",",
"input_ops",
")",
"output_names",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
",",
"output_ops",
")",
"temp",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"dump_model",
"(",
"path",
"=",
"temp",
")",
"model_path",
"=",
"temp",
"+",
"'/model.pb'",
"bin_path",
"=",
"temp",
"+",
"'/model.bin'",
"model",
"=",
"Model",
".",
"load_tensorflow",
"(",
"model_path",
",",
"input_names",
",",
"output_names",
",",
"byte_order",
",",
"bin_path",
",",
"bigdl_type",
")",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"temp",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"return",
"model"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
export_checkpoint
|
Export variable tensors from the checkpoint files.
:param checkpoint_path: tensorflow checkpoint path
:return: dictionary of tensor. The key is the variable name and the value is the numpy
|
pyspark/bigdl/util/tf_utils.py
|
def export_checkpoint(checkpoint_path):
"""
Export variable tensors from the checkpoint files.
:param checkpoint_path: tensorflow checkpoint path
:return: dictionary of tensor. The key is the variable name and the value is the numpy
"""
reader = tf.train.NewCheckpointReader(checkpoint_path)
# Get tensor name list
tensor_names = filter(lambda n: n!='global_step',
reader.get_variable_to_shape_map().keys())
# Prepare key-value dictionary
tensors = {}
for tn in tensor_names:
tensors[tn] = reader.get_tensor(tn)
return tensors
|
def export_checkpoint(checkpoint_path):
"""
Export variable tensors from the checkpoint files.
:param checkpoint_path: tensorflow checkpoint path
:return: dictionary of tensor. The key is the variable name and the value is the numpy
"""
reader = tf.train.NewCheckpointReader(checkpoint_path)
# Get tensor name list
tensor_names = filter(lambda n: n!='global_step',
reader.get_variable_to_shape_map().keys())
# Prepare key-value dictionary
tensors = {}
for tn in tensor_names:
tensors[tn] = reader.get_tensor(tn)
return tensors
|
[
"Export",
"variable",
"tensors",
"from",
"the",
"checkpoint",
"files",
"."
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/tf_utils.py#L83-L100
|
[
"def",
"export_checkpoint",
"(",
"checkpoint_path",
")",
":",
"reader",
"=",
"tf",
".",
"train",
".",
"NewCheckpointReader",
"(",
"checkpoint_path",
")",
"# Get tensor name list",
"tensor_names",
"=",
"filter",
"(",
"lambda",
"n",
":",
"n",
"!=",
"'global_step'",
",",
"reader",
".",
"get_variable_to_shape_map",
"(",
")",
".",
"keys",
"(",
")",
")",
"# Prepare key-value dictionary",
"tensors",
"=",
"{",
"}",
"for",
"tn",
"in",
"tensor_names",
":",
"tensors",
"[",
"tn",
"]",
"=",
"reader",
".",
"get_tensor",
"(",
"tn",
")",
"return",
"tensors"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
save_variable_bigdl
|
Save a variable dictionary to a Java object file, so it can be read by BigDL
:param tensors: tensor dictionary
:param target_path: where is the Java object file store
:param bigdl_type: model variable numeric type
:return: nothing
|
pyspark/bigdl/util/tf_utils.py
|
def save_variable_bigdl(tensors, target_path, bigdl_type="float"):
"""
Save a variable dictionary to a Java object file, so it can be read by BigDL
:param tensors: tensor dictionary
:param target_path: where is the Java object file store
:param bigdl_type: model variable numeric type
:return: nothing
"""
import numpy as np
jtensors = {}
for tn in tensors.keys():
if not isinstance(tensors[tn], np.ndarray):
value = np.array(tensors[tn])
else:
value = tensors[tn]
jtensors[tn] = JTensor.from_ndarray(value)
callBigDlFunc(bigdl_type, "saveTensorDictionary", jtensors, target_path)
|
def save_variable_bigdl(tensors, target_path, bigdl_type="float"):
"""
Save a variable dictionary to a Java object file, so it can be read by BigDL
:param tensors: tensor dictionary
:param target_path: where is the Java object file store
:param bigdl_type: model variable numeric type
:return: nothing
"""
import numpy as np
jtensors = {}
for tn in tensors.keys():
if not isinstance(tensors[tn], np.ndarray):
value = np.array(tensors[tn])
else:
value = tensors[tn]
jtensors[tn] = JTensor.from_ndarray(value)
callBigDlFunc(bigdl_type, "saveTensorDictionary", jtensors, target_path)
|
[
"Save",
"a",
"variable",
"dictionary",
"to",
"a",
"Java",
"object",
"file",
"so",
"it",
"can",
"be",
"read",
"by",
"BigDL"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/tf_utils.py#L103-L121
|
[
"def",
"save_variable_bigdl",
"(",
"tensors",
",",
"target_path",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"import",
"numpy",
"as",
"np",
"jtensors",
"=",
"{",
"}",
"for",
"tn",
"in",
"tensors",
".",
"keys",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"tensors",
"[",
"tn",
"]",
",",
"np",
".",
"ndarray",
")",
":",
"value",
"=",
"np",
".",
"array",
"(",
"tensors",
"[",
"tn",
"]",
")",
"else",
":",
"value",
"=",
"tensors",
"[",
"tn",
"]",
"jtensors",
"[",
"tn",
"]",
"=",
"JTensor",
".",
"from_ndarray",
"(",
"value",
")",
"callBigDlFunc",
"(",
"bigdl_type",
",",
"\"saveTensorDictionary\"",
",",
"jtensors",
",",
"target_path",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
dump_model
|
Dump a tensorflow model to files. The graph will be dumped to path/model.pb, and the checkpoint will
be dumped to path/model.bin
:param path: dump folder path
:param sess: if user pass in session, we assume that the variable of the graph in the session
has been inited
:param graph: tensorflow graph. Default use the default graph of the session
:param bigdl_type: model variable numeric type
:return: nothing
|
pyspark/bigdl/util/tf_utils.py
|
def dump_model(path, graph=None, sess=None, ckpt_file=None, bigdl_type="float"):
"""
Dump a tensorflow model to files. The graph will be dumped to path/model.pb, and the checkpoint will
be dumped to path/model.bin
:param path: dump folder path
:param sess: if user pass in session, we assume that the variable of the graph in the session
has been inited
:param graph: tensorflow graph. Default use the default graph of the session
:param bigdl_type: model variable numeric type
:return: nothing
"""
if not os.path.isdir(path):
raise ValueError("Folder " + path + " does not exist")
temp = None
if ckpt_file is None:
if sess is None:
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
temp = tempfile.mkdtemp()
ckpt_file = temp
# dump checkpoint to temp files
saver = tf.train.Saver()
saver.save(sess, ckpt_file)
# generate bin files
tensors = export_checkpoint(ckpt_file)
save_variable_bigdl(tensors, path + "/model.bin", bigdl_type)
# dump grap to pb file
graph = sess.graph if graph is None else graph
with gfile.GFile(path + "/model.pb", "wb") as f:
f.write(graph.as_graph_def().SerializeToString())
if temp is not None:
try:
shutil.rmtree(temp)
except OSError as e:
if e.errno != errno.ENOENT:
raise
|
def dump_model(path, graph=None, sess=None, ckpt_file=None, bigdl_type="float"):
"""
Dump a tensorflow model to files. The graph will be dumped to path/model.pb, and the checkpoint will
be dumped to path/model.bin
:param path: dump folder path
:param sess: if user pass in session, we assume that the variable of the graph in the session
has been inited
:param graph: tensorflow graph. Default use the default graph of the session
:param bigdl_type: model variable numeric type
:return: nothing
"""
if not os.path.isdir(path):
raise ValueError("Folder " + path + " does not exist")
temp = None
if ckpt_file is None:
if sess is None:
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
temp = tempfile.mkdtemp()
ckpt_file = temp
# dump checkpoint to temp files
saver = tf.train.Saver()
saver.save(sess, ckpt_file)
# generate bin files
tensors = export_checkpoint(ckpt_file)
save_variable_bigdl(tensors, path + "/model.bin", bigdl_type)
# dump grap to pb file
graph = sess.graph if graph is None else graph
with gfile.GFile(path + "/model.pb", "wb") as f:
f.write(graph.as_graph_def().SerializeToString())
if temp is not None:
try:
shutil.rmtree(temp)
except OSError as e:
if e.errno != errno.ENOENT:
raise
|
[
"Dump",
"a",
"tensorflow",
"model",
"to",
"files",
".",
"The",
"graph",
"will",
"be",
"dumped",
"to",
"path",
"/",
"model",
".",
"pb",
"and",
"the",
"checkpoint",
"will",
"be",
"dumped",
"to",
"path",
"/",
"model",
".",
"bin",
":",
"param",
"path",
":",
"dump",
"folder",
"path",
":",
"param",
"sess",
":",
"if",
"user",
"pass",
"in",
"session",
"we",
"assume",
"that",
"the",
"variable",
"of",
"the",
"graph",
"in",
"the",
"session",
"has",
"been",
"inited",
":",
"param",
"graph",
":",
"tensorflow",
"graph",
".",
"Default",
"use",
"the",
"default",
"graph",
"of",
"the",
"session",
":",
"param",
"bigdl_type",
":",
"model",
"variable",
"numeric",
"type",
":",
"return",
":",
"nothing"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/tf_utils.py#L124-L164
|
[
"def",
"dump_model",
"(",
"path",
",",
"graph",
"=",
"None",
",",
"sess",
"=",
"None",
",",
"ckpt_file",
"=",
"None",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"raise",
"ValueError",
"(",
"\"Folder \"",
"+",
"path",
"+",
"\" does not exist\"",
")",
"temp",
"=",
"None",
"if",
"ckpt_file",
"is",
"None",
":",
"if",
"sess",
"is",
"None",
":",
"sess",
"=",
"tf",
".",
"Session",
"(",
")",
"init",
"=",
"tf",
".",
"global_variables_initializer",
"(",
")",
"sess",
".",
"run",
"(",
"init",
")",
"temp",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"ckpt_file",
"=",
"temp",
"# dump checkpoint to temp files",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"saver",
".",
"save",
"(",
"sess",
",",
"ckpt_file",
")",
"# generate bin files",
"tensors",
"=",
"export_checkpoint",
"(",
"ckpt_file",
")",
"save_variable_bigdl",
"(",
"tensors",
",",
"path",
"+",
"\"/model.bin\"",
",",
"bigdl_type",
")",
"# dump grap to pb file",
"graph",
"=",
"sess",
".",
"graph",
"if",
"graph",
"is",
"None",
"else",
"graph",
"with",
"gfile",
".",
"GFile",
"(",
"path",
"+",
"\"/model.pb\"",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"graph",
".",
"as_graph_def",
"(",
")",
".",
"SerializeToString",
"(",
")",
")",
"if",
"temp",
"is",
"not",
"None",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"temp",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
merge_checkpoint
|
Get the variable values from the checkpoint file, and merge them to the GraphDef file
Args:
input_graph: the GraphDef file, doesn't contain variable values
checkpoint: the checkpoint file
output_node_names: A list of string, the output names
output_graph: String of the location and the name of the
output graph
|
pyspark/bigdl/util/tf_utils.py
|
def merge_checkpoint(input_graph,
checkpoint,
output_node_names,
output_graph,
sess):
"""
Get the variable values from the checkpoint file, and merge them to the GraphDef file
Args:
input_graph: the GraphDef file, doesn't contain variable values
checkpoint: the checkpoint file
output_node_names: A list of string, the output names
output_graph: String of the location and the name of the
output graph
"""
restore_op_name = "save/restore_all"
filename_tensor_name = "save/Const:0"
input_graph_def = graph_pb2.GraphDef()
with gfile.FastGFile(input_graph, "r") as f:
text_format.Merge(f.read().decode("utf-8"), input_graph_def)
for node in input_graph_def.node:
node.device = ""
importer.import_graph_def(input_graph_def, name="")
sess.run([restore_op_name], {filename_tensor_name: checkpoint})
output_graph_def = graph_util.convert_variables_to_constants(
sess,
input_graph_def,
output_node_names,
variable_names_blacklist=""
)
with gfile.GFile(output_graph, "wb") as f:
f.write(output_graph_def.SerializeToString())
|
def merge_checkpoint(input_graph,
checkpoint,
output_node_names,
output_graph,
sess):
"""
Get the variable values from the checkpoint file, and merge them to the GraphDef file
Args:
input_graph: the GraphDef file, doesn't contain variable values
checkpoint: the checkpoint file
output_node_names: A list of string, the output names
output_graph: String of the location and the name of the
output graph
"""
restore_op_name = "save/restore_all"
filename_tensor_name = "save/Const:0"
input_graph_def = graph_pb2.GraphDef()
with gfile.FastGFile(input_graph, "r") as f:
text_format.Merge(f.read().decode("utf-8"), input_graph_def)
for node in input_graph_def.node:
node.device = ""
importer.import_graph_def(input_graph_def, name="")
sess.run([restore_op_name], {filename_tensor_name: checkpoint})
output_graph_def = graph_util.convert_variables_to_constants(
sess,
input_graph_def,
output_node_names,
variable_names_blacklist=""
)
with gfile.GFile(output_graph, "wb") as f:
f.write(output_graph_def.SerializeToString())
|
[
"Get",
"the",
"variable",
"values",
"from",
"the",
"checkpoint",
"file",
"and",
"merge",
"them",
"to",
"the",
"GraphDef",
"file",
"Args",
":",
"input_graph",
":",
"the",
"GraphDef",
"file",
"doesn",
"t",
"contain",
"variable",
"values",
"checkpoint",
":",
"the",
"checkpoint",
"file",
"output_node_names",
":",
"A",
"list",
"of",
"string",
"the",
"output",
"names",
"output_graph",
":",
"String",
"of",
"the",
"location",
"and",
"the",
"name",
"of",
"the",
"output",
"graph"
] |
intel-analytics/BigDL
|
python
|
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/tf_utils.py#L167-L202
|
[
"def",
"merge_checkpoint",
"(",
"input_graph",
",",
"checkpoint",
",",
"output_node_names",
",",
"output_graph",
",",
"sess",
")",
":",
"restore_op_name",
"=",
"\"save/restore_all\"",
"filename_tensor_name",
"=",
"\"save/Const:0\"",
"input_graph_def",
"=",
"graph_pb2",
".",
"GraphDef",
"(",
")",
"with",
"gfile",
".",
"FastGFile",
"(",
"input_graph",
",",
"\"r\"",
")",
"as",
"f",
":",
"text_format",
".",
"Merge",
"(",
"f",
".",
"read",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
",",
"input_graph_def",
")",
"for",
"node",
"in",
"input_graph_def",
".",
"node",
":",
"node",
".",
"device",
"=",
"\"\"",
"importer",
".",
"import_graph_def",
"(",
"input_graph_def",
",",
"name",
"=",
"\"\"",
")",
"sess",
".",
"run",
"(",
"[",
"restore_op_name",
"]",
",",
"{",
"filename_tensor_name",
":",
"checkpoint",
"}",
")",
"output_graph_def",
"=",
"graph_util",
".",
"convert_variables_to_constants",
"(",
"sess",
",",
"input_graph_def",
",",
"output_node_names",
",",
"variable_names_blacklist",
"=",
"\"\"",
")",
"with",
"gfile",
".",
"GFile",
"(",
"output_graph",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"output_graph_def",
".",
"SerializeToString",
"(",
")",
")"
] |
e9c19788285986ab789a2e2998f9a85d7524779f
|
test
|
DefaultAgent._call
|
Processes batch of utterances and returns corresponding responses batch.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances indexes in incoming batch are used as dialog IDs.
Args:
utterances_batch: Batch of incoming utterances.
utterances_ids: Batch of dialog IDs corresponding to incoming utterances.
Returns:
responses: A batch of responses corresponding to the
utterance batch received by agent.
|
deeppavlov/agents/default_agent/default_agent.py
|
def _call(self, utterances_batch: list, utterances_ids: Optional[list]=None) -> list:
"""
Processes batch of utterances and returns corresponding responses batch.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances indexes in incoming batch are used as dialog IDs.
Args:
utterances_batch: Batch of incoming utterances.
utterances_ids: Batch of dialog IDs corresponding to incoming utterances.
Returns:
responses: A batch of responses corresponding to the
utterance batch received by agent.
"""
batch_size = len(utterances_batch)
ids = utterances_ids or list(range(batch_size))
batch_history = [self.history[utt_id] for utt_id in ids]
responses = []
filtered = self.skills_filter(utterances_batch, batch_history)
for skill_i, (filtered_utterances, skill) in enumerate(zip(filtered, self.wrapped_skills)):
skill_i_utt_indexes = [utt_index for utt_index, utt_filter in enumerate(filtered_utterances) if utt_filter]
if skill_i_utt_indexes:
skill_i_utt_batch = [utterances_batch[i] for i in skill_i_utt_indexes]
skill_i_utt_ids = [ids[i] for i in skill_i_utt_indexes]
res = [(None, 0.)] * batch_size
predicted, confidence = skill(skill_i_utt_batch, skill_i_utt_ids)
for i, predicted, confidence in zip(skill_i_utt_indexes, predicted, confidence):
res[i] = (predicted, confidence)
responses.append(res)
responses = self.skills_processor(utterances_batch, batch_history, *responses)
return responses
|
def _call(self, utterances_batch: list, utterances_ids: Optional[list]=None) -> list:
"""
Processes batch of utterances and returns corresponding responses batch.
Each call of Agent passes incoming utterances batch through skills filter,
agent skills, skills processor. Batch of dialog IDs can be provided, in
other case utterances indexes in incoming batch are used as dialog IDs.
Args:
utterances_batch: Batch of incoming utterances.
utterances_ids: Batch of dialog IDs corresponding to incoming utterances.
Returns:
responses: A batch of responses corresponding to the
utterance batch received by agent.
"""
batch_size = len(utterances_batch)
ids = utterances_ids or list(range(batch_size))
batch_history = [self.history[utt_id] for utt_id in ids]
responses = []
filtered = self.skills_filter(utterances_batch, batch_history)
for skill_i, (filtered_utterances, skill) in enumerate(zip(filtered, self.wrapped_skills)):
skill_i_utt_indexes = [utt_index for utt_index, utt_filter in enumerate(filtered_utterances) if utt_filter]
if skill_i_utt_indexes:
skill_i_utt_batch = [utterances_batch[i] for i in skill_i_utt_indexes]
skill_i_utt_ids = [ids[i] for i in skill_i_utt_indexes]
res = [(None, 0.)] * batch_size
predicted, confidence = skill(skill_i_utt_batch, skill_i_utt_ids)
for i, predicted, confidence in zip(skill_i_utt_indexes, predicted, confidence):
res[i] = (predicted, confidence)
responses.append(res)
responses = self.skills_processor(utterances_batch, batch_history, *responses)
return responses
|
[
"Processes",
"batch",
"of",
"utterances",
"and",
"returns",
"corresponding",
"responses",
"batch",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/agents/default_agent/default_agent.py#L56-L95
|
[
"def",
"_call",
"(",
"self",
",",
"utterances_batch",
":",
"list",
",",
"utterances_ids",
":",
"Optional",
"[",
"list",
"]",
"=",
"None",
")",
"->",
"list",
":",
"batch_size",
"=",
"len",
"(",
"utterances_batch",
")",
"ids",
"=",
"utterances_ids",
"or",
"list",
"(",
"range",
"(",
"batch_size",
")",
")",
"batch_history",
"=",
"[",
"self",
".",
"history",
"[",
"utt_id",
"]",
"for",
"utt_id",
"in",
"ids",
"]",
"responses",
"=",
"[",
"]",
"filtered",
"=",
"self",
".",
"skills_filter",
"(",
"utterances_batch",
",",
"batch_history",
")",
"for",
"skill_i",
",",
"(",
"filtered_utterances",
",",
"skill",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"filtered",
",",
"self",
".",
"wrapped_skills",
")",
")",
":",
"skill_i_utt_indexes",
"=",
"[",
"utt_index",
"for",
"utt_index",
",",
"utt_filter",
"in",
"enumerate",
"(",
"filtered_utterances",
")",
"if",
"utt_filter",
"]",
"if",
"skill_i_utt_indexes",
":",
"skill_i_utt_batch",
"=",
"[",
"utterances_batch",
"[",
"i",
"]",
"for",
"i",
"in",
"skill_i_utt_indexes",
"]",
"skill_i_utt_ids",
"=",
"[",
"ids",
"[",
"i",
"]",
"for",
"i",
"in",
"skill_i_utt_indexes",
"]",
"res",
"=",
"[",
"(",
"None",
",",
"0.",
")",
"]",
"*",
"batch_size",
"predicted",
",",
"confidence",
"=",
"skill",
"(",
"skill_i_utt_batch",
",",
"skill_i_utt_ids",
")",
"for",
"i",
",",
"predicted",
",",
"confidence",
"in",
"zip",
"(",
"skill_i_utt_indexes",
",",
"predicted",
",",
"confidence",
")",
":",
"res",
"[",
"i",
"]",
"=",
"(",
"predicted",
",",
"confidence",
")",
"responses",
".",
"append",
"(",
"res",
")",
"responses",
"=",
"self",
".",
"skills_processor",
"(",
"utterances_batch",
",",
"batch_history",
",",
"*",
"responses",
")",
"return",
"responses"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
expand_tile
|
Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2
|
deeppavlov/core/layers/keras_layers.py
|
def expand_tile(units, axis):
"""
Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2
"""
assert axis in (1, 2)
n_time_steps = K.int_shape(units)[1]
repetitions = [1, 1, 1, 1]
repetitions[axis] = n_time_steps
if axis == 1:
expanded = Reshape(target_shape=( (1,) + K.int_shape(units)[1:] ))(units)
else:
expanded = Reshape(target_shape=(K.int_shape(units)[1:2] + (1,) + K.int_shape(units)[2:]))(units)
return K.tile(expanded, repetitions)
|
def expand_tile(units, axis):
"""
Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2
"""
assert axis in (1, 2)
n_time_steps = K.int_shape(units)[1]
repetitions = [1, 1, 1, 1]
repetitions[axis] = n_time_steps
if axis == 1:
expanded = Reshape(target_shape=( (1,) + K.int_shape(units)[1:] ))(units)
else:
expanded = Reshape(target_shape=(K.int_shape(units)[1:2] + (1,) + K.int_shape(units)[2:]))(units)
return K.tile(expanded, repetitions)
|
[
"Expand",
"and",
"tile",
"tensor",
"along",
"given",
"axis"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/keras_layers.py#L22-L39
|
[
"def",
"expand_tile",
"(",
"units",
",",
"axis",
")",
":",
"assert",
"axis",
"in",
"(",
"1",
",",
"2",
")",
"n_time_steps",
"=",
"K",
".",
"int_shape",
"(",
"units",
")",
"[",
"1",
"]",
"repetitions",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
"repetitions",
"[",
"axis",
"]",
"=",
"n_time_steps",
"if",
"axis",
"==",
"1",
":",
"expanded",
"=",
"Reshape",
"(",
"target_shape",
"=",
"(",
"(",
"1",
",",
")",
"+",
"K",
".",
"int_shape",
"(",
"units",
")",
"[",
"1",
":",
"]",
")",
")",
"(",
"units",
")",
"else",
":",
"expanded",
"=",
"Reshape",
"(",
"target_shape",
"=",
"(",
"K",
".",
"int_shape",
"(",
"units",
")",
"[",
"1",
":",
"2",
"]",
"+",
"(",
"1",
",",
")",
"+",
"K",
".",
"int_shape",
"(",
"units",
")",
"[",
"2",
":",
"]",
")",
")",
"(",
"units",
")",
"return",
"K",
".",
"tile",
"(",
"expanded",
",",
"repetitions",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
additive_self_attention
|
Compute additive self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)>
v is a learnable vector of n_hidden dimensionality,
W_1 and W_2 are learnable [n_hidden, n_input_features] matrices
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of2784131 units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
|
deeppavlov/core/layers/keras_layers.py
|
def additive_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
"""
Compute additive self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)>
v is a learnable vector of n_hidden dimensionality,
W_1 and W_2 are learnable [n_hidden, n_input_features] matrices
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of2784131 units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
"""
n_input_features = K.int_shape(units)[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
exp1 = Lambda(lambda x: expand_tile(x, axis=1))(units)
exp2 = Lambda(lambda x: expand_tile(x, axis=2))(units)
units_pairs = Concatenate(axis=3)([exp1, exp2])
query = Dense(n_hidden, activation="tanh")(units_pairs)
attention = Dense(1, activation=lambda x: softmax(x, axis=2))(query)
attended_units = Lambda(lambda x: K.sum(attention * x, axis=2))(exp1)
output = Dense(n_output_features, activation=activation)(attended_units)
return output
|
def additive_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
"""
Compute additive self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)>
v is a learnable vector of n_hidden dimensionality,
W_1 and W_2 are learnable [n_hidden, n_input_features] matrices
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of2784131 units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
"""
n_input_features = K.int_shape(units)[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
exp1 = Lambda(lambda x: expand_tile(x, axis=1))(units)
exp2 = Lambda(lambda x: expand_tile(x, axis=2))(units)
units_pairs = Concatenate(axis=3)([exp1, exp2])
query = Dense(n_hidden, activation="tanh")(units_pairs)
attention = Dense(1, activation=lambda x: softmax(x, axis=2))(query)
attended_units = Lambda(lambda x: K.sum(attention * x, axis=2))(exp1)
output = Dense(n_output_features, activation=activation)(attended_units)
return output
|
[
"Compute",
"additive",
"self",
"attention",
"for",
"time",
"series",
"of",
"vectors",
"(",
"with",
"batch",
"dimension",
")",
"the",
"formula",
":",
"score",
"(",
"h_i",
"h_j",
")",
"=",
"<v",
"tanh",
"(",
"W_1",
"h_i",
"+",
"W_2",
"h_j",
")",
">",
"v",
"is",
"a",
"learnable",
"vector",
"of",
"n_hidden",
"dimensionality",
"W_1",
"and",
"W_2",
"are",
"learnable",
"[",
"n_hidden",
"n_input_features",
"]",
"matrices"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/keras_layers.py#L42-L70
|
[
"def",
"additive_self_attention",
"(",
"units",
",",
"n_hidden",
"=",
"None",
",",
"n_output_features",
"=",
"None",
",",
"activation",
"=",
"None",
")",
":",
"n_input_features",
"=",
"K",
".",
"int_shape",
"(",
"units",
")",
"[",
"2",
"]",
"if",
"n_hidden",
"is",
"None",
":",
"n_hidden",
"=",
"n_input_features",
"if",
"n_output_features",
"is",
"None",
":",
"n_output_features",
"=",
"n_input_features",
"exp1",
"=",
"Lambda",
"(",
"lambda",
"x",
":",
"expand_tile",
"(",
"x",
",",
"axis",
"=",
"1",
")",
")",
"(",
"units",
")",
"exp2",
"=",
"Lambda",
"(",
"lambda",
"x",
":",
"expand_tile",
"(",
"x",
",",
"axis",
"=",
"2",
")",
")",
"(",
"units",
")",
"units_pairs",
"=",
"Concatenate",
"(",
"axis",
"=",
"3",
")",
"(",
"[",
"exp1",
",",
"exp2",
"]",
")",
"query",
"=",
"Dense",
"(",
"n_hidden",
",",
"activation",
"=",
"\"tanh\"",
")",
"(",
"units_pairs",
")",
"attention",
"=",
"Dense",
"(",
"1",
",",
"activation",
"=",
"lambda",
"x",
":",
"softmax",
"(",
"x",
",",
"axis",
"=",
"2",
")",
")",
"(",
"query",
")",
"attended_units",
"=",
"Lambda",
"(",
"lambda",
"x",
":",
"K",
".",
"sum",
"(",
"attention",
"*",
"x",
",",
"axis",
"=",
"2",
")",
")",
"(",
"exp1",
")",
"output",
"=",
"Dense",
"(",
"n_output_features",
",",
"activation",
"=",
"activation",
")",
"(",
"attended_units",
")",
"return",
"output"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
multiplicative_self_attention
|
Compute multiplicative self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <W_1 h_i, W_2 h_j>, W_1 and W_2 are learnable matrices
with dimensionality [n_hidden, n_input_features]
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
|
deeppavlov/core/layers/keras_layers.py
|
def multiplicative_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
"""
Compute multiplicative self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <W_1 h_i, W_2 h_j>, W_1 and W_2 are learnable matrices
with dimensionality [n_hidden, n_input_features]
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
"""
n_input_features = K.int_shape(units)[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
exp1 = Lambda(lambda x: expand_tile(x, axis=1))(units)
exp2 = Lambda(lambda x: expand_tile(x, axis=2))(units)
queries = Dense(n_hidden)(exp1)
keys = Dense(n_hidden)(exp2)
scores = Lambda(lambda x: K.sum(queries * x, axis=3, keepdims=True))(keys)
attention = Lambda(lambda x: softmax(x, axis=2))(scores)
mult = Multiply()([attention, exp1])
attended_units = Lambda(lambda x: K.sum(x, axis=2))(mult)
output = Dense(n_output_features, activation=activation)(attended_units)
return output
|
def multiplicative_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
"""
Compute multiplicative self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <W_1 h_i, W_2 h_j>, W_1 and W_2 are learnable matrices
with dimensionality [n_hidden, n_input_features]
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
"""
n_input_features = K.int_shape(units)[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
exp1 = Lambda(lambda x: expand_tile(x, axis=1))(units)
exp2 = Lambda(lambda x: expand_tile(x, axis=2))(units)
queries = Dense(n_hidden)(exp1)
keys = Dense(n_hidden)(exp2)
scores = Lambda(lambda x: K.sum(queries * x, axis=3, keepdims=True))(keys)
attention = Lambda(lambda x: softmax(x, axis=2))(scores)
mult = Multiply()([attention, exp1])
attended_units = Lambda(lambda x: K.sum(x, axis=2))(mult)
output = Dense(n_output_features, activation=activation)(attended_units)
return output
|
[
"Compute",
"multiplicative",
"self",
"attention",
"for",
"time",
"series",
"of",
"vectors",
"(",
"with",
"batch",
"dimension",
")",
"the",
"formula",
":",
"score",
"(",
"h_i",
"h_j",
")",
"=",
"<W_1",
"h_i",
"W_2",
"h_j",
">",
"W_1",
"and",
"W_2",
"are",
"learnable",
"matrices",
"with",
"dimensionality",
"[",
"n_hidden",
"n_input_features",
"]"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/keras_layers.py#L73-L102
|
[
"def",
"multiplicative_self_attention",
"(",
"units",
",",
"n_hidden",
"=",
"None",
",",
"n_output_features",
"=",
"None",
",",
"activation",
"=",
"None",
")",
":",
"n_input_features",
"=",
"K",
".",
"int_shape",
"(",
"units",
")",
"[",
"2",
"]",
"if",
"n_hidden",
"is",
"None",
":",
"n_hidden",
"=",
"n_input_features",
"if",
"n_output_features",
"is",
"None",
":",
"n_output_features",
"=",
"n_input_features",
"exp1",
"=",
"Lambda",
"(",
"lambda",
"x",
":",
"expand_tile",
"(",
"x",
",",
"axis",
"=",
"1",
")",
")",
"(",
"units",
")",
"exp2",
"=",
"Lambda",
"(",
"lambda",
"x",
":",
"expand_tile",
"(",
"x",
",",
"axis",
"=",
"2",
")",
")",
"(",
"units",
")",
"queries",
"=",
"Dense",
"(",
"n_hidden",
")",
"(",
"exp1",
")",
"keys",
"=",
"Dense",
"(",
"n_hidden",
")",
"(",
"exp2",
")",
"scores",
"=",
"Lambda",
"(",
"lambda",
"x",
":",
"K",
".",
"sum",
"(",
"queries",
"*",
"x",
",",
"axis",
"=",
"3",
",",
"keepdims",
"=",
"True",
")",
")",
"(",
"keys",
")",
"attention",
"=",
"Lambda",
"(",
"lambda",
"x",
":",
"softmax",
"(",
"x",
",",
"axis",
"=",
"2",
")",
")",
"(",
"scores",
")",
"mult",
"=",
"Multiply",
"(",
")",
"(",
"[",
"attention",
",",
"exp1",
"]",
")",
"attended_units",
"=",
"Lambda",
"(",
"lambda",
"x",
":",
"K",
".",
"sum",
"(",
"x",
",",
"axis",
"=",
"2",
")",
")",
"(",
"mult",
")",
"output",
"=",
"Dense",
"(",
"n_output_features",
",",
"activation",
"=",
"activation",
")",
"(",
"attended_units",
")",
"return",
"output"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
precompute_future_symbols
|
Collecting possible continuations of length <= n for every node
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def precompute_future_symbols(trie, n, allow_spaces=False):
"""
Collecting possible continuations of length <= n for every node
"""
if n == 0:
return
if trie.is_terminated and trie.precompute_symbols:
# символы уже предпосчитаны
return
for index, final in enumerate(trie.final):
trie.data[index] = [set() for i in range(n)]
for index, (node_data, final) in enumerate(zip(trie.data, trie.final)):
node_data[0] = set(trie._get_letters(index))
if allow_spaces and final:
node_data[0].add(" ")
for d in range(1, n):
for index, (node_data, final) in enumerate(zip(trie.data, trie.final)):
children = set(trie._get_children(index))
for child in children:
node_data[d] |= trie.data[child][d - 1]
# в случае, если разрешён возврат по пробелу в стартовое состояние
if allow_spaces and final:
node_data[d] |= trie.data[trie.root][d - 1]
trie.terminated = True
|
def precompute_future_symbols(trie, n, allow_spaces=False):
"""
Collecting possible continuations of length <= n for every node
"""
if n == 0:
return
if trie.is_terminated and trie.precompute_symbols:
# символы уже предпосчитаны
return
for index, final in enumerate(trie.final):
trie.data[index] = [set() for i in range(n)]
for index, (node_data, final) in enumerate(zip(trie.data, trie.final)):
node_data[0] = set(trie._get_letters(index))
if allow_spaces and final:
node_data[0].add(" ")
for d in range(1, n):
for index, (node_data, final) in enumerate(zip(trie.data, trie.final)):
children = set(trie._get_children(index))
for child in children:
node_data[d] |= trie.data[child][d - 1]
# в случае, если разрешён возврат по пробелу в стартовое состояние
if allow_spaces and final:
node_data[d] |= trie.data[trie.root][d - 1]
trie.terminated = True
|
[
"Collecting",
"possible",
"continuations",
"of",
"length",
"<",
"=",
"n",
"for",
"every",
"node"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L465-L488
|
[
"def",
"precompute_future_symbols",
"(",
"trie",
",",
"n",
",",
"allow_spaces",
"=",
"False",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"if",
"trie",
".",
"is_terminated",
"and",
"trie",
".",
"precompute_symbols",
":",
"# символы уже предпосчитаны",
"return",
"for",
"index",
",",
"final",
"in",
"enumerate",
"(",
"trie",
".",
"final",
")",
":",
"trie",
".",
"data",
"[",
"index",
"]",
"=",
"[",
"set",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"index",
",",
"(",
"node_data",
",",
"final",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"trie",
".",
"data",
",",
"trie",
".",
"final",
")",
")",
":",
"node_data",
"[",
"0",
"]",
"=",
"set",
"(",
"trie",
".",
"_get_letters",
"(",
"index",
")",
")",
"if",
"allow_spaces",
"and",
"final",
":",
"node_data",
"[",
"0",
"]",
".",
"add",
"(",
"\" \"",
")",
"for",
"d",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"for",
"index",
",",
"(",
"node_data",
",",
"final",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"trie",
".",
"data",
",",
"trie",
".",
"final",
")",
")",
":",
"children",
"=",
"set",
"(",
"trie",
".",
"_get_children",
"(",
"index",
")",
")",
"for",
"child",
"in",
"children",
":",
"node_data",
"[",
"d",
"]",
"|=",
"trie",
".",
"data",
"[",
"child",
"]",
"[",
"d",
"-",
"1",
"]",
"# в случае, если разрешён возврат по пробелу в стартовое состояние",
"if",
"allow_spaces",
"and",
"final",
":",
"node_data",
"[",
"d",
"]",
"|=",
"trie",
".",
"data",
"[",
"trie",
".",
"root",
"]",
"[",
"d",
"-",
"1",
"]",
"trie",
".",
"terminated",
"=",
"True"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie.save
|
Сохраняет дерево для дальнейшего использования
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def save(self, outfile):
"""
Сохраняет дерево для дальнейшего использования
"""
with open(outfile, "w", encoding="utf8") as fout:
attr_values = [getattr(self, attr) for attr in Trie.ATTRS]
attr_values.append(any(x is not None for x in self.data))
fout.write("{}\n{}\t{}\n".format(
" ".join("T" if x else "F" for x in attr_values),
self.nodes_number, self.root))
fout.write(" ".join(str(a) for a in self.alphabet) + "\n")
for index, label in enumerate(self.final):
letters = self._get_letters(index, return_indexes=True)
children = self._get_children(index)
fout.write("{}\t{}\n".format(
"T" if label else "F", " ".join("{}:{}".format(*elem)
for elem in zip(letters, children))))
if self.precompute_symbols is not None:
for elem in self.data:
fout.write(":".join(",".join(
map(str, symbols)) for symbols in elem) + "\n")
return
|
def save(self, outfile):
"""
Сохраняет дерево для дальнейшего использования
"""
with open(outfile, "w", encoding="utf8") as fout:
attr_values = [getattr(self, attr) for attr in Trie.ATTRS]
attr_values.append(any(x is not None for x in self.data))
fout.write("{}\n{}\t{}\n".format(
" ".join("T" if x else "F" for x in attr_values),
self.nodes_number, self.root))
fout.write(" ".join(str(a) for a in self.alphabet) + "\n")
for index, label in enumerate(self.final):
letters = self._get_letters(index, return_indexes=True)
children = self._get_children(index)
fout.write("{}\t{}\n".format(
"T" if label else "F", " ".join("{}:{}".format(*elem)
for elem in zip(letters, children))))
if self.precompute_symbols is not None:
for elem in self.data:
fout.write(":".join(",".join(
map(str, symbols)) for symbols in elem) + "\n")
return
|
[
"Сохраняет",
"дерево",
"для",
"дальнейшего",
"использования"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L61-L82
|
[
"def",
"save",
"(",
"self",
",",
"outfile",
")",
":",
"with",
"open",
"(",
"outfile",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf8\"",
")",
"as",
"fout",
":",
"attr_values",
"=",
"[",
"getattr",
"(",
"self",
",",
"attr",
")",
"for",
"attr",
"in",
"Trie",
".",
"ATTRS",
"]",
"attr_values",
".",
"append",
"(",
"any",
"(",
"x",
"is",
"not",
"None",
"for",
"x",
"in",
"self",
".",
"data",
")",
")",
"fout",
".",
"write",
"(",
"\"{}\\n{}\\t{}\\n\"",
".",
"format",
"(",
"\" \"",
".",
"join",
"(",
"\"T\"",
"if",
"x",
"else",
"\"F\"",
"for",
"x",
"in",
"attr_values",
")",
",",
"self",
".",
"nodes_number",
",",
"self",
".",
"root",
")",
")",
"fout",
".",
"write",
"(",
"\" \"",
".",
"join",
"(",
"str",
"(",
"a",
")",
"for",
"a",
"in",
"self",
".",
"alphabet",
")",
"+",
"\"\\n\"",
")",
"for",
"index",
",",
"label",
"in",
"enumerate",
"(",
"self",
".",
"final",
")",
":",
"letters",
"=",
"self",
".",
"_get_letters",
"(",
"index",
",",
"return_indexes",
"=",
"True",
")",
"children",
"=",
"self",
".",
"_get_children",
"(",
"index",
")",
"fout",
".",
"write",
"(",
"\"{}\\t{}\\n\"",
".",
"format",
"(",
"\"T\"",
"if",
"label",
"else",
"\"F\"",
",",
"\" \"",
".",
"join",
"(",
"\"{}:{}\"",
".",
"format",
"(",
"*",
"elem",
")",
"for",
"elem",
"in",
"zip",
"(",
"letters",
",",
"children",
")",
")",
")",
")",
"if",
"self",
".",
"precompute_symbols",
"is",
"not",
"None",
":",
"for",
"elem",
"in",
"self",
".",
"data",
":",
"fout",
".",
"write",
"(",
"\":\"",
".",
"join",
"(",
"\",\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"symbols",
")",
")",
"for",
"symbols",
"in",
"elem",
")",
"+",
"\"\\n\"",
")",
"return"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie.make_cashed
|
Включает кэширование запросов к descend
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def make_cashed(self):
"""
Включает кэширование запросов к descend
"""
self._descendance_cash = [dict() for _ in self.graph]
self.descend = self._descend_cashed
|
def make_cashed(self):
"""
Включает кэширование запросов к descend
"""
self._descendance_cash = [dict() for _ in self.graph]
self.descend = self._descend_cashed
|
[
"Включает",
"кэширование",
"запросов",
"к",
"descend"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L84-L89
|
[
"def",
"make_cashed",
"(",
"self",
")",
":",
"self",
".",
"_descendance_cash",
"=",
"[",
"dict",
"(",
")",
"for",
"_",
"in",
"self",
".",
"graph",
"]",
"self",
".",
"descend",
"=",
"self",
".",
"_descend_cashed"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie.add
|
Добавление строки s в префиксный бор
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def add(self, s):
"""
Добавление строки s в префиксный бор
"""
if self.is_terminated:
raise TypeError("Impossible to add string to fitted trie")
if s == "":
self._set_final(self.root)
return
curr = self.root
for i, a in enumerate(s):
code = self.alphabet_codes[a]
next = self.graph[curr][code]
if next == Trie.NO_NODE:
curr = self._add_descendant(curr, s[i:])
break
else:
curr = next
self._set_final(curr)
return self
|
def add(self, s):
"""
Добавление строки s в префиксный бор
"""
if self.is_terminated:
raise TypeError("Impossible to add string to fitted trie")
if s == "":
self._set_final(self.root)
return
curr = self.root
for i, a in enumerate(s):
code = self.alphabet_codes[a]
next = self.graph[curr][code]
if next == Trie.NO_NODE:
curr = self._add_descendant(curr, s[i:])
break
else:
curr = next
self._set_final(curr)
return self
|
[
"Добавление",
"строки",
"s",
"в",
"префиксный",
"бор"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L96-L115
|
[
"def",
"add",
"(",
"self",
",",
"s",
")",
":",
"if",
"self",
".",
"is_terminated",
":",
"raise",
"TypeError",
"(",
"\"Impossible to add string to fitted trie\"",
")",
"if",
"s",
"==",
"\"\"",
":",
"self",
".",
"_set_final",
"(",
"self",
".",
"root",
")",
"return",
"curr",
"=",
"self",
".",
"root",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"s",
")",
":",
"code",
"=",
"self",
".",
"alphabet_codes",
"[",
"a",
"]",
"next",
"=",
"self",
".",
"graph",
"[",
"curr",
"]",
"[",
"code",
"]",
"if",
"next",
"==",
"Trie",
".",
"NO_NODE",
":",
"curr",
"=",
"self",
".",
"_add_descendant",
"(",
"curr",
",",
"s",
"[",
"i",
":",
"]",
")",
"break",
"else",
":",
"curr",
"=",
"next",
"self",
".",
"_set_final",
"(",
"curr",
")",
"return",
"self"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie.words
|
Возвращает итератор по словам, содержащимся в боре
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def words(self):
"""
Возвращает итератор по словам, содержащимся в боре
"""
branch, word, indexes = [self.root], [], [0]
letters_with_children = [self._get_children_and_letters(self.root)]
while len(branch) > 0:
if self.is_final(branch[-1]):
yield "".join(word)
while indexes[-1] == len(letters_with_children[-1]):
indexes.pop()
letters_with_children.pop()
branch.pop()
if len(indexes) == 0:
raise StopIteration()
word.pop()
next_letter, next_child = letters_with_children[-1][indexes[-1]]
indexes[-1] += 1
indexes.append(0)
word.append(next_letter)
branch.append(next_child)
letters_with_children.append(self._get_children_and_letters(branch[-1]))
|
def words(self):
"""
Возвращает итератор по словам, содержащимся в боре
"""
branch, word, indexes = [self.root], [], [0]
letters_with_children = [self._get_children_and_letters(self.root)]
while len(branch) > 0:
if self.is_final(branch[-1]):
yield "".join(word)
while indexes[-1] == len(letters_with_children[-1]):
indexes.pop()
letters_with_children.pop()
branch.pop()
if len(indexes) == 0:
raise StopIteration()
word.pop()
next_letter, next_child = letters_with_children[-1][indexes[-1]]
indexes[-1] += 1
indexes.append(0)
word.append(next_letter)
branch.append(next_child)
letters_with_children.append(self._get_children_and_letters(branch[-1]))
|
[
"Возвращает",
"итератор",
"по",
"словам",
"содержащимся",
"в",
"боре"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L139-L160
|
[
"def",
"words",
"(",
"self",
")",
":",
"branch",
",",
"word",
",",
"indexes",
"=",
"[",
"self",
".",
"root",
"]",
",",
"[",
"]",
",",
"[",
"0",
"]",
"letters_with_children",
"=",
"[",
"self",
".",
"_get_children_and_letters",
"(",
"self",
".",
"root",
")",
"]",
"while",
"len",
"(",
"branch",
")",
">",
"0",
":",
"if",
"self",
".",
"is_final",
"(",
"branch",
"[",
"-",
"1",
"]",
")",
":",
"yield",
"\"\"",
".",
"join",
"(",
"word",
")",
"while",
"indexes",
"[",
"-",
"1",
"]",
"==",
"len",
"(",
"letters_with_children",
"[",
"-",
"1",
"]",
")",
":",
"indexes",
".",
"pop",
"(",
")",
"letters_with_children",
".",
"pop",
"(",
")",
"branch",
".",
"pop",
"(",
")",
"if",
"len",
"(",
"indexes",
")",
"==",
"0",
":",
"raise",
"StopIteration",
"(",
")",
"word",
".",
"pop",
"(",
")",
"next_letter",
",",
"next_child",
"=",
"letters_with_children",
"[",
"-",
"1",
"]",
"[",
"indexes",
"[",
"-",
"1",
"]",
"]",
"indexes",
"[",
"-",
"1",
"]",
"+=",
"1",
"indexes",
".",
"append",
"(",
"0",
")",
"word",
".",
"append",
"(",
"next_letter",
")",
"branch",
".",
"append",
"(",
"next_child",
")",
"letters_with_children",
".",
"append",
"(",
"self",
".",
"_get_children_and_letters",
"(",
"branch",
"[",
"-",
"1",
"]",
")",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie.find_partitions
|
Находит все разбиения s = s_1 ... s_m на словарные слова s_1, ..., s_m
для m <= max_count
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def find_partitions(self, s, max_count=1):
"""
Находит все разбиения s = s_1 ... s_m на словарные слова s_1, ..., s_m
для m <= max_count
"""
curr_agenda = [(self.root, [], 0)]
for i, a in enumerate(s):
next_agenda = []
for curr, borders, cost in curr_agenda:
if cost >= max_count:
continue
child = self.graph[curr][self.alphabet_codes[a]]
# child = self.graph[curr][a]
if child == Trie.NO_NODE:
continue
next_agenda.append((child, borders, cost))
if self.is_final(child):
next_agenda.append((self.root, borders + [i+1], cost+1))
curr_agenda = next_agenda
answer = []
for curr, borders, cost in curr_agenda:
if curr == self.root:
borders = [0] + borders
answer.append([s[left:borders[i+1]] for i, left in enumerate(borders[:-1])])
return answer
|
def find_partitions(self, s, max_count=1):
"""
Находит все разбиения s = s_1 ... s_m на словарные слова s_1, ..., s_m
для m <= max_count
"""
curr_agenda = [(self.root, [], 0)]
for i, a in enumerate(s):
next_agenda = []
for curr, borders, cost in curr_agenda:
if cost >= max_count:
continue
child = self.graph[curr][self.alphabet_codes[a]]
# child = self.graph[curr][a]
if child == Trie.NO_NODE:
continue
next_agenda.append((child, borders, cost))
if self.is_final(child):
next_agenda.append((self.root, borders + [i+1], cost+1))
curr_agenda = next_agenda
answer = []
for curr, borders, cost in curr_agenda:
if curr == self.root:
borders = [0] + borders
answer.append([s[left:borders[i+1]] for i, left in enumerate(borders[:-1])])
return answer
|
[
"Находит",
"все",
"разбиения",
"s",
"=",
"s_1",
"...",
"s_m",
"на",
"словарные",
"слова",
"s_1",
"...",
"s_m",
"для",
"m",
"<",
"=",
"max_count"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L175-L199
|
[
"def",
"find_partitions",
"(",
"self",
",",
"s",
",",
"max_count",
"=",
"1",
")",
":",
"curr_agenda",
"=",
"[",
"(",
"self",
".",
"root",
",",
"[",
"]",
",",
"0",
")",
"]",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"s",
")",
":",
"next_agenda",
"=",
"[",
"]",
"for",
"curr",
",",
"borders",
",",
"cost",
"in",
"curr_agenda",
":",
"if",
"cost",
">=",
"max_count",
":",
"continue",
"child",
"=",
"self",
".",
"graph",
"[",
"curr",
"]",
"[",
"self",
".",
"alphabet_codes",
"[",
"a",
"]",
"]",
"# child = self.graph[curr][a]",
"if",
"child",
"==",
"Trie",
".",
"NO_NODE",
":",
"continue",
"next_agenda",
".",
"append",
"(",
"(",
"child",
",",
"borders",
",",
"cost",
")",
")",
"if",
"self",
".",
"is_final",
"(",
"child",
")",
":",
"next_agenda",
".",
"append",
"(",
"(",
"self",
".",
"root",
",",
"borders",
"+",
"[",
"i",
"+",
"1",
"]",
",",
"cost",
"+",
"1",
")",
")",
"curr_agenda",
"=",
"next_agenda",
"answer",
"=",
"[",
"]",
"for",
"curr",
",",
"borders",
",",
"cost",
"in",
"curr_agenda",
":",
"if",
"curr",
"==",
"self",
".",
"root",
":",
"borders",
"=",
"[",
"0",
"]",
"+",
"borders",
"answer",
".",
"append",
"(",
"[",
"s",
"[",
"left",
":",
"borders",
"[",
"i",
"+",
"1",
"]",
"]",
"for",
"i",
",",
"left",
"in",
"enumerate",
"(",
"borders",
"[",
":",
"-",
"1",
"]",
")",
"]",
")",
"return",
"answer"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie._add_empty_child
|
Добавление ребёнка к вершине parent по символу с кодом code
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def _add_empty_child(self, parent, code, final=False):
"""
Добавление ребёнка к вершине parent по символу с кодом code
"""
self.graph[parent][code] = self.nodes_number
self.graph.append(self._make_default_node())
self.data.append(None)
self.final.append(final)
self.nodes_number += 1
return (self.nodes_number - 1)
|
def _add_empty_child(self, parent, code, final=False):
"""
Добавление ребёнка к вершине parent по символу с кодом code
"""
self.graph[parent][code] = self.nodes_number
self.graph.append(self._make_default_node())
self.data.append(None)
self.final.append(final)
self.nodes_number += 1
return (self.nodes_number - 1)
|
[
"Добавление",
"ребёнка",
"к",
"вершине",
"parent",
"по",
"символу",
"с",
"кодом",
"code"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L224-L233
|
[
"def",
"_add_empty_child",
"(",
"self",
",",
"parent",
",",
"code",
",",
"final",
"=",
"False",
")",
":",
"self",
".",
"graph",
"[",
"parent",
"]",
"[",
"code",
"]",
"=",
"self",
".",
"nodes_number",
"self",
".",
"graph",
".",
"append",
"(",
"self",
".",
"_make_default_node",
"(",
")",
")",
"self",
".",
"data",
".",
"append",
"(",
"None",
")",
"self",
".",
"final",
".",
"append",
"(",
"final",
")",
"self",
".",
"nodes_number",
"+=",
"1",
"return",
"(",
"self",
".",
"nodes_number",
"-",
"1",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie._descend_simple
|
Спуск из вершины curr по строке s
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def _descend_simple(self, curr, s):
"""
Спуск из вершины curr по строке s
"""
for a in s:
curr = self.graph[curr][self.alphabet_codes[a]]
if curr == Trie.NO_NODE:
break
return curr
|
def _descend_simple(self, curr, s):
"""
Спуск из вершины curr по строке s
"""
for a in s:
curr = self.graph[curr][self.alphabet_codes[a]]
if curr == Trie.NO_NODE:
break
return curr
|
[
"Спуск",
"из",
"вершины",
"curr",
"по",
"строке",
"s"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L235-L243
|
[
"def",
"_descend_simple",
"(",
"self",
",",
"curr",
",",
"s",
")",
":",
"for",
"a",
"in",
"s",
":",
"curr",
"=",
"self",
".",
"graph",
"[",
"curr",
"]",
"[",
"self",
".",
"alphabet_codes",
"[",
"a",
"]",
"]",
"if",
"curr",
"==",
"Trie",
".",
"NO_NODE",
":",
"break",
"return",
"curr"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie._descend_cashed
|
Спуск из вершины curr по строке s с кэшированием
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def _descend_cashed(self, curr, s):
"""
Спуск из вершины curr по строке s с кэшированием
"""
if s == "":
return curr
curr_cash = self._descendance_cash[curr]
answer = curr_cash.get(s, None)
if answer is not None:
return answer
# для оптимизации дублируем код
res = curr
for a in s:
res = self.graph[res][self.alphabet_codes[a]]
# res = self.graph[res][a]
if res == Trie.NO_NODE:
break
curr_cash[s] = res
return res
|
def _descend_cashed(self, curr, s):
"""
Спуск из вершины curr по строке s с кэшированием
"""
if s == "":
return curr
curr_cash = self._descendance_cash[curr]
answer = curr_cash.get(s, None)
if answer is not None:
return answer
# для оптимизации дублируем код
res = curr
for a in s:
res = self.graph[res][self.alphabet_codes[a]]
# res = self.graph[res][a]
if res == Trie.NO_NODE:
break
curr_cash[s] = res
return res
|
[
"Спуск",
"из",
"вершины",
"curr",
"по",
"строке",
"s",
"с",
"кэшированием"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L245-L263
|
[
"def",
"_descend_cashed",
"(",
"self",
",",
"curr",
",",
"s",
")",
":",
"if",
"s",
"==",
"\"\"",
":",
"return",
"curr",
"curr_cash",
"=",
"self",
".",
"_descendance_cash",
"[",
"curr",
"]",
"answer",
"=",
"curr_cash",
".",
"get",
"(",
"s",
",",
"None",
")",
"if",
"answer",
"is",
"not",
"None",
":",
"return",
"answer",
"# для оптимизации дублируем код",
"res",
"=",
"curr",
"for",
"a",
"in",
"s",
":",
"res",
"=",
"self",
".",
"graph",
"[",
"res",
"]",
"[",
"self",
".",
"alphabet_codes",
"[",
"a",
"]",
"]",
"# res = self.graph[res][a]",
"if",
"res",
"==",
"Trie",
".",
"NO_NODE",
":",
"break",
"curr_cash",
"[",
"s",
"]",
"=",
"res",
"return",
"res"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie._get_letters
|
Извлекает все метки выходных рёбер вершины с номером index
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def _get_letters(self, index, return_indexes=False):
"""
Извлекает все метки выходных рёбер вершины с номером index
"""
if self.dict_storage:
answer = list(self.graph[index].keys())
else:
answer = [i for i, elem in enumerate(self.graph[index])
if elem != Trie.NO_NODE]
if not return_indexes:
answer = [(self.alphabet[i] if i >= 0 else " ") for i in answer]
return answer
|
def _get_letters(self, index, return_indexes=False):
"""
Извлекает все метки выходных рёбер вершины с номером index
"""
if self.dict_storage:
answer = list(self.graph[index].keys())
else:
answer = [i for i, elem in enumerate(self.graph[index])
if elem != Trie.NO_NODE]
if not return_indexes:
answer = [(self.alphabet[i] if i >= 0 else " ") for i in answer]
return answer
|
[
"Извлекает",
"все",
"метки",
"выходных",
"рёбер",
"вершины",
"с",
"номером",
"index"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L271-L282
|
[
"def",
"_get_letters",
"(",
"self",
",",
"index",
",",
"return_indexes",
"=",
"False",
")",
":",
"if",
"self",
".",
"dict_storage",
":",
"answer",
"=",
"list",
"(",
"self",
".",
"graph",
"[",
"index",
"]",
".",
"keys",
"(",
")",
")",
"else",
":",
"answer",
"=",
"[",
"i",
"for",
"i",
",",
"elem",
"in",
"enumerate",
"(",
"self",
".",
"graph",
"[",
"index",
"]",
")",
"if",
"elem",
"!=",
"Trie",
".",
"NO_NODE",
"]",
"if",
"not",
"return_indexes",
":",
"answer",
"=",
"[",
"(",
"self",
".",
"alphabet",
"[",
"i",
"]",
"if",
"i",
">=",
"0",
"else",
"\" \"",
")",
"for",
"i",
"in",
"answer",
"]",
"return",
"answer"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
Trie._get_children
|
Извлекает всех потомков вершины с номером index
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def _get_children(self, index):
"""
Извлекает всех потомков вершины с номером index
"""
if self.dict_storage:
return list(self.graph[index].values())
else:
return [elem for elem in self.graph[index] if elem != Trie.NO_NODE]
|
def _get_children(self, index):
"""
Извлекает всех потомков вершины с номером index
"""
if self.dict_storage:
return list(self.graph[index].values())
else:
return [elem for elem in self.graph[index] if elem != Trie.NO_NODE]
|
[
"Извлекает",
"всех",
"потомков",
"вершины",
"с",
"номером",
"index"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L295-L302
|
[
"def",
"_get_children",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"dict_storage",
":",
"return",
"list",
"(",
"self",
".",
"graph",
"[",
"index",
"]",
".",
"values",
"(",
")",
")",
"else",
":",
"return",
"[",
"elem",
"for",
"elem",
"in",
"self",
".",
"graph",
"[",
"index",
"]",
"if",
"elem",
"!=",
"Trie",
".",
"NO_NODE",
"]"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
TrieMinimizer.generate_postorder
|
Обратная топологическая сортировка
|
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
|
def generate_postorder(self, trie):
"""
Обратная топологическая сортировка
"""
order, stack = [], []
stack.append(trie.root)
colors = ['white'] * len(trie)
while len(stack) > 0:
index = stack[-1]
color = colors[index]
if color == 'white': # вершина ещё не обрабатывалась
colors[index] = 'grey'
for child in trie._get_children(index):
# проверяем, посещали ли мы ребёнка раньше
if child != Trie.NO_NODE and colors[child] == 'white':
stack.append(child)
else:
if color == 'grey':
colors[index] = 'black'
order.append(index)
stack = stack[:-1]
return order
|
def generate_postorder(self, trie):
"""
Обратная топологическая сортировка
"""
order, stack = [], []
stack.append(trie.root)
colors = ['white'] * len(trie)
while len(stack) > 0:
index = stack[-1]
color = colors[index]
if color == 'white': # вершина ещё не обрабатывалась
colors[index] = 'grey'
for child in trie._get_children(index):
# проверяем, посещали ли мы ребёнка раньше
if child != Trie.NO_NODE and colors[child] == 'white':
stack.append(child)
else:
if color == 'grey':
colors[index] = 'black'
order.append(index)
stack = stack[:-1]
return order
|
[
"Обратная",
"топологическая",
"сортировка"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L379-L400
|
[
"def",
"generate_postorder",
"(",
"self",
",",
"trie",
")",
":",
"order",
",",
"stack",
"=",
"[",
"]",
",",
"[",
"]",
"stack",
".",
"append",
"(",
"trie",
".",
"root",
")",
"colors",
"=",
"[",
"'white'",
"]",
"*",
"len",
"(",
"trie",
")",
"while",
"len",
"(",
"stack",
")",
">",
"0",
":",
"index",
"=",
"stack",
"[",
"-",
"1",
"]",
"color",
"=",
"colors",
"[",
"index",
"]",
"if",
"color",
"==",
"'white'",
":",
"# вершина ещё не обрабатывалась",
"colors",
"[",
"index",
"]",
"=",
"'grey'",
"for",
"child",
"in",
"trie",
".",
"_get_children",
"(",
"index",
")",
":",
"# проверяем, посещали ли мы ребёнка раньше",
"if",
"child",
"!=",
"Trie",
".",
"NO_NODE",
"and",
"colors",
"[",
"child",
"]",
"==",
"'white'",
":",
"stack",
".",
"append",
"(",
"child",
")",
"else",
":",
"if",
"color",
"==",
"'grey'",
":",
"colors",
"[",
"index",
"]",
"=",
"'black'",
"order",
".",
"append",
"(",
"index",
")",
"stack",
"=",
"stack",
"[",
":",
"-",
"1",
"]",
"return",
"order"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
run_population
|
Change save and load paths for obtained population, save config.json with model config,
run population via current python executor (with which evolve.py already run)
and on given devices (-1 means CPU, other integeres - visible for evolve.py GPUs)
Args:
population: list of dictionaries - configs of current population
evolution: ParamsEvolution
gpus: list of given devices (list of integers)
Returns:
None
|
deeppavlov/evolve.py
|
def run_population(population, evolution, gpus):
"""
Change save and load paths for obtained population, save config.json with model config,
run population via current python executor (with which evolve.py already run)
and on given devices (-1 means CPU, other integeres - visible for evolve.py GPUs)
Args:
population: list of dictionaries - configs of current population
evolution: ParamsEvolution
gpus: list of given devices (list of integers)
Returns:
None
"""
population_size = len(population)
for k in range(population_size // len(gpus) + 1):
procs = []
for j in range(len(gpus)):
i = k * len(gpus) + j
if i < population_size:
save_path = expand_path(
evolution.get_value_from_config(parse_config(population[i]),
evolution.path_to_models_save_path))
save_path.mkdir(parents=True, exist_ok=True)
f_name = save_path / "config.json"
save_json(population[i], f_name)
with save_path.joinpath('out.txt').open('w', encoding='utf8') as outlog,\
save_path.joinpath('err.txt').open('w', encoding='utf8') as errlog:
env = dict(os.environ)
if len(gpus) > 1 or gpus[0] != -1:
env['CUDA_VISIBLE_DEVICES'] = str(gpus[j])
procs.append(Popen("{} -m deeppavlov train {}".format(sys.executable, str(f_name)),
shell=True, stdout=outlog, stderr=errlog, env=env))
for j, proc in enumerate(procs):
i = k * len(gpus) + j
log.info(f'Waiting on {i}th proc')
if proc.wait() != 0:
save_path = expand_path(
evolution.get_value_from_config(parse_config(population[i]),
evolution.path_to_models_save_path))
with save_path.joinpath('err.txt').open(encoding='utf8') as errlog:
log.warning(f'Population {i} returned an error code {proc.returncode} and an error log:\n' +
errlog.read())
return None
|
def run_population(population, evolution, gpus):
"""
Change save and load paths for obtained population, save config.json with model config,
run population via current python executor (with which evolve.py already run)
and on given devices (-1 means CPU, other integeres - visible for evolve.py GPUs)
Args:
population: list of dictionaries - configs of current population
evolution: ParamsEvolution
gpus: list of given devices (list of integers)
Returns:
None
"""
population_size = len(population)
for k in range(population_size // len(gpus) + 1):
procs = []
for j in range(len(gpus)):
i = k * len(gpus) + j
if i < population_size:
save_path = expand_path(
evolution.get_value_from_config(parse_config(population[i]),
evolution.path_to_models_save_path))
save_path.mkdir(parents=True, exist_ok=True)
f_name = save_path / "config.json"
save_json(population[i], f_name)
with save_path.joinpath('out.txt').open('w', encoding='utf8') as outlog,\
save_path.joinpath('err.txt').open('w', encoding='utf8') as errlog:
env = dict(os.environ)
if len(gpus) > 1 or gpus[0] != -1:
env['CUDA_VISIBLE_DEVICES'] = str(gpus[j])
procs.append(Popen("{} -m deeppavlov train {}".format(sys.executable, str(f_name)),
shell=True, stdout=outlog, stderr=errlog, env=env))
for j, proc in enumerate(procs):
i = k * len(gpus) + j
log.info(f'Waiting on {i}th proc')
if proc.wait() != 0:
save_path = expand_path(
evolution.get_value_from_config(parse_config(population[i]),
evolution.path_to_models_save_path))
with save_path.joinpath('err.txt').open(encoding='utf8') as errlog:
log.warning(f'Population {i} returned an error code {proc.returncode} and an error log:\n' +
errlog.read())
return None
|
[
"Change",
"save",
"and",
"load",
"paths",
"for",
"obtained",
"population",
"save",
"config",
".",
"json",
"with",
"model",
"config",
"run",
"population",
"via",
"current",
"python",
"executor",
"(",
"with",
"which",
"evolve",
".",
"py",
"already",
"run",
")",
"and",
"on",
"given",
"devices",
"(",
"-",
"1",
"means",
"CPU",
"other",
"integeres",
"-",
"visible",
"for",
"evolve",
".",
"py",
"GPUs",
")",
"Args",
":",
"population",
":",
"list",
"of",
"dictionaries",
"-",
"configs",
"of",
"current",
"population",
"evolution",
":",
"ParamsEvolution",
"gpus",
":",
"list",
"of",
"given",
"devices",
"(",
"list",
"of",
"integers",
")"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/evolve.py#L173-L218
|
[
"def",
"run_population",
"(",
"population",
",",
"evolution",
",",
"gpus",
")",
":",
"population_size",
"=",
"len",
"(",
"population",
")",
"for",
"k",
"in",
"range",
"(",
"population_size",
"//",
"len",
"(",
"gpus",
")",
"+",
"1",
")",
":",
"procs",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"gpus",
")",
")",
":",
"i",
"=",
"k",
"*",
"len",
"(",
"gpus",
")",
"+",
"j",
"if",
"i",
"<",
"population_size",
":",
"save_path",
"=",
"expand_path",
"(",
"evolution",
".",
"get_value_from_config",
"(",
"parse_config",
"(",
"population",
"[",
"i",
"]",
")",
",",
"evolution",
".",
"path_to_models_save_path",
")",
")",
"save_path",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"f_name",
"=",
"save_path",
"/",
"\"config.json\"",
"save_json",
"(",
"population",
"[",
"i",
"]",
",",
"f_name",
")",
"with",
"save_path",
".",
"joinpath",
"(",
"'out.txt'",
")",
".",
"open",
"(",
"'w'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"outlog",
",",
"save_path",
".",
"joinpath",
"(",
"'err.txt'",
")",
".",
"open",
"(",
"'w'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"errlog",
":",
"env",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"if",
"len",
"(",
"gpus",
")",
">",
"1",
"or",
"gpus",
"[",
"0",
"]",
"!=",
"-",
"1",
":",
"env",
"[",
"'CUDA_VISIBLE_DEVICES'",
"]",
"=",
"str",
"(",
"gpus",
"[",
"j",
"]",
")",
"procs",
".",
"append",
"(",
"Popen",
"(",
"\"{} -m deeppavlov train {}\"",
".",
"format",
"(",
"sys",
".",
"executable",
",",
"str",
"(",
"f_name",
")",
")",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"outlog",
",",
"stderr",
"=",
"errlog",
",",
"env",
"=",
"env",
")",
")",
"for",
"j",
",",
"proc",
"in",
"enumerate",
"(",
"procs",
")",
":",
"i",
"=",
"k",
"*",
"len",
"(",
"gpus",
")",
"+",
"j",
"log",
".",
"info",
"(",
"f'Waiting on {i}th proc'",
")",
"if",
"proc",
".",
"wait",
"(",
")",
"!=",
"0",
":",
"save_path",
"=",
"expand_path",
"(",
"evolution",
".",
"get_value_from_config",
"(",
"parse_config",
"(",
"population",
"[",
"i",
"]",
")",
",",
"evolution",
".",
"path_to_models_save_path",
")",
")",
"with",
"save_path",
".",
"joinpath",
"(",
"'err.txt'",
")",
".",
"open",
"(",
"encoding",
"=",
"'utf8'",
")",
"as",
"errlog",
":",
"log",
".",
"warning",
"(",
"f'Population {i} returned an error code {proc.returncode} and an error log:\\n'",
"+",
"errlog",
".",
"read",
"(",
")",
")",
"return",
"None"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
dot_attention
|
Computes attention vector for each item in inputs:
attention vector is a weighted sum of memory items.
Dot product between input and memory vector is used as similarity measure.
Gate mechanism is applied to attention vectors to produce output.
Args:
inputs: Tensor [batch_size x input_len x feature_size]
memory: Tensor [batch_size x memory_len x feature_size]
mask: inputs mask
att_size: hidden size of attention
keep_prob: dropout keep_prob
scope:
Returns:
attention vectors [batch_size x input_len x (feature_size + feature_size)]
|
deeppavlov/models/squad/utils.py
|
def dot_attention(inputs, memory, mask, att_size, keep_prob=1.0, scope="dot_attention"):
"""Computes attention vector for each item in inputs:
attention vector is a weighted sum of memory items.
Dot product between input and memory vector is used as similarity measure.
Gate mechanism is applied to attention vectors to produce output.
Args:
inputs: Tensor [batch_size x input_len x feature_size]
memory: Tensor [batch_size x memory_len x feature_size]
mask: inputs mask
att_size: hidden size of attention
keep_prob: dropout keep_prob
scope:
Returns:
attention vectors [batch_size x input_len x (feature_size + feature_size)]
"""
with tf.variable_scope(scope):
BS, IL, IH = tf.unstack(tf.shape(inputs))
BS, ML, MH = tf.unstack(tf.shape(memory))
d_inputs = tf.nn.dropout(inputs, keep_prob=keep_prob, noise_shape=[BS, 1, IH])
d_memory = tf.nn.dropout(memory, keep_prob=keep_prob, noise_shape=[BS, 1, MH])
with tf.variable_scope("attention"):
inputs_att = tf.layers.dense(d_inputs, att_size, use_bias=False, activation=tf.nn.relu)
memory_att = tf.layers.dense(d_memory, att_size, use_bias=False, activation=tf.nn.relu)
logits = tf.matmul(inputs_att, tf.transpose(memory_att, [0, 2, 1])) / (att_size ** 0.5)
mask = tf.tile(tf.expand_dims(mask, axis=1), [1, IL, 1])
att_weights = tf.nn.softmax(softmax_mask(logits, mask))
outputs = tf.matmul(att_weights, memory)
res = tf.concat([inputs, outputs], axis=2)
with tf.variable_scope("gate"):
dim = res.get_shape().as_list()[-1]
d_res = tf.nn.dropout(res, keep_prob=keep_prob, noise_shape=[BS, 1, IH + MH])
gate = tf.layers.dense(d_res, dim, use_bias=False, activation=tf.nn.sigmoid)
return res * gate
|
def dot_attention(inputs, memory, mask, att_size, keep_prob=1.0, scope="dot_attention"):
"""Computes attention vector for each item in inputs:
attention vector is a weighted sum of memory items.
Dot product between input and memory vector is used as similarity measure.
Gate mechanism is applied to attention vectors to produce output.
Args:
inputs: Tensor [batch_size x input_len x feature_size]
memory: Tensor [batch_size x memory_len x feature_size]
mask: inputs mask
att_size: hidden size of attention
keep_prob: dropout keep_prob
scope:
Returns:
attention vectors [batch_size x input_len x (feature_size + feature_size)]
"""
with tf.variable_scope(scope):
BS, IL, IH = tf.unstack(tf.shape(inputs))
BS, ML, MH = tf.unstack(tf.shape(memory))
d_inputs = tf.nn.dropout(inputs, keep_prob=keep_prob, noise_shape=[BS, 1, IH])
d_memory = tf.nn.dropout(memory, keep_prob=keep_prob, noise_shape=[BS, 1, MH])
with tf.variable_scope("attention"):
inputs_att = tf.layers.dense(d_inputs, att_size, use_bias=False, activation=tf.nn.relu)
memory_att = tf.layers.dense(d_memory, att_size, use_bias=False, activation=tf.nn.relu)
logits = tf.matmul(inputs_att, tf.transpose(memory_att, [0, 2, 1])) / (att_size ** 0.5)
mask = tf.tile(tf.expand_dims(mask, axis=1), [1, IL, 1])
att_weights = tf.nn.softmax(softmax_mask(logits, mask))
outputs = tf.matmul(att_weights, memory)
res = tf.concat([inputs, outputs], axis=2)
with tf.variable_scope("gate"):
dim = res.get_shape().as_list()[-1]
d_res = tf.nn.dropout(res, keep_prob=keep_prob, noise_shape=[BS, 1, IH + MH])
gate = tf.layers.dense(d_res, dim, use_bias=False, activation=tf.nn.sigmoid)
return res * gate
|
[
"Computes",
"attention",
"vector",
"for",
"each",
"item",
"in",
"inputs",
":",
"attention",
"vector",
"is",
"a",
"weighted",
"sum",
"of",
"memory",
"items",
".",
"Dot",
"product",
"between",
"input",
"and",
"memory",
"vector",
"is",
"used",
"as",
"similarity",
"measure",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/squad/utils.py#L144-L183
|
[
"def",
"dot_attention",
"(",
"inputs",
",",
"memory",
",",
"mask",
",",
"att_size",
",",
"keep_prob",
"=",
"1.0",
",",
"scope",
"=",
"\"dot_attention\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
")",
":",
"BS",
",",
"IL",
",",
"IH",
"=",
"tf",
".",
"unstack",
"(",
"tf",
".",
"shape",
"(",
"inputs",
")",
")",
"BS",
",",
"ML",
",",
"MH",
"=",
"tf",
".",
"unstack",
"(",
"tf",
".",
"shape",
"(",
"memory",
")",
")",
"d_inputs",
"=",
"tf",
".",
"nn",
".",
"dropout",
"(",
"inputs",
",",
"keep_prob",
"=",
"keep_prob",
",",
"noise_shape",
"=",
"[",
"BS",
",",
"1",
",",
"IH",
"]",
")",
"d_memory",
"=",
"tf",
".",
"nn",
".",
"dropout",
"(",
"memory",
",",
"keep_prob",
"=",
"keep_prob",
",",
"noise_shape",
"=",
"[",
"BS",
",",
"1",
",",
"MH",
"]",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"\"attention\"",
")",
":",
"inputs_att",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"d_inputs",
",",
"att_size",
",",
"use_bias",
"=",
"False",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"memory_att",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"d_memory",
",",
"att_size",
",",
"use_bias",
"=",
"False",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"relu",
")",
"logits",
"=",
"tf",
".",
"matmul",
"(",
"inputs_att",
",",
"tf",
".",
"transpose",
"(",
"memory_att",
",",
"[",
"0",
",",
"2",
",",
"1",
"]",
")",
")",
"/",
"(",
"att_size",
"**",
"0.5",
")",
"mask",
"=",
"tf",
".",
"tile",
"(",
"tf",
".",
"expand_dims",
"(",
"mask",
",",
"axis",
"=",
"1",
")",
",",
"[",
"1",
",",
"IL",
",",
"1",
"]",
")",
"att_weights",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"softmax_mask",
"(",
"logits",
",",
"mask",
")",
")",
"outputs",
"=",
"tf",
".",
"matmul",
"(",
"att_weights",
",",
"memory",
")",
"res",
"=",
"tf",
".",
"concat",
"(",
"[",
"inputs",
",",
"outputs",
"]",
",",
"axis",
"=",
"2",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"\"gate\"",
")",
":",
"dim",
"=",
"res",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"-",
"1",
"]",
"d_res",
"=",
"tf",
".",
"nn",
".",
"dropout",
"(",
"res",
",",
"keep_prob",
"=",
"keep_prob",
",",
"noise_shape",
"=",
"[",
"BS",
",",
"1",
",",
"IH",
"+",
"MH",
"]",
")",
"gate",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"d_res",
",",
"dim",
",",
"use_bias",
"=",
"False",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"sigmoid",
")",
"return",
"res",
"*",
"gate"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
simple_attention
|
Simple attention without any conditions.
Computes weighted sum of memory elements.
|
deeppavlov/models/squad/utils.py
|
def simple_attention(memory, att_size, mask, keep_prob=1.0, scope="simple_attention"):
"""Simple attention without any conditions.
Computes weighted sum of memory elements.
"""
with tf.variable_scope(scope):
BS, ML, MH = tf.unstack(tf.shape(memory))
memory_do = tf.nn.dropout(memory, keep_prob=keep_prob, noise_shape=[BS, 1, MH])
logits = tf.layers.dense(tf.layers.dense(memory_do, att_size, activation=tf.nn.tanh), 1, use_bias=False)
logits = softmax_mask(tf.squeeze(logits, [2]), mask)
att_weights = tf.expand_dims(tf.nn.softmax(logits), axis=2)
res = tf.reduce_sum(att_weights * memory, axis=1)
return res
|
def simple_attention(memory, att_size, mask, keep_prob=1.0, scope="simple_attention"):
"""Simple attention without any conditions.
Computes weighted sum of memory elements.
"""
with tf.variable_scope(scope):
BS, ML, MH = tf.unstack(tf.shape(memory))
memory_do = tf.nn.dropout(memory, keep_prob=keep_prob, noise_shape=[BS, 1, MH])
logits = tf.layers.dense(tf.layers.dense(memory_do, att_size, activation=tf.nn.tanh), 1, use_bias=False)
logits = softmax_mask(tf.squeeze(logits, [2]), mask)
att_weights = tf.expand_dims(tf.nn.softmax(logits), axis=2)
res = tf.reduce_sum(att_weights * memory, axis=1)
return res
|
[
"Simple",
"attention",
"without",
"any",
"conditions",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/squad/utils.py#L186-L198
|
[
"def",
"simple_attention",
"(",
"memory",
",",
"att_size",
",",
"mask",
",",
"keep_prob",
"=",
"1.0",
",",
"scope",
"=",
"\"simple_attention\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
")",
":",
"BS",
",",
"ML",
",",
"MH",
"=",
"tf",
".",
"unstack",
"(",
"tf",
".",
"shape",
"(",
"memory",
")",
")",
"memory_do",
"=",
"tf",
".",
"nn",
".",
"dropout",
"(",
"memory",
",",
"keep_prob",
"=",
"keep_prob",
",",
"noise_shape",
"=",
"[",
"BS",
",",
"1",
",",
"MH",
"]",
")",
"logits",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"tf",
".",
"layers",
".",
"dense",
"(",
"memory_do",
",",
"att_size",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"tanh",
")",
",",
"1",
",",
"use_bias",
"=",
"False",
")",
"logits",
"=",
"softmax_mask",
"(",
"tf",
".",
"squeeze",
"(",
"logits",
",",
"[",
"2",
"]",
")",
",",
"mask",
")",
"att_weights",
"=",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"nn",
".",
"softmax",
"(",
"logits",
")",
",",
"axis",
"=",
"2",
")",
"res",
"=",
"tf",
".",
"reduce_sum",
"(",
"att_weights",
"*",
"memory",
",",
"axis",
"=",
"1",
")",
"return",
"res"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
attention
|
Computes weighted sum of inputs conditioned on state
|
deeppavlov/models/squad/utils.py
|
def attention(inputs, state, att_size, mask, scope="attention"):
"""Computes weighted sum of inputs conditioned on state"""
with tf.variable_scope(scope):
u = tf.concat([tf.tile(tf.expand_dims(state, axis=1), [1, tf.shape(inputs)[1], 1]), inputs], axis=2)
logits = tf.layers.dense(tf.layers.dense(u, att_size, activation=tf.nn.tanh), 1, use_bias=False)
logits = softmax_mask(tf.squeeze(logits, [2]), mask)
att_weights = tf.expand_dims(tf.nn.softmax(logits), axis=2)
res = tf.reduce_sum(att_weights * inputs, axis=1)
return res, logits
|
def attention(inputs, state, att_size, mask, scope="attention"):
"""Computes weighted sum of inputs conditioned on state"""
with tf.variable_scope(scope):
u = tf.concat([tf.tile(tf.expand_dims(state, axis=1), [1, tf.shape(inputs)[1], 1]), inputs], axis=2)
logits = tf.layers.dense(tf.layers.dense(u, att_size, activation=tf.nn.tanh), 1, use_bias=False)
logits = softmax_mask(tf.squeeze(logits, [2]), mask)
att_weights = tf.expand_dims(tf.nn.softmax(logits), axis=2)
res = tf.reduce_sum(att_weights * inputs, axis=1)
return res, logits
|
[
"Computes",
"weighted",
"sum",
"of",
"inputs",
"conditioned",
"on",
"state"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/squad/utils.py#L201-L209
|
[
"def",
"attention",
"(",
"inputs",
",",
"state",
",",
"att_size",
",",
"mask",
",",
"scope",
"=",
"\"attention\"",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"scope",
")",
":",
"u",
"=",
"tf",
".",
"concat",
"(",
"[",
"tf",
".",
"tile",
"(",
"tf",
".",
"expand_dims",
"(",
"state",
",",
"axis",
"=",
"1",
")",
",",
"[",
"1",
",",
"tf",
".",
"shape",
"(",
"inputs",
")",
"[",
"1",
"]",
",",
"1",
"]",
")",
",",
"inputs",
"]",
",",
"axis",
"=",
"2",
")",
"logits",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"tf",
".",
"layers",
".",
"dense",
"(",
"u",
",",
"att_size",
",",
"activation",
"=",
"tf",
".",
"nn",
".",
"tanh",
")",
",",
"1",
",",
"use_bias",
"=",
"False",
")",
"logits",
"=",
"softmax_mask",
"(",
"tf",
".",
"squeeze",
"(",
"logits",
",",
"[",
"2",
"]",
")",
",",
"mask",
")",
"att_weights",
"=",
"tf",
".",
"expand_dims",
"(",
"tf",
".",
"nn",
".",
"softmax",
"(",
"logits",
")",
",",
"axis",
"=",
"2",
")",
"res",
"=",
"tf",
".",
"reduce_sum",
"(",
"att_weights",
"*",
"inputs",
",",
"axis",
"=",
"1",
")",
"return",
"res",
",",
"logits"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
compute_bleu
|
Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of lists of references for each translation. Each
reference should be tokenized into a list of tokens.
translation_corpus: list of translations to score. Each translation
should be tokenized into a list of tokens.
max_order: Maximum n-gram order to use when computing BLEU score.
smooth: Whether or not to apply Lin et al. 2004 smoothing.
Returns:
3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram
precisions and brevity penalty.
|
deeppavlov/metrics/google_bleu.py
|
def compute_bleu(reference_corpus, translation_corpus, max_order=4,
smooth=False):
"""Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of lists of references for each translation. Each
reference should be tokenized into a list of tokens.
translation_corpus: list of translations to score. Each translation
should be tokenized into a list of tokens.
max_order: Maximum n-gram order to use when computing BLEU score.
smooth: Whether or not to apply Lin et al. 2004 smoothing.
Returns:
3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram
precisions and brevity penalty.
"""
matches_by_order = [0] * max_order
possible_matches_by_order = [0] * max_order
reference_length = 0
translation_length = 0
for (references, translation) in zip(reference_corpus,
translation_corpus):
reference_length += min(len(r) for r in references)
translation_length += len(translation)
merged_ref_ngram_counts = collections.Counter()
for reference in references:
merged_ref_ngram_counts |= _get_ngrams(reference, max_order)
translation_ngram_counts = _get_ngrams(translation, max_order)
overlap = translation_ngram_counts & merged_ref_ngram_counts
for ngram in overlap:
matches_by_order[len(ngram)-1] += overlap[ngram]
for order in range(1, max_order+1):
possible_matches = len(translation) - order + 1
if possible_matches > 0:
possible_matches_by_order[order-1] += possible_matches
precisions = [0] * max_order
for i in range(0, max_order):
if smooth:
precisions[i] = ((matches_by_order[i] + 1.) /
(possible_matches_by_order[i] + 1.))
else:
if possible_matches_by_order[i] > 0:
precisions[i] = (float(matches_by_order[i]) /
possible_matches_by_order[i])
else:
precisions[i] = 0.0
if min(precisions) > 0:
p_log_sum = sum((1. / max_order) * math.log(p) for p in precisions)
geo_mean = math.exp(p_log_sum)
else:
geo_mean = 0
ratio = float(translation_length) / reference_length
if ratio > 1.0:
bp = 1.
else:
bp = math.exp(1 - 1. / ratio)
bleu = geo_mean * bp
return (bleu, precisions, bp, ratio, translation_length, reference_length)
|
def compute_bleu(reference_corpus, translation_corpus, max_order=4,
smooth=False):
"""Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of lists of references for each translation. Each
reference should be tokenized into a list of tokens.
translation_corpus: list of translations to score. Each translation
should be tokenized into a list of tokens.
max_order: Maximum n-gram order to use when computing BLEU score.
smooth: Whether or not to apply Lin et al. 2004 smoothing.
Returns:
3-Tuple with the BLEU score, n-gram precisions, geometric mean of n-gram
precisions and brevity penalty.
"""
matches_by_order = [0] * max_order
possible_matches_by_order = [0] * max_order
reference_length = 0
translation_length = 0
for (references, translation) in zip(reference_corpus,
translation_corpus):
reference_length += min(len(r) for r in references)
translation_length += len(translation)
merged_ref_ngram_counts = collections.Counter()
for reference in references:
merged_ref_ngram_counts |= _get_ngrams(reference, max_order)
translation_ngram_counts = _get_ngrams(translation, max_order)
overlap = translation_ngram_counts & merged_ref_ngram_counts
for ngram in overlap:
matches_by_order[len(ngram)-1] += overlap[ngram]
for order in range(1, max_order+1):
possible_matches = len(translation) - order + 1
if possible_matches > 0:
possible_matches_by_order[order-1] += possible_matches
precisions = [0] * max_order
for i in range(0, max_order):
if smooth:
precisions[i] = ((matches_by_order[i] + 1.) /
(possible_matches_by_order[i] + 1.))
else:
if possible_matches_by_order[i] > 0:
precisions[i] = (float(matches_by_order[i]) /
possible_matches_by_order[i])
else:
precisions[i] = 0.0
if min(precisions) > 0:
p_log_sum = sum((1. / max_order) * math.log(p) for p in precisions)
geo_mean = math.exp(p_log_sum)
else:
geo_mean = 0
ratio = float(translation_length) / reference_length
if ratio > 1.0:
bp = 1.
else:
bp = math.exp(1 - 1. / ratio)
bleu = geo_mean * bp
return (bleu, precisions, bp, ratio, translation_length, reference_length)
|
[
"Computes",
"BLEU",
"score",
"of",
"translated",
"segments",
"against",
"one",
"or",
"more",
"references",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/google_bleu.py#L48-L112
|
[
"def",
"compute_bleu",
"(",
"reference_corpus",
",",
"translation_corpus",
",",
"max_order",
"=",
"4",
",",
"smooth",
"=",
"False",
")",
":",
"matches_by_order",
"=",
"[",
"0",
"]",
"*",
"max_order",
"possible_matches_by_order",
"=",
"[",
"0",
"]",
"*",
"max_order",
"reference_length",
"=",
"0",
"translation_length",
"=",
"0",
"for",
"(",
"references",
",",
"translation",
")",
"in",
"zip",
"(",
"reference_corpus",
",",
"translation_corpus",
")",
":",
"reference_length",
"+=",
"min",
"(",
"len",
"(",
"r",
")",
"for",
"r",
"in",
"references",
")",
"translation_length",
"+=",
"len",
"(",
"translation",
")",
"merged_ref_ngram_counts",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"reference",
"in",
"references",
":",
"merged_ref_ngram_counts",
"|=",
"_get_ngrams",
"(",
"reference",
",",
"max_order",
")",
"translation_ngram_counts",
"=",
"_get_ngrams",
"(",
"translation",
",",
"max_order",
")",
"overlap",
"=",
"translation_ngram_counts",
"&",
"merged_ref_ngram_counts",
"for",
"ngram",
"in",
"overlap",
":",
"matches_by_order",
"[",
"len",
"(",
"ngram",
")",
"-",
"1",
"]",
"+=",
"overlap",
"[",
"ngram",
"]",
"for",
"order",
"in",
"range",
"(",
"1",
",",
"max_order",
"+",
"1",
")",
":",
"possible_matches",
"=",
"len",
"(",
"translation",
")",
"-",
"order",
"+",
"1",
"if",
"possible_matches",
">",
"0",
":",
"possible_matches_by_order",
"[",
"order",
"-",
"1",
"]",
"+=",
"possible_matches",
"precisions",
"=",
"[",
"0",
"]",
"*",
"max_order",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"max_order",
")",
":",
"if",
"smooth",
":",
"precisions",
"[",
"i",
"]",
"=",
"(",
"(",
"matches_by_order",
"[",
"i",
"]",
"+",
"1.",
")",
"/",
"(",
"possible_matches_by_order",
"[",
"i",
"]",
"+",
"1.",
")",
")",
"else",
":",
"if",
"possible_matches_by_order",
"[",
"i",
"]",
">",
"0",
":",
"precisions",
"[",
"i",
"]",
"=",
"(",
"float",
"(",
"matches_by_order",
"[",
"i",
"]",
")",
"/",
"possible_matches_by_order",
"[",
"i",
"]",
")",
"else",
":",
"precisions",
"[",
"i",
"]",
"=",
"0.0",
"if",
"min",
"(",
"precisions",
")",
">",
"0",
":",
"p_log_sum",
"=",
"sum",
"(",
"(",
"1.",
"/",
"max_order",
")",
"*",
"math",
".",
"log",
"(",
"p",
")",
"for",
"p",
"in",
"precisions",
")",
"geo_mean",
"=",
"math",
".",
"exp",
"(",
"p_log_sum",
")",
"else",
":",
"geo_mean",
"=",
"0",
"ratio",
"=",
"float",
"(",
"translation_length",
")",
"/",
"reference_length",
"if",
"ratio",
">",
"1.0",
":",
"bp",
"=",
"1.",
"else",
":",
"bp",
"=",
"math",
".",
"exp",
"(",
"1",
"-",
"1.",
"/",
"ratio",
")",
"bleu",
"=",
"geo_mean",
"*",
"bp",
"return",
"(",
"bleu",
",",
"precisions",
",",
"bp",
",",
"ratio",
",",
"translation_length",
",",
"reference_length",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
DialogLogger._get_log_file
|
Returns opened file object for writing dialog logs.
Returns:
log_file: opened Python file object.
|
deeppavlov/core/agent/dialog_logger.py
|
def _get_log_file(self):
"""Returns opened file object for writing dialog logs.
Returns:
log_file: opened Python file object.
"""
log_dir: Path = Path(self.config['log_path']).expanduser().resolve() / self.agent_name
log_dir.mkdir(parents=True, exist_ok=True)
log_file_path = Path(log_dir, f'{self._get_timestamp_utc_str()}_{self.agent_name}.log')
log_file = open(log_file_path, 'a', buffering=1, encoding='utf8')
return log_file
|
def _get_log_file(self):
"""Returns opened file object for writing dialog logs.
Returns:
log_file: opened Python file object.
"""
log_dir: Path = Path(self.config['log_path']).expanduser().resolve() / self.agent_name
log_dir.mkdir(parents=True, exist_ok=True)
log_file_path = Path(log_dir, f'{self._get_timestamp_utc_str()}_{self.agent_name}.log')
log_file = open(log_file_path, 'a', buffering=1, encoding='utf8')
return log_file
|
[
"Returns",
"opened",
"file",
"object",
"for",
"writing",
"dialog",
"logs",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/agent/dialog_logger.py#L66-L76
|
[
"def",
"_get_log_file",
"(",
"self",
")",
":",
"log_dir",
":",
"Path",
"=",
"Path",
"(",
"self",
".",
"config",
"[",
"'log_path'",
"]",
")",
".",
"expanduser",
"(",
")",
".",
"resolve",
"(",
")",
"/",
"self",
".",
"agent_name",
"log_dir",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"log_file_path",
"=",
"Path",
"(",
"log_dir",
",",
"f'{self._get_timestamp_utc_str()}_{self.agent_name}.log'",
")",
"log_file",
"=",
"open",
"(",
"log_file_path",
",",
"'a'",
",",
"buffering",
"=",
"1",
",",
"encoding",
"=",
"'utf8'",
")",
"return",
"log_file"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
DialogLogger._log
|
Logs single dialog utterance to current dialog log file.
Args:
utterance: Dialog utterance.
direction: 'in' or 'out' utterance direction.
dialog_id: Dialog ID.
|
deeppavlov/core/agent/dialog_logger.py
|
def _log(self, utterance: Any, direction: str, dialog_id: Optional[Hashable]=None):
"""Logs single dialog utterance to current dialog log file.
Args:
utterance: Dialog utterance.
direction: 'in' or 'out' utterance direction.
dialog_id: Dialog ID.
"""
if isinstance(utterance, str):
pass
elif isinstance(utterance, RichMessage):
utterance = utterance.json()
elif isinstance(utterance, (list, dict)):
utterance = jsonify_data(utterance)
else:
utterance = str(utterance)
dialog_id = str(dialog_id) if not isinstance(dialog_id, str) else dialog_id
if self.log_file.tell() >= self.log_max_size * 1024:
self.log_file.close()
self.log_file = self._get_log_file()
else:
try:
log_msg = {}
log_msg['timestamp'] = self._get_timestamp_utc_str()
log_msg['dialog_id'] = dialog_id
log_msg['direction'] = direction
log_msg['message'] = utterance
log_str = json.dumps(log_msg, ensure_ascii=self.config['ensure_ascii'])
self.log_file.write(f'{log_str}\n')
except IOError:
log.error('Failed to write dialog log.')
|
def _log(self, utterance: Any, direction: str, dialog_id: Optional[Hashable]=None):
"""Logs single dialog utterance to current dialog log file.
Args:
utterance: Dialog utterance.
direction: 'in' or 'out' utterance direction.
dialog_id: Dialog ID.
"""
if isinstance(utterance, str):
pass
elif isinstance(utterance, RichMessage):
utterance = utterance.json()
elif isinstance(utterance, (list, dict)):
utterance = jsonify_data(utterance)
else:
utterance = str(utterance)
dialog_id = str(dialog_id) if not isinstance(dialog_id, str) else dialog_id
if self.log_file.tell() >= self.log_max_size * 1024:
self.log_file.close()
self.log_file = self._get_log_file()
else:
try:
log_msg = {}
log_msg['timestamp'] = self._get_timestamp_utc_str()
log_msg['dialog_id'] = dialog_id
log_msg['direction'] = direction
log_msg['message'] = utterance
log_str = json.dumps(log_msg, ensure_ascii=self.config['ensure_ascii'])
self.log_file.write(f'{log_str}\n')
except IOError:
log.error('Failed to write dialog log.')
|
[
"Logs",
"single",
"dialog",
"utterance",
"to",
"current",
"dialog",
"log",
"file",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/agent/dialog_logger.py#L78-L110
|
[
"def",
"_log",
"(",
"self",
",",
"utterance",
":",
"Any",
",",
"direction",
":",
"str",
",",
"dialog_id",
":",
"Optional",
"[",
"Hashable",
"]",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"utterance",
",",
"str",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"utterance",
",",
"RichMessage",
")",
":",
"utterance",
"=",
"utterance",
".",
"json",
"(",
")",
"elif",
"isinstance",
"(",
"utterance",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"utterance",
"=",
"jsonify_data",
"(",
"utterance",
")",
"else",
":",
"utterance",
"=",
"str",
"(",
"utterance",
")",
"dialog_id",
"=",
"str",
"(",
"dialog_id",
")",
"if",
"not",
"isinstance",
"(",
"dialog_id",
",",
"str",
")",
"else",
"dialog_id",
"if",
"self",
".",
"log_file",
".",
"tell",
"(",
")",
">=",
"self",
".",
"log_max_size",
"*",
"1024",
":",
"self",
".",
"log_file",
".",
"close",
"(",
")",
"self",
".",
"log_file",
"=",
"self",
".",
"_get_log_file",
"(",
")",
"else",
":",
"try",
":",
"log_msg",
"=",
"{",
"}",
"log_msg",
"[",
"'timestamp'",
"]",
"=",
"self",
".",
"_get_timestamp_utc_str",
"(",
")",
"log_msg",
"[",
"'dialog_id'",
"]",
"=",
"dialog_id",
"log_msg",
"[",
"'direction'",
"]",
"=",
"direction",
"log_msg",
"[",
"'message'",
"]",
"=",
"utterance",
"log_str",
"=",
"json",
".",
"dumps",
"(",
"log_msg",
",",
"ensure_ascii",
"=",
"self",
".",
"config",
"[",
"'ensure_ascii'",
"]",
")",
"self",
".",
"log_file",
".",
"write",
"(",
"f'{log_str}\\n'",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"'Failed to write dialog log.'",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
DialogLogger.log_in
|
Wraps _log method for all input utterances.
Args:
utterance: Dialog utterance.
dialog_id: Dialog ID.
|
deeppavlov/core/agent/dialog_logger.py
|
def log_in(self, utterance: Any, dialog_id: Optional[Hashable] = None) -> None:
"""Wraps _log method for all input utterances.
Args:
utterance: Dialog utterance.
dialog_id: Dialog ID.
"""
if self.enabled:
self._log(utterance, 'in', dialog_id)
|
def log_in(self, utterance: Any, dialog_id: Optional[Hashable] = None) -> None:
"""Wraps _log method for all input utterances.
Args:
utterance: Dialog utterance.
dialog_id: Dialog ID.
"""
if self.enabled:
self._log(utterance, 'in', dialog_id)
|
[
"Wraps",
"_log",
"method",
"for",
"all",
"input",
"utterances",
".",
"Args",
":",
"utterance",
":",
"Dialog",
"utterance",
".",
"dialog_id",
":",
"Dialog",
"ID",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/agent/dialog_logger.py#L112-L119
|
[
"def",
"log_in",
"(",
"self",
",",
"utterance",
":",
"Any",
",",
"dialog_id",
":",
"Optional",
"[",
"Hashable",
"]",
"=",
"None",
")",
"->",
"None",
":",
"if",
"self",
".",
"enabled",
":",
"self",
".",
"_log",
"(",
"utterance",
",",
"'in'",
",",
"dialog_id",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
summary_gradient_updates
|
get summary ops for the magnitude of gradient updates
|
deeppavlov/models/elmo/train_utils.py
|
def summary_gradient_updates(grads, opt, lr):
"""get summary ops for the magnitude of gradient updates"""
# strategy:
# make a dict of variable name -> [variable, grad, adagrad slot]
vars_grads = {}
for v in tf.trainable_variables():
vars_grads[v.name] = [v, None, None]
for g, v in grads:
vars_grads[v.name][1] = g
vars_grads[v.name][2] = opt.get_slot(v, 'accumulator')
# now make summaries
ret = []
for vname, (v, g, a) in vars_grads.items():
if g is None:
continue
if isinstance(g, tf.IndexedSlices):
# a sparse gradient - only take norm of params that are updated
updates = lr * g.values
if a is not None:
updates /= tf.sqrt(tf.gather(a, g.indices))
else:
updates = lr * g
if a is not None:
updates /= tf.sqrt(a)
values_norm = tf.sqrt(tf.reduce_sum(v * v)) + 1.0e-7
updates_norm = tf.sqrt(tf.reduce_sum(updates * updates))
ret.append(tf.summary.scalar('UPDATE/' + vname.replace(":", "_"), updates_norm / values_norm))
return ret
|
def summary_gradient_updates(grads, opt, lr):
"""get summary ops for the magnitude of gradient updates"""
# strategy:
# make a dict of variable name -> [variable, grad, adagrad slot]
vars_grads = {}
for v in tf.trainable_variables():
vars_grads[v.name] = [v, None, None]
for g, v in grads:
vars_grads[v.name][1] = g
vars_grads[v.name][2] = opt.get_slot(v, 'accumulator')
# now make summaries
ret = []
for vname, (v, g, a) in vars_grads.items():
if g is None:
continue
if isinstance(g, tf.IndexedSlices):
# a sparse gradient - only take norm of params that are updated
updates = lr * g.values
if a is not None:
updates /= tf.sqrt(tf.gather(a, g.indices))
else:
updates = lr * g
if a is not None:
updates /= tf.sqrt(a)
values_norm = tf.sqrt(tf.reduce_sum(v * v)) + 1.0e-7
updates_norm = tf.sqrt(tf.reduce_sum(updates * updates))
ret.append(tf.summary.scalar('UPDATE/' + vname.replace(":", "_"), updates_norm / values_norm))
return ret
|
[
"get",
"summary",
"ops",
"for",
"the",
"magnitude",
"of",
"gradient",
"updates"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/train_utils.py#L84-L117
|
[
"def",
"summary_gradient_updates",
"(",
"grads",
",",
"opt",
",",
"lr",
")",
":",
"# strategy:",
"# make a dict of variable name -> [variable, grad, adagrad slot]",
"vars_grads",
"=",
"{",
"}",
"for",
"v",
"in",
"tf",
".",
"trainable_variables",
"(",
")",
":",
"vars_grads",
"[",
"v",
".",
"name",
"]",
"=",
"[",
"v",
",",
"None",
",",
"None",
"]",
"for",
"g",
",",
"v",
"in",
"grads",
":",
"vars_grads",
"[",
"v",
".",
"name",
"]",
"[",
"1",
"]",
"=",
"g",
"vars_grads",
"[",
"v",
".",
"name",
"]",
"[",
"2",
"]",
"=",
"opt",
".",
"get_slot",
"(",
"v",
",",
"'accumulator'",
")",
"# now make summaries",
"ret",
"=",
"[",
"]",
"for",
"vname",
",",
"(",
"v",
",",
"g",
",",
"a",
")",
"in",
"vars_grads",
".",
"items",
"(",
")",
":",
"if",
"g",
"is",
"None",
":",
"continue",
"if",
"isinstance",
"(",
"g",
",",
"tf",
".",
"IndexedSlices",
")",
":",
"# a sparse gradient - only take norm of params that are updated",
"updates",
"=",
"lr",
"*",
"g",
".",
"values",
"if",
"a",
"is",
"not",
"None",
":",
"updates",
"/=",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"gather",
"(",
"a",
",",
"g",
".",
"indices",
")",
")",
"else",
":",
"updates",
"=",
"lr",
"*",
"g",
"if",
"a",
"is",
"not",
"None",
":",
"updates",
"/=",
"tf",
".",
"sqrt",
"(",
"a",
")",
"values_norm",
"=",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"reduce_sum",
"(",
"v",
"*",
"v",
")",
")",
"+",
"1.0e-7",
"updates_norm",
"=",
"tf",
".",
"sqrt",
"(",
"tf",
".",
"reduce_sum",
"(",
"updates",
"*",
"updates",
")",
")",
"ret",
".",
"append",
"(",
"tf",
".",
"summary",
".",
"scalar",
"(",
"'UPDATE/'",
"+",
"vname",
".",
"replace",
"(",
"\":\"",
",",
"\"_\"",
")",
",",
"updates_norm",
"/",
"values_norm",
")",
")",
"return",
"ret"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
_deduplicate_indexed_slices
|
Sums `values` associated with any non-unique `indices`.
Args:
values: A `Tensor` with rank >= 1.
indices: A one-dimensional integer `Tensor`, indexing into the first
dimension of `values` (as in an IndexedSlices object).
Returns:
A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a
de-duplicated version of `indices` and `summed_values` contains the sum of
`values` slices associated with each unique index.
|
deeppavlov/models/elmo/train_utils.py
|
def _deduplicate_indexed_slices(values, indices):
"""Sums `values` associated with any non-unique `indices`.
Args:
values: A `Tensor` with rank >= 1.
indices: A one-dimensional integer `Tensor`, indexing into the first
dimension of `values` (as in an IndexedSlices object).
Returns:
A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a
de-duplicated version of `indices` and `summed_values` contains the sum of
`values` slices associated with each unique index.
"""
unique_indices, new_index_positions = tf.unique(indices)
summed_values = tf.unsorted_segment_sum(values,
new_index_positions,
tf.shape(unique_indices)[0])
return (summed_values, unique_indices)
|
def _deduplicate_indexed_slices(values, indices):
"""Sums `values` associated with any non-unique `indices`.
Args:
values: A `Tensor` with rank >= 1.
indices: A one-dimensional integer `Tensor`, indexing into the first
dimension of `values` (as in an IndexedSlices object).
Returns:
A tuple of (`summed_values`, `unique_indices`) where `unique_indices` is a
de-duplicated version of `indices` and `summed_values` contains the sum of
`values` slices associated with each unique index.
"""
unique_indices, new_index_positions = tf.unique(indices)
summed_values = tf.unsorted_segment_sum(values,
new_index_positions,
tf.shape(unique_indices)[0])
return (summed_values, unique_indices)
|
[
"Sums",
"values",
"associated",
"with",
"any",
"non",
"-",
"unique",
"indices",
".",
"Args",
":",
"values",
":",
"A",
"Tensor",
"with",
"rank",
">",
"=",
"1",
".",
"indices",
":",
"A",
"one",
"-",
"dimensional",
"integer",
"Tensor",
"indexing",
"into",
"the",
"first",
"dimension",
"of",
"values",
"(",
"as",
"in",
"an",
"IndexedSlices",
"object",
")",
".",
"Returns",
":",
"A",
"tuple",
"of",
"(",
"summed_values",
"unique_indices",
")",
"where",
"unique_indices",
"is",
"a",
"de",
"-",
"duplicated",
"version",
"of",
"indices",
"and",
"summed_values",
"contains",
"the",
"sum",
"of",
"values",
"slices",
"associated",
"with",
"each",
"unique",
"index",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/train_utils.py#L120-L135
|
[
"def",
"_deduplicate_indexed_slices",
"(",
"values",
",",
"indices",
")",
":",
"unique_indices",
",",
"new_index_positions",
"=",
"tf",
".",
"unique",
"(",
"indices",
")",
"summed_values",
"=",
"tf",
".",
"unsorted_segment_sum",
"(",
"values",
",",
"new_index_positions",
",",
"tf",
".",
"shape",
"(",
"unique_indices",
")",
"[",
"0",
"]",
")",
"return",
"(",
"summed_values",
",",
"unique_indices",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
dump_weights
|
Dump the trained weights from a model to a HDF5 file.
|
deeppavlov/models/elmo/train_utils.py
|
def dump_weights(tf_save_dir, outfile, options):
"""
Dump the trained weights from a model to a HDF5 file.
"""
def _get_outname(tf_name):
outname = re.sub(':0$', '', tf_name)
outname = outname.lstrip('lm/')
outname = re.sub('/rnn/', '/RNN/', outname)
outname = re.sub('/multi_rnn_cell/', '/MultiRNNCell/', outname)
outname = re.sub('/cell_', '/Cell', outname)
outname = re.sub('/lstm_cell/', '/LSTMCell/', outname)
if '/RNN/' in outname:
if 'projection' in outname:
outname = re.sub('projection/kernel', 'W_P_0', outname)
else:
outname = re.sub('/kernel', '/W_0', outname)
outname = re.sub('/bias', '/B', outname)
return outname
ckpt_file = tf.train.latest_checkpoint(tf_save_dir)
config = tf.ConfigProto(allow_soft_placement=True)
with tf.Graph().as_default():
with tf.Session(config=config) as sess:
with tf.variable_scope('lm'):
LanguageModel(options, False) # Create graph
# we use the "Saver" class to load the variables
loader = tf.train.Saver()
loader.restore(sess, ckpt_file)
with h5py.File(outfile, 'w') as fout:
for v in tf.trainable_variables():
if v.name.find('softmax') >= 0:
# don't dump these
continue
outname = _get_outname(v.name)
# print("Saving variable {0} with name {1}".format(
# v.name, outname))
shape = v.get_shape().as_list()
dset = fout.create_dataset(outname, shape, dtype='float32')
values = sess.run([v])[0]
dset[...] = values
|
def dump_weights(tf_save_dir, outfile, options):
"""
Dump the trained weights from a model to a HDF5 file.
"""
def _get_outname(tf_name):
outname = re.sub(':0$', '', tf_name)
outname = outname.lstrip('lm/')
outname = re.sub('/rnn/', '/RNN/', outname)
outname = re.sub('/multi_rnn_cell/', '/MultiRNNCell/', outname)
outname = re.sub('/cell_', '/Cell', outname)
outname = re.sub('/lstm_cell/', '/LSTMCell/', outname)
if '/RNN/' in outname:
if 'projection' in outname:
outname = re.sub('projection/kernel', 'W_P_0', outname)
else:
outname = re.sub('/kernel', '/W_0', outname)
outname = re.sub('/bias', '/B', outname)
return outname
ckpt_file = tf.train.latest_checkpoint(tf_save_dir)
config = tf.ConfigProto(allow_soft_placement=True)
with tf.Graph().as_default():
with tf.Session(config=config) as sess:
with tf.variable_scope('lm'):
LanguageModel(options, False) # Create graph
# we use the "Saver" class to load the variables
loader = tf.train.Saver()
loader.restore(sess, ckpt_file)
with h5py.File(outfile, 'w') as fout:
for v in tf.trainable_variables():
if v.name.find('softmax') >= 0:
# don't dump these
continue
outname = _get_outname(v.name)
# print("Saving variable {0} with name {1}".format(
# v.name, outname))
shape = v.get_shape().as_list()
dset = fout.create_dataset(outname, shape, dtype='float32')
values = sess.run([v])[0]
dset[...] = values
|
[
"Dump",
"the",
"trained",
"weights",
"from",
"a",
"model",
"to",
"a",
"HDF5",
"file",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/elmo/train_utils.py#L202-L244
|
[
"def",
"dump_weights",
"(",
"tf_save_dir",
",",
"outfile",
",",
"options",
")",
":",
"def",
"_get_outname",
"(",
"tf_name",
")",
":",
"outname",
"=",
"re",
".",
"sub",
"(",
"':0$'",
",",
"''",
",",
"tf_name",
")",
"outname",
"=",
"outname",
".",
"lstrip",
"(",
"'lm/'",
")",
"outname",
"=",
"re",
".",
"sub",
"(",
"'/rnn/'",
",",
"'/RNN/'",
",",
"outname",
")",
"outname",
"=",
"re",
".",
"sub",
"(",
"'/multi_rnn_cell/'",
",",
"'/MultiRNNCell/'",
",",
"outname",
")",
"outname",
"=",
"re",
".",
"sub",
"(",
"'/cell_'",
",",
"'/Cell'",
",",
"outname",
")",
"outname",
"=",
"re",
".",
"sub",
"(",
"'/lstm_cell/'",
",",
"'/LSTMCell/'",
",",
"outname",
")",
"if",
"'/RNN/'",
"in",
"outname",
":",
"if",
"'projection'",
"in",
"outname",
":",
"outname",
"=",
"re",
".",
"sub",
"(",
"'projection/kernel'",
",",
"'W_P_0'",
",",
"outname",
")",
"else",
":",
"outname",
"=",
"re",
".",
"sub",
"(",
"'/kernel'",
",",
"'/W_0'",
",",
"outname",
")",
"outname",
"=",
"re",
".",
"sub",
"(",
"'/bias'",
",",
"'/B'",
",",
"outname",
")",
"return",
"outname",
"ckpt_file",
"=",
"tf",
".",
"train",
".",
"latest_checkpoint",
"(",
"tf_save_dir",
")",
"config",
"=",
"tf",
".",
"ConfigProto",
"(",
"allow_soft_placement",
"=",
"True",
")",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"with",
"tf",
".",
"Session",
"(",
"config",
"=",
"config",
")",
"as",
"sess",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"'lm'",
")",
":",
"LanguageModel",
"(",
"options",
",",
"False",
")",
"# Create graph",
"# we use the \"Saver\" class to load the variables",
"loader",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"loader",
".",
"restore",
"(",
"sess",
",",
"ckpt_file",
")",
"with",
"h5py",
".",
"File",
"(",
"outfile",
",",
"'w'",
")",
"as",
"fout",
":",
"for",
"v",
"in",
"tf",
".",
"trainable_variables",
"(",
")",
":",
"if",
"v",
".",
"name",
".",
"find",
"(",
"'softmax'",
")",
">=",
"0",
":",
"# don't dump these",
"continue",
"outname",
"=",
"_get_outname",
"(",
"v",
".",
"name",
")",
"# print(\"Saving variable {0} with name {1}\".format(",
"# v.name, outname))",
"shape",
"=",
"v",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"dset",
"=",
"fout",
".",
"create_dataset",
"(",
"outname",
",",
"shape",
",",
"dtype",
"=",
"'float32'",
")",
"values",
"=",
"sess",
".",
"run",
"(",
"[",
"v",
"]",
")",
"[",
"0",
"]",
"dset",
"[",
"...",
"]",
"=",
"values"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
read_data_by_config
|
Read data by dataset_reader from specified config.
|
deeppavlov/core/commands/train.py
|
def read_data_by_config(config: dict):
"""Read data by dataset_reader from specified config."""
dataset_config = config.get('dataset', None)
if dataset_config:
config.pop('dataset')
ds_type = dataset_config['type']
if ds_type == 'classification':
reader = {'class_name': 'basic_classification_reader'}
iterator = {'class_name': 'basic_classification_iterator'}
config['dataset_reader'] = {**dataset_config, **reader}
config['dataset_iterator'] = {**dataset_config, **iterator}
else:
raise Exception("Unsupported dataset type: {}".format(ds_type))
try:
reader_config = dict(config['dataset_reader'])
except KeyError:
raise ConfigError("No dataset reader is provided in the JSON config.")
reader = get_model(reader_config.pop('class_name'))()
data_path = reader_config.pop('data_path', '')
if isinstance(data_path, list):
data_path = [expand_path(x) for x in data_path]
else:
data_path = expand_path(data_path)
return reader.read(data_path, **reader_config)
|
def read_data_by_config(config: dict):
"""Read data by dataset_reader from specified config."""
dataset_config = config.get('dataset', None)
if dataset_config:
config.pop('dataset')
ds_type = dataset_config['type']
if ds_type == 'classification':
reader = {'class_name': 'basic_classification_reader'}
iterator = {'class_name': 'basic_classification_iterator'}
config['dataset_reader'] = {**dataset_config, **reader}
config['dataset_iterator'] = {**dataset_config, **iterator}
else:
raise Exception("Unsupported dataset type: {}".format(ds_type))
try:
reader_config = dict(config['dataset_reader'])
except KeyError:
raise ConfigError("No dataset reader is provided in the JSON config.")
reader = get_model(reader_config.pop('class_name'))()
data_path = reader_config.pop('data_path', '')
if isinstance(data_path, list):
data_path = [expand_path(x) for x in data_path]
else:
data_path = expand_path(data_path)
return reader.read(data_path, **reader_config)
|
[
"Read",
"data",
"by",
"dataset_reader",
"from",
"specified",
"config",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/commands/train.py#L31-L58
|
[
"def",
"read_data_by_config",
"(",
"config",
":",
"dict",
")",
":",
"dataset_config",
"=",
"config",
".",
"get",
"(",
"'dataset'",
",",
"None",
")",
"if",
"dataset_config",
":",
"config",
".",
"pop",
"(",
"'dataset'",
")",
"ds_type",
"=",
"dataset_config",
"[",
"'type'",
"]",
"if",
"ds_type",
"==",
"'classification'",
":",
"reader",
"=",
"{",
"'class_name'",
":",
"'basic_classification_reader'",
"}",
"iterator",
"=",
"{",
"'class_name'",
":",
"'basic_classification_iterator'",
"}",
"config",
"[",
"'dataset_reader'",
"]",
"=",
"{",
"*",
"*",
"dataset_config",
",",
"*",
"*",
"reader",
"}",
"config",
"[",
"'dataset_iterator'",
"]",
"=",
"{",
"*",
"*",
"dataset_config",
",",
"*",
"*",
"iterator",
"}",
"else",
":",
"raise",
"Exception",
"(",
"\"Unsupported dataset type: {}\"",
".",
"format",
"(",
"ds_type",
")",
")",
"try",
":",
"reader_config",
"=",
"dict",
"(",
"config",
"[",
"'dataset_reader'",
"]",
")",
"except",
"KeyError",
":",
"raise",
"ConfigError",
"(",
"\"No dataset reader is provided in the JSON config.\"",
")",
"reader",
"=",
"get_model",
"(",
"reader_config",
".",
"pop",
"(",
"'class_name'",
")",
")",
"(",
")",
"data_path",
"=",
"reader_config",
".",
"pop",
"(",
"'data_path'",
",",
"''",
")",
"if",
"isinstance",
"(",
"data_path",
",",
"list",
")",
":",
"data_path",
"=",
"[",
"expand_path",
"(",
"x",
")",
"for",
"x",
"in",
"data_path",
"]",
"else",
":",
"data_path",
"=",
"expand_path",
"(",
"data_path",
")",
"return",
"reader",
".",
"read",
"(",
"data_path",
",",
"*",
"*",
"reader_config",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
get_iterator_from_config
|
Create iterator (from config) for specified data.
|
deeppavlov/core/commands/train.py
|
def get_iterator_from_config(config: dict, data: dict):
"""Create iterator (from config) for specified data."""
iterator_config = config['dataset_iterator']
iterator: Union[DataLearningIterator, DataFittingIterator] = from_params(iterator_config,
data=data)
return iterator
|
def get_iterator_from_config(config: dict, data: dict):
"""Create iterator (from config) for specified data."""
iterator_config = config['dataset_iterator']
iterator: Union[DataLearningIterator, DataFittingIterator] = from_params(iterator_config,
data=data)
return iterator
|
[
"Create",
"iterator",
"(",
"from",
"config",
")",
"for",
"specified",
"data",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/commands/train.py#L61-L66
|
[
"def",
"get_iterator_from_config",
"(",
"config",
":",
"dict",
",",
"data",
":",
"dict",
")",
":",
"iterator_config",
"=",
"config",
"[",
"'dataset_iterator'",
"]",
"iterator",
":",
"Union",
"[",
"DataLearningIterator",
",",
"DataFittingIterator",
"]",
"=",
"from_params",
"(",
"iterator_config",
",",
"data",
"=",
"data",
")",
"return",
"iterator"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
train_evaluate_model_from_config
|
Make training and evaluation of the model described in corresponding configuration file.
|
deeppavlov/core/commands/train.py
|
def train_evaluate_model_from_config(config: Union[str, Path, dict],
iterator: Union[DataLearningIterator, DataFittingIterator] = None, *,
to_train: bool = True,
evaluation_targets: Optional[Iterable[str]] = None,
to_validate: Optional[bool] = None,
download: bool = False,
start_epoch_num: Optional[int] = None,
recursive: bool = False) -> Dict[str, Dict[str, float]]:
"""Make training and evaluation of the model described in corresponding configuration file."""
config = parse_config(config)
if download:
deep_download(config)
if to_train and recursive:
for subconfig in get_all_elems_from_json(config['chainer'], 'config_path'):
log.info(f'Training "{subconfig}"')
train_evaluate_model_from_config(subconfig, download=False, recursive=True)
import_packages(config.get('metadata', {}).get('imports', []))
if iterator is None:
try:
data = read_data_by_config(config)
except ConfigError as e:
to_train = False
log.warning(f'Skipping training. {e.message}')
else:
iterator = get_iterator_from_config(config, data)
if 'train' not in config:
log.warning('Train config is missing. Populating with default values')
train_config = config.get('train')
if start_epoch_num is not None:
train_config['start_epoch_num'] = start_epoch_num
if 'evaluation_targets' not in train_config and ('validate_best' in train_config
or 'test_best' in train_config):
log.warning('"validate_best" and "test_best" parameters are deprecated.'
' Please, use "evaluation_targets" list instead')
train_config['evaluation_targets'] = []
if train_config.pop('validate_best', True):
train_config['evaluation_targets'].append('valid')
if train_config.pop('test_best', True):
train_config['evaluation_targets'].append('test')
trainer_class = get_model(train_config.pop('class_name', 'nn_trainer'))
trainer = trainer_class(config['chainer'], **train_config)
if to_train:
trainer.train(iterator)
res = {}
if iterator is not None:
if to_validate is not None:
if evaluation_targets is None:
log.warning('"to_validate" parameter is deprecated and will be removed in future versions.'
' Please, use "evaluation_targets" list instead')
evaluation_targets = ['test']
if to_validate:
evaluation_targets.append('valid')
else:
log.warn('Both "evaluation_targets" and "to_validate" parameters are specified.'
' "to_validate" is deprecated and will be ignored')
res = trainer.evaluate(iterator, evaluation_targets, print_reports=True)
trainer.get_chainer().destroy()
res = {k: v['metrics'] for k, v in res.items()}
return res
|
def train_evaluate_model_from_config(config: Union[str, Path, dict],
iterator: Union[DataLearningIterator, DataFittingIterator] = None, *,
to_train: bool = True,
evaluation_targets: Optional[Iterable[str]] = None,
to_validate: Optional[bool] = None,
download: bool = False,
start_epoch_num: Optional[int] = None,
recursive: bool = False) -> Dict[str, Dict[str, float]]:
"""Make training and evaluation of the model described in corresponding configuration file."""
config = parse_config(config)
if download:
deep_download(config)
if to_train and recursive:
for subconfig in get_all_elems_from_json(config['chainer'], 'config_path'):
log.info(f'Training "{subconfig}"')
train_evaluate_model_from_config(subconfig, download=False, recursive=True)
import_packages(config.get('metadata', {}).get('imports', []))
if iterator is None:
try:
data = read_data_by_config(config)
except ConfigError as e:
to_train = False
log.warning(f'Skipping training. {e.message}')
else:
iterator = get_iterator_from_config(config, data)
if 'train' not in config:
log.warning('Train config is missing. Populating with default values')
train_config = config.get('train')
if start_epoch_num is not None:
train_config['start_epoch_num'] = start_epoch_num
if 'evaluation_targets' not in train_config and ('validate_best' in train_config
or 'test_best' in train_config):
log.warning('"validate_best" and "test_best" parameters are deprecated.'
' Please, use "evaluation_targets" list instead')
train_config['evaluation_targets'] = []
if train_config.pop('validate_best', True):
train_config['evaluation_targets'].append('valid')
if train_config.pop('test_best', True):
train_config['evaluation_targets'].append('test')
trainer_class = get_model(train_config.pop('class_name', 'nn_trainer'))
trainer = trainer_class(config['chainer'], **train_config)
if to_train:
trainer.train(iterator)
res = {}
if iterator is not None:
if to_validate is not None:
if evaluation_targets is None:
log.warning('"to_validate" parameter is deprecated and will be removed in future versions.'
' Please, use "evaluation_targets" list instead')
evaluation_targets = ['test']
if to_validate:
evaluation_targets.append('valid')
else:
log.warn('Both "evaluation_targets" and "to_validate" parameters are specified.'
' "to_validate" is deprecated and will be ignored')
res = trainer.evaluate(iterator, evaluation_targets, print_reports=True)
trainer.get_chainer().destroy()
res = {k: v['metrics'] for k, v in res.items()}
return res
|
[
"Make",
"training",
"and",
"evaluation",
"of",
"the",
"model",
"described",
"in",
"corresponding",
"configuration",
"file",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/commands/train.py#L69-L142
|
[
"def",
"train_evaluate_model_from_config",
"(",
"config",
":",
"Union",
"[",
"str",
",",
"Path",
",",
"dict",
"]",
",",
"iterator",
":",
"Union",
"[",
"DataLearningIterator",
",",
"DataFittingIterator",
"]",
"=",
"None",
",",
"*",
",",
"to_train",
":",
"bool",
"=",
"True",
",",
"evaluation_targets",
":",
"Optional",
"[",
"Iterable",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"to_validate",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
",",
"download",
":",
"bool",
"=",
"False",
",",
"start_epoch_num",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"recursive",
":",
"bool",
"=",
"False",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"float",
"]",
"]",
":",
"config",
"=",
"parse_config",
"(",
"config",
")",
"if",
"download",
":",
"deep_download",
"(",
"config",
")",
"if",
"to_train",
"and",
"recursive",
":",
"for",
"subconfig",
"in",
"get_all_elems_from_json",
"(",
"config",
"[",
"'chainer'",
"]",
",",
"'config_path'",
")",
":",
"log",
".",
"info",
"(",
"f'Training \"{subconfig}\"'",
")",
"train_evaluate_model_from_config",
"(",
"subconfig",
",",
"download",
"=",
"False",
",",
"recursive",
"=",
"True",
")",
"import_packages",
"(",
"config",
".",
"get",
"(",
"'metadata'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'imports'",
",",
"[",
"]",
")",
")",
"if",
"iterator",
"is",
"None",
":",
"try",
":",
"data",
"=",
"read_data_by_config",
"(",
"config",
")",
"except",
"ConfigError",
"as",
"e",
":",
"to_train",
"=",
"False",
"log",
".",
"warning",
"(",
"f'Skipping training. {e.message}'",
")",
"else",
":",
"iterator",
"=",
"get_iterator_from_config",
"(",
"config",
",",
"data",
")",
"if",
"'train'",
"not",
"in",
"config",
":",
"log",
".",
"warning",
"(",
"'Train config is missing. Populating with default values'",
")",
"train_config",
"=",
"config",
".",
"get",
"(",
"'train'",
")",
"if",
"start_epoch_num",
"is",
"not",
"None",
":",
"train_config",
"[",
"'start_epoch_num'",
"]",
"=",
"start_epoch_num",
"if",
"'evaluation_targets'",
"not",
"in",
"train_config",
"and",
"(",
"'validate_best'",
"in",
"train_config",
"or",
"'test_best'",
"in",
"train_config",
")",
":",
"log",
".",
"warning",
"(",
"'\"validate_best\" and \"test_best\" parameters are deprecated.'",
"' Please, use \"evaluation_targets\" list instead'",
")",
"train_config",
"[",
"'evaluation_targets'",
"]",
"=",
"[",
"]",
"if",
"train_config",
".",
"pop",
"(",
"'validate_best'",
",",
"True",
")",
":",
"train_config",
"[",
"'evaluation_targets'",
"]",
".",
"append",
"(",
"'valid'",
")",
"if",
"train_config",
".",
"pop",
"(",
"'test_best'",
",",
"True",
")",
":",
"train_config",
"[",
"'evaluation_targets'",
"]",
".",
"append",
"(",
"'test'",
")",
"trainer_class",
"=",
"get_model",
"(",
"train_config",
".",
"pop",
"(",
"'class_name'",
",",
"'nn_trainer'",
")",
")",
"trainer",
"=",
"trainer_class",
"(",
"config",
"[",
"'chainer'",
"]",
",",
"*",
"*",
"train_config",
")",
"if",
"to_train",
":",
"trainer",
".",
"train",
"(",
"iterator",
")",
"res",
"=",
"{",
"}",
"if",
"iterator",
"is",
"not",
"None",
":",
"if",
"to_validate",
"is",
"not",
"None",
":",
"if",
"evaluation_targets",
"is",
"None",
":",
"log",
".",
"warning",
"(",
"'\"to_validate\" parameter is deprecated and will be removed in future versions.'",
"' Please, use \"evaluation_targets\" list instead'",
")",
"evaluation_targets",
"=",
"[",
"'test'",
"]",
"if",
"to_validate",
":",
"evaluation_targets",
".",
"append",
"(",
"'valid'",
")",
"else",
":",
"log",
".",
"warn",
"(",
"'Both \"evaluation_targets\" and \"to_validate\" parameters are specified.'",
"' \"to_validate\" is deprecated and will be ignored'",
")",
"res",
"=",
"trainer",
".",
"evaluate",
"(",
"iterator",
",",
"evaluation_targets",
",",
"print_reports",
"=",
"True",
")",
"trainer",
".",
"get_chainer",
"(",
")",
".",
"destroy",
"(",
")",
"res",
"=",
"{",
"k",
":",
"v",
"[",
"'metrics'",
"]",
"for",
"k",
",",
"v",
"in",
"res",
".",
"items",
"(",
")",
"}",
"return",
"res"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
interact_alice
|
Exchange messages between basic pipelines and the Yandex.Dialogs service.
If the pipeline returns multiple values, only the first one is forwarded to Yandex.
|
deeppavlov/utils/alice/alice.py
|
def interact_alice(agent: Agent):
"""
Exchange messages between basic pipelines and the Yandex.Dialogs service.
If the pipeline returns multiple values, only the first one is forwarded to Yandex.
"""
data = request.get_json()
text = data['request'].get('command', '').strip()
payload = data['request'].get('payload')
session_id = data['session']['session_id']
user_id = data['session']['user_id']
message_id = data['session']['message_id']
dialog_id = DialogID(user_id, session_id)
response = {
'response': {
'end_session': True,
'text': ''
},
"session": {
'session_id': session_id,
'message_id': message_id,
'user_id': user_id
},
'version': '1.0'
}
agent_response: Union[str, RichMessage] = agent([payload or text], [dialog_id])[0]
if isinstance(agent_response, RichMessage):
response['response']['text'] = '\n'.join([j['content']
for j in agent_response.json()
if j['type'] == 'plain_text'])
else:
response['response']['text'] = str(agent_response)
return jsonify(response), 200
|
def interact_alice(agent: Agent):
"""
Exchange messages between basic pipelines and the Yandex.Dialogs service.
If the pipeline returns multiple values, only the first one is forwarded to Yandex.
"""
data = request.get_json()
text = data['request'].get('command', '').strip()
payload = data['request'].get('payload')
session_id = data['session']['session_id']
user_id = data['session']['user_id']
message_id = data['session']['message_id']
dialog_id = DialogID(user_id, session_id)
response = {
'response': {
'end_session': True,
'text': ''
},
"session": {
'session_id': session_id,
'message_id': message_id,
'user_id': user_id
},
'version': '1.0'
}
agent_response: Union[str, RichMessage] = agent([payload or text], [dialog_id])[0]
if isinstance(agent_response, RichMessage):
response['response']['text'] = '\n'.join([j['content']
for j in agent_response.json()
if j['type'] == 'plain_text'])
else:
response['response']['text'] = str(agent_response)
return jsonify(response), 200
|
[
"Exchange",
"messages",
"between",
"basic",
"pipelines",
"and",
"the",
"Yandex",
".",
"Dialogs",
"service",
".",
"If",
"the",
"pipeline",
"returns",
"multiple",
"values",
"only",
"the",
"first",
"one",
"is",
"forwarded",
"to",
"Yandex",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/utils/alice/alice.py#L45-L81
|
[
"def",
"interact_alice",
"(",
"agent",
":",
"Agent",
")",
":",
"data",
"=",
"request",
".",
"get_json",
"(",
")",
"text",
"=",
"data",
"[",
"'request'",
"]",
".",
"get",
"(",
"'command'",
",",
"''",
")",
".",
"strip",
"(",
")",
"payload",
"=",
"data",
"[",
"'request'",
"]",
".",
"get",
"(",
"'payload'",
")",
"session_id",
"=",
"data",
"[",
"'session'",
"]",
"[",
"'session_id'",
"]",
"user_id",
"=",
"data",
"[",
"'session'",
"]",
"[",
"'user_id'",
"]",
"message_id",
"=",
"data",
"[",
"'session'",
"]",
"[",
"'message_id'",
"]",
"dialog_id",
"=",
"DialogID",
"(",
"user_id",
",",
"session_id",
")",
"response",
"=",
"{",
"'response'",
":",
"{",
"'end_session'",
":",
"True",
",",
"'text'",
":",
"''",
"}",
",",
"\"session\"",
":",
"{",
"'session_id'",
":",
"session_id",
",",
"'message_id'",
":",
"message_id",
",",
"'user_id'",
":",
"user_id",
"}",
",",
"'version'",
":",
"'1.0'",
"}",
"agent_response",
":",
"Union",
"[",
"str",
",",
"RichMessage",
"]",
"=",
"agent",
"(",
"[",
"payload",
"or",
"text",
"]",
",",
"[",
"dialog_id",
"]",
")",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"agent_response",
",",
"RichMessage",
")",
":",
"response",
"[",
"'response'",
"]",
"[",
"'text'",
"]",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"j",
"[",
"'content'",
"]",
"for",
"j",
"in",
"agent_response",
".",
"json",
"(",
")",
"if",
"j",
"[",
"'type'",
"]",
"==",
"'plain_text'",
"]",
")",
"else",
":",
"response",
"[",
"'response'",
"]",
"[",
"'text'",
"]",
"=",
"str",
"(",
"agent_response",
")",
"return",
"jsonify",
"(",
"response",
")",
",",
"200"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
labels2onehot
|
Convert labels to one-hot vectors for multi-class multi-label classification
Args:
labels: list of samples where each sample is a class or a list of classes which sample belongs with
classes: array of classes' names
Returns:
2d array with one-hot representation of given samples
|
deeppavlov/models/classifiers/utils.py
|
def labels2onehot(labels: [List[str], List[List[str]], np.ndarray], classes: [list, np.ndarray]) -> np.ndarray:
"""
Convert labels to one-hot vectors for multi-class multi-label classification
Args:
labels: list of samples where each sample is a class or a list of classes which sample belongs with
classes: array of classes' names
Returns:
2d array with one-hot representation of given samples
"""
n_classes = len(classes)
y = []
for sample in labels:
curr = np.zeros(n_classes)
if isinstance(sample, list):
for intent in sample:
if intent not in classes:
log.warning('Unknown intent {} detected. Assigning no class'.format(intent))
else:
curr[np.where(np.array(classes) == intent)[0]] = 1
else:
curr[np.where(np.array(classes) == sample)[0]] = 1
y.append(curr)
y = np.asarray(y)
return y
|
def labels2onehot(labels: [List[str], List[List[str]], np.ndarray], classes: [list, np.ndarray]) -> np.ndarray:
"""
Convert labels to one-hot vectors for multi-class multi-label classification
Args:
labels: list of samples where each sample is a class or a list of classes which sample belongs with
classes: array of classes' names
Returns:
2d array with one-hot representation of given samples
"""
n_classes = len(classes)
y = []
for sample in labels:
curr = np.zeros(n_classes)
if isinstance(sample, list):
for intent in sample:
if intent not in classes:
log.warning('Unknown intent {} detected. Assigning no class'.format(intent))
else:
curr[np.where(np.array(classes) == intent)[0]] = 1
else:
curr[np.where(np.array(classes) == sample)[0]] = 1
y.append(curr)
y = np.asarray(y)
return y
|
[
"Convert",
"labels",
"to",
"one",
"-",
"hot",
"vectors",
"for",
"multi",
"-",
"class",
"multi",
"-",
"label",
"classification"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/classifiers/utils.py#L24-L49
|
[
"def",
"labels2onehot",
"(",
"labels",
":",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"np",
".",
"ndarray",
"]",
",",
"classes",
":",
"[",
"list",
",",
"np",
".",
"ndarray",
"]",
")",
"->",
"np",
".",
"ndarray",
":",
"n_classes",
"=",
"len",
"(",
"classes",
")",
"y",
"=",
"[",
"]",
"for",
"sample",
"in",
"labels",
":",
"curr",
"=",
"np",
".",
"zeros",
"(",
"n_classes",
")",
"if",
"isinstance",
"(",
"sample",
",",
"list",
")",
":",
"for",
"intent",
"in",
"sample",
":",
"if",
"intent",
"not",
"in",
"classes",
":",
"log",
".",
"warning",
"(",
"'Unknown intent {} detected. Assigning no class'",
".",
"format",
"(",
"intent",
")",
")",
"else",
":",
"curr",
"[",
"np",
".",
"where",
"(",
"np",
".",
"array",
"(",
"classes",
")",
"==",
"intent",
")",
"[",
"0",
"]",
"]",
"=",
"1",
"else",
":",
"curr",
"[",
"np",
".",
"where",
"(",
"np",
".",
"array",
"(",
"classes",
")",
"==",
"sample",
")",
"[",
"0",
"]",
"]",
"=",
"1",
"y",
".",
"append",
"(",
"curr",
")",
"y",
"=",
"np",
".",
"asarray",
"(",
"y",
")",
"return",
"y"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
proba2labels
|
Convert vectors of probabilities to labels using confident threshold
(if probability to belong with the class is bigger than confident_threshold, sample belongs with the class;
if no probabilities bigger than confident threshold, sample belongs with the class with the biggest probability)
Args:
proba: list of samples where each sample is a vector of probabilities to belong with given classes
confident_threshold (float): boundary of probability to belong with a class
classes: array of classes' names
Returns:
list of lists of labels for each sample
|
deeppavlov/models/classifiers/utils.py
|
def proba2labels(proba: [list, np.ndarray], confident_threshold: float, classes: [list, np.ndarray]) -> List[List]:
"""
Convert vectors of probabilities to labels using confident threshold
(if probability to belong with the class is bigger than confident_threshold, sample belongs with the class;
if no probabilities bigger than confident threshold, sample belongs with the class with the biggest probability)
Args:
proba: list of samples where each sample is a vector of probabilities to belong with given classes
confident_threshold (float): boundary of probability to belong with a class
classes: array of classes' names
Returns:
list of lists of labels for each sample
"""
y = []
for sample in proba:
to_add = np.where(sample > confident_threshold)[0]
if len(to_add) > 0:
y.append(np.array(classes)[to_add].tolist())
else:
y.append(np.array([np.array(classes)[np.argmax(sample)]]).tolist())
return y
|
def proba2labels(proba: [list, np.ndarray], confident_threshold: float, classes: [list, np.ndarray]) -> List[List]:
"""
Convert vectors of probabilities to labels using confident threshold
(if probability to belong with the class is bigger than confident_threshold, sample belongs with the class;
if no probabilities bigger than confident threshold, sample belongs with the class with the biggest probability)
Args:
proba: list of samples where each sample is a vector of probabilities to belong with given classes
confident_threshold (float): boundary of probability to belong with a class
classes: array of classes' names
Returns:
list of lists of labels for each sample
"""
y = []
for sample in proba:
to_add = np.where(sample > confident_threshold)[0]
if len(to_add) > 0:
y.append(np.array(classes)[to_add].tolist())
else:
y.append(np.array([np.array(classes)[np.argmax(sample)]]).tolist())
return y
|
[
"Convert",
"vectors",
"of",
"probabilities",
"to",
"labels",
"using",
"confident",
"threshold",
"(",
"if",
"probability",
"to",
"belong",
"with",
"the",
"class",
"is",
"bigger",
"than",
"confident_threshold",
"sample",
"belongs",
"with",
"the",
"class",
";",
"if",
"no",
"probabilities",
"bigger",
"than",
"confident",
"threshold",
"sample",
"belongs",
"with",
"the",
"class",
"with",
"the",
"biggest",
"probability",
")"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/classifiers/utils.py#L52-L74
|
[
"def",
"proba2labels",
"(",
"proba",
":",
"[",
"list",
",",
"np",
".",
"ndarray",
"]",
",",
"confident_threshold",
":",
"float",
",",
"classes",
":",
"[",
"list",
",",
"np",
".",
"ndarray",
"]",
")",
"->",
"List",
"[",
"List",
"]",
":",
"y",
"=",
"[",
"]",
"for",
"sample",
"in",
"proba",
":",
"to_add",
"=",
"np",
".",
"where",
"(",
"sample",
">",
"confident_threshold",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"to_add",
")",
">",
"0",
":",
"y",
".",
"append",
"(",
"np",
".",
"array",
"(",
"classes",
")",
"[",
"to_add",
"]",
".",
"tolist",
"(",
")",
")",
"else",
":",
"y",
".",
"append",
"(",
"np",
".",
"array",
"(",
"[",
"np",
".",
"array",
"(",
"classes",
")",
"[",
"np",
".",
"argmax",
"(",
"sample",
")",
"]",
"]",
")",
".",
"tolist",
"(",
")",
")",
"return",
"y"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
proba2onehot
|
Convert vectors of probabilities to one-hot representations using confident threshold
Args:
proba: samples where each sample is a vector of probabilities to belong with given classes
confident_threshold: boundary of probability to belong with a class
classes: array of classes' names
Returns:
2d array with one-hot representation of given samples
|
deeppavlov/models/classifiers/utils.py
|
def proba2onehot(proba: [list, np.ndarray], confident_threshold: float, classes: [list, np.ndarray]) -> np.ndarray:
"""
Convert vectors of probabilities to one-hot representations using confident threshold
Args:
proba: samples where each sample is a vector of probabilities to belong with given classes
confident_threshold: boundary of probability to belong with a class
classes: array of classes' names
Returns:
2d array with one-hot representation of given samples
"""
return labels2onehot(proba2labels(proba, confident_threshold, classes), classes)
|
def proba2onehot(proba: [list, np.ndarray], confident_threshold: float, classes: [list, np.ndarray]) -> np.ndarray:
"""
Convert vectors of probabilities to one-hot representations using confident threshold
Args:
proba: samples where each sample is a vector of probabilities to belong with given classes
confident_threshold: boundary of probability to belong with a class
classes: array of classes' names
Returns:
2d array with one-hot representation of given samples
"""
return labels2onehot(proba2labels(proba, confident_threshold, classes), classes)
|
[
"Convert",
"vectors",
"of",
"probabilities",
"to",
"one",
"-",
"hot",
"representations",
"using",
"confident",
"threshold"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/classifiers/utils.py#L77-L89
|
[
"def",
"proba2onehot",
"(",
"proba",
":",
"[",
"list",
",",
"np",
".",
"ndarray",
"]",
",",
"confident_threshold",
":",
"float",
",",
"classes",
":",
"[",
"list",
",",
"np",
".",
"ndarray",
"]",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"labels2onehot",
"(",
"proba2labels",
"(",
"proba",
",",
"confident_threshold",
",",
"classes",
")",
",",
"classes",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
KerasModel._config_session
|
Configure session for particular device
Returns:
tensorflow.Session
|
deeppavlov/core/models/keras_model.py
|
def _config_session():
"""
Configure session for particular device
Returns:
tensorflow.Session
"""
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list = '0'
return tf.Session(config=config)
|
def _config_session():
"""
Configure session for particular device
Returns:
tensorflow.Session
"""
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list = '0'
return tf.Session(config=config)
|
[
"Configure",
"session",
"for",
"particular",
"device"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L61-L71
|
[
"def",
"_config_session",
"(",
")",
":",
"config",
"=",
"tf",
".",
"ConfigProto",
"(",
")",
"config",
".",
"gpu_options",
".",
"allow_growth",
"=",
"True",
"config",
".",
"gpu_options",
".",
"visible_device_list",
"=",
"'0'",
"return",
"tf",
".",
"Session",
"(",
"config",
"=",
"config",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
KerasModel.process_event
|
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None
|
deeppavlov/core/models/keras_model.py
|
def process_event(self, event_name: str, data: dict) -> None:
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None
"""
if event_name == "after_epoch":
self.epochs_done = data["epochs_done"]
self.batches_seen = data["batches_seen"]
self.train_examples_seen = data["train_examples_seen"]
return
|
def process_event(self, event_name: str, data: dict) -> None:
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None
"""
if event_name == "after_epoch":
self.epochs_done = data["epochs_done"]
self.batches_seen = data["batches_seen"]
self.train_examples_seen = data["train_examples_seen"]
return
|
[
"Process",
"event",
"after",
"epoch",
"Args",
":",
"event_name",
":",
"whether",
"event",
"is",
"send",
"after",
"epoch",
"or",
"batch",
".",
"Set",
"of",
"values",
":",
"after_epoch",
"after_batch",
"data",
":",
"event",
"data",
"(",
"dictionary",
")"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L81-L96
|
[
"def",
"process_event",
"(",
"self",
",",
"event_name",
":",
"str",
",",
"data",
":",
"dict",
")",
"->",
"None",
":",
"if",
"event_name",
"==",
"\"after_epoch\"",
":",
"self",
".",
"epochs_done",
"=",
"data",
"[",
"\"epochs_done\"",
"]",
"self",
".",
"batches_seen",
"=",
"data",
"[",
"\"batches_seen\"",
"]",
"self",
".",
"train_examples_seen",
"=",
"data",
"[",
"\"train_examples_seen\"",
"]",
"return"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
KerasWrapper.load
|
Checks existence of the model file, loads the model if the file exists
|
deeppavlov/core/models/keras_model.py
|
def load(self) -> None:
"""Checks existence of the model file, loads the model if the file exists"""
# Checks presence of the model files
if self.load_path.exists():
path = str(self.load_path.resolve())
log.info('[loading model from {}]'.format(path))
self._net.load(path)
|
def load(self) -> None:
"""Checks existence of the model file, loads the model if the file exists"""
# Checks presence of the model files
if self.load_path.exists():
path = str(self.load_path.resolve())
log.info('[loading model from {}]'.format(path))
self._net.load(path)
|
[
"Checks",
"existence",
"of",
"the",
"model",
"file",
"loads",
"the",
"model",
"if",
"the",
"file",
"exists"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L140-L147
|
[
"def",
"load",
"(",
"self",
")",
"->",
"None",
":",
"# Checks presence of the model files",
"if",
"self",
".",
"load_path",
".",
"exists",
"(",
")",
":",
"path",
"=",
"str",
"(",
"self",
".",
"load_path",
".",
"resolve",
"(",
")",
")",
"log",
".",
"info",
"(",
"'[loading model from {}]'",
".",
"format",
"(",
"path",
")",
")",
"self",
".",
"_net",
".",
"load",
"(",
"path",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
KerasWrapper.save
|
Saves model to the save_path, provided in config. The directory is
already created by super().__init__, which is called in __init__ of this class
|
deeppavlov/core/models/keras_model.py
|
def save(self) -> None:
"""Saves model to the save_path, provided in config. The directory is
already created by super().__init__, which is called in __init__ of this class"""
path = str(self.save_path.absolute())
log.info('[saving model to {}]'.format(path))
self._net.save(path)
|
def save(self) -> None:
"""Saves model to the save_path, provided in config. The directory is
already created by super().__init__, which is called in __init__ of this class"""
path = str(self.save_path.absolute())
log.info('[saving model to {}]'.format(path))
self._net.save(path)
|
[
"Saves",
"model",
"to",
"the",
"save_path",
"provided",
"in",
"config",
".",
"The",
"directory",
"is",
"already",
"created",
"by",
"super",
"()",
".",
"__init__",
"which",
"is",
"called",
"in",
"__init__",
"of",
"this",
"class"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L149-L154
|
[
"def",
"save",
"(",
"self",
")",
"->",
"None",
":",
"path",
"=",
"str",
"(",
"self",
".",
"save_path",
".",
"absolute",
"(",
")",
")",
"log",
".",
"info",
"(",
"'[saving model to {}]'",
".",
"format",
"(",
"path",
")",
")",
"self",
".",
"_net",
".",
"save",
"(",
"path",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
KerasWrapper.train_on_batch
|
Trains the model on a single batch.
Args:
*args: the list of network inputs.
Last element of `args` is the batch of targets,
all previous elements are training data batches
|
deeppavlov/core/models/keras_model.py
|
def train_on_batch(self, *args) -> None:
"""Trains the model on a single batch.
Args:
*args: the list of network inputs.
Last element of `args` is the batch of targets,
all previous elements are training data batches
"""
*data, labels = args
self._net.train_on_batch(data, labels)
|
def train_on_batch(self, *args) -> None:
"""Trains the model on a single batch.
Args:
*args: the list of network inputs.
Last element of `args` is the batch of targets,
all previous elements are training data batches
"""
*data, labels = args
self._net.train_on_batch(data, labels)
|
[
"Trains",
"the",
"model",
"on",
"a",
"single",
"batch",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L156-L165
|
[
"def",
"train_on_batch",
"(",
"self",
",",
"*",
"args",
")",
"->",
"None",
":",
"*",
"data",
",",
"labels",
"=",
"args",
"self",
".",
"_net",
".",
"train_on_batch",
"(",
"data",
",",
"labels",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
LRScheduledKerasModel.get_momentum_variable
|
Extract values of momentum variables from optimizer
Returns:
optimizer's `rho` or `beta_1`
|
deeppavlov/core/models/keras_model.py
|
def get_momentum_variable(self):
"""
Extract values of momentum variables from optimizer
Returns:
optimizer's `rho` or `beta_1`
"""
optimizer = self.get_optimizer()
if hasattr(optimizer, 'rho'):
return optimizer.rho
elif hasattr(optimizer, 'beta_1'):
return optimizer.beta_1
return None
|
def get_momentum_variable(self):
"""
Extract values of momentum variables from optimizer
Returns:
optimizer's `rho` or `beta_1`
"""
optimizer = self.get_optimizer()
if hasattr(optimizer, 'rho'):
return optimizer.rho
elif hasattr(optimizer, 'beta_1'):
return optimizer.beta_1
return None
|
[
"Extract",
"values",
"of",
"momentum",
"variables",
"from",
"optimizer"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L238-L250
|
[
"def",
"get_momentum_variable",
"(",
"self",
")",
":",
"optimizer",
"=",
"self",
".",
"get_optimizer",
"(",
")",
"if",
"hasattr",
"(",
"optimizer",
",",
"'rho'",
")",
":",
"return",
"optimizer",
".",
"rho",
"elif",
"hasattr",
"(",
"optimizer",
",",
"'beta_1'",
")",
":",
"return",
"optimizer",
".",
"beta_1",
"return",
"None"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
LRScheduledKerasModel._update_graph_variables
|
Update graph variables setting giving `learning_rate` and `momentum`
Args:
learning_rate: learning rate value to be set in graph (set if not None)
momentum: momentum value to be set in graph (set if not None)
Returns:
None
|
deeppavlov/core/models/keras_model.py
|
def _update_graph_variables(self, learning_rate: float = None, momentum: float = None):
"""
Update graph variables setting giving `learning_rate` and `momentum`
Args:
learning_rate: learning rate value to be set in graph (set if not None)
momentum: momentum value to be set in graph (set if not None)
Returns:
None
"""
if learning_rate is not None:
K.set_value(self.get_learning_rate_variable(), learning_rate)
# log.info(f"Learning rate = {learning_rate}")
if momentum is not None:
K.set_value(self.get_momentum_variable(), momentum)
|
def _update_graph_variables(self, learning_rate: float = None, momentum: float = None):
"""
Update graph variables setting giving `learning_rate` and `momentum`
Args:
learning_rate: learning rate value to be set in graph (set if not None)
momentum: momentum value to be set in graph (set if not None)
Returns:
None
"""
if learning_rate is not None:
K.set_value(self.get_learning_rate_variable(), learning_rate)
# log.info(f"Learning rate = {learning_rate}")
if momentum is not None:
K.set_value(self.get_momentum_variable(), momentum)
|
[
"Update",
"graph",
"variables",
"setting",
"giving",
"learning_rate",
"and",
"momentum"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L253-L268
|
[
"def",
"_update_graph_variables",
"(",
"self",
",",
"learning_rate",
":",
"float",
"=",
"None",
",",
"momentum",
":",
"float",
"=",
"None",
")",
":",
"if",
"learning_rate",
"is",
"not",
"None",
":",
"K",
".",
"set_value",
"(",
"self",
".",
"get_learning_rate_variable",
"(",
")",
",",
"learning_rate",
")",
"# log.info(f\"Learning rate = {learning_rate}\")",
"if",
"momentum",
"is",
"not",
"None",
":",
"K",
".",
"set_value",
"(",
"self",
".",
"get_momentum_variable",
"(",
")",
",",
"momentum",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
LRScheduledKerasModel.process_event
|
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None
|
deeppavlov/core/models/keras_model.py
|
def process_event(self, event_name: str, data: dict):
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None
"""
if (isinstance(self.opt.get("learning_rate", None), float) and
isinstance(self.opt.get("learning_rate_decay", None), float)):
pass
else:
if event_name == 'after_train_log':
if (self.get_learning_rate_variable() is not None) and ('learning_rate' not in data):
data['learning_rate'] = float(K.get_value(self.get_learning_rate_variable()))
# data['learning_rate'] = self._lr
if (self.get_momentum_variable() is not None) and ('momentum' not in data):
data['momentum'] = float(K.get_value(self.get_momentum_variable()))
# data['momentum'] = self._mom
else:
super().process_event(event_name, data)
|
def process_event(self, event_name: str, data: dict):
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None
"""
if (isinstance(self.opt.get("learning_rate", None), float) and
isinstance(self.opt.get("learning_rate_decay", None), float)):
pass
else:
if event_name == 'after_train_log':
if (self.get_learning_rate_variable() is not None) and ('learning_rate' not in data):
data['learning_rate'] = float(K.get_value(self.get_learning_rate_variable()))
# data['learning_rate'] = self._lr
if (self.get_momentum_variable() is not None) and ('momentum' not in data):
data['momentum'] = float(K.get_value(self.get_momentum_variable()))
# data['momentum'] = self._mom
else:
super().process_event(event_name, data)
|
[
"Process",
"event",
"after",
"epoch",
"Args",
":",
"event_name",
":",
"whether",
"event",
"is",
"send",
"after",
"epoch",
"or",
"batch",
".",
"Set",
"of",
"values",
":",
"after_epoch",
"after_batch",
"data",
":",
"event",
"data",
"(",
"dictionary",
")"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L271-L294
|
[
"def",
"process_event",
"(",
"self",
",",
"event_name",
":",
"str",
",",
"data",
":",
"dict",
")",
":",
"if",
"(",
"isinstance",
"(",
"self",
".",
"opt",
".",
"get",
"(",
"\"learning_rate\"",
",",
"None",
")",
",",
"float",
")",
"and",
"isinstance",
"(",
"self",
".",
"opt",
".",
"get",
"(",
"\"learning_rate_decay\"",
",",
"None",
")",
",",
"float",
")",
")",
":",
"pass",
"else",
":",
"if",
"event_name",
"==",
"'after_train_log'",
":",
"if",
"(",
"self",
".",
"get_learning_rate_variable",
"(",
")",
"is",
"not",
"None",
")",
"and",
"(",
"'learning_rate'",
"not",
"in",
"data",
")",
":",
"data",
"[",
"'learning_rate'",
"]",
"=",
"float",
"(",
"K",
".",
"get_value",
"(",
"self",
".",
"get_learning_rate_variable",
"(",
")",
")",
")",
"# data['learning_rate'] = self._lr",
"if",
"(",
"self",
".",
"get_momentum_variable",
"(",
")",
"is",
"not",
"None",
")",
"and",
"(",
"'momentum'",
"not",
"in",
"data",
")",
":",
"data",
"[",
"'momentum'",
"]",
"=",
"float",
"(",
"K",
".",
"get_value",
"(",
"self",
".",
"get_momentum_variable",
"(",
")",
")",
")",
"# data['momentum'] = self._mom",
"else",
":",
"super",
"(",
")",
".",
"process_event",
"(",
"event_name",
",",
"data",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
round_f1
|
Calculates F1 (binary) measure.
Args:
y_true: list of true values
y_predicted: list of predicted values
Returns:
F1 score
|
deeppavlov/metrics/fmeasure.py
|
def round_f1(y_true, y_predicted):
"""
Calculates F1 (binary) measure.
Args:
y_true: list of true values
y_predicted: list of predicted values
Returns:
F1 score
"""
try:
predictions = [np.round(x) for x in y_predicted]
except TypeError:
predictions = y_predicted
return f1_score(y_true, predictions)
|
def round_f1(y_true, y_predicted):
"""
Calculates F1 (binary) measure.
Args:
y_true: list of true values
y_predicted: list of predicted values
Returns:
F1 score
"""
try:
predictions = [np.round(x) for x in y_predicted]
except TypeError:
predictions = y_predicted
return f1_score(y_true, predictions)
|
[
"Calculates",
"F1",
"(",
"binary",
")",
"measure",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/fmeasure.py#L40-L56
|
[
"def",
"round_f1",
"(",
"y_true",
",",
"y_predicted",
")",
":",
"try",
":",
"predictions",
"=",
"[",
"np",
".",
"round",
"(",
"x",
")",
"for",
"x",
"in",
"y_predicted",
"]",
"except",
"TypeError",
":",
"predictions",
"=",
"y_predicted",
"return",
"f1_score",
"(",
"y_true",
",",
"predictions",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
round_f1_macro
|
Calculates F1 macro measure.
Args:
y_true: list of true values
y_predicted: list of predicted values
Returns:
F1 score
|
deeppavlov/metrics/fmeasure.py
|
def round_f1_macro(y_true, y_predicted):
"""
Calculates F1 macro measure.
Args:
y_true: list of true values
y_predicted: list of predicted values
Returns:
F1 score
"""
try:
predictions = [np.round(x) for x in y_predicted]
except TypeError:
predictions = y_predicted
return f1_score(np.array(y_true), np.array(predictions), average="macro")
|
def round_f1_macro(y_true, y_predicted):
"""
Calculates F1 macro measure.
Args:
y_true: list of true values
y_predicted: list of predicted values
Returns:
F1 score
"""
try:
predictions = [np.round(x) for x in y_predicted]
except TypeError:
predictions = y_predicted
return f1_score(np.array(y_true), np.array(predictions), average="macro")
|
[
"Calculates",
"F1",
"macro",
"measure",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/fmeasure.py#L60-L76
|
[
"def",
"round_f1_macro",
"(",
"y_true",
",",
"y_predicted",
")",
":",
"try",
":",
"predictions",
"=",
"[",
"np",
".",
"round",
"(",
"x",
")",
"for",
"x",
"in",
"y_predicted",
"]",
"except",
"TypeError",
":",
"predictions",
"=",
"y_predicted",
"return",
"f1_score",
"(",
"np",
".",
"array",
"(",
"y_true",
")",
",",
"np",
".",
"array",
"(",
"predictions",
")",
",",
"average",
"=",
"\"macro\"",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
process_word
|
Converts word to a tuple of symbols, optionally converts it to lowercase
and adds capitalization label.
Args:
word: input word
to_lower: whether to lowercase
append_case: whether to add case mark
('<FIRST_UPPER>' for first capital and '<ALL_UPPER>' for all caps)
Returns:
a preprocessed word
|
deeppavlov/models/preprocessors/capitalization.py
|
def process_word(word: str, to_lower: bool = False,
append_case: Optional[str] = None) -> Tuple[str]:
"""Converts word to a tuple of symbols, optionally converts it to lowercase
and adds capitalization label.
Args:
word: input word
to_lower: whether to lowercase
append_case: whether to add case mark
('<FIRST_UPPER>' for first capital and '<ALL_UPPER>' for all caps)
Returns:
a preprocessed word
"""
if all(x.isupper() for x in word) and len(word) > 1:
uppercase = "<ALL_UPPER>"
elif word[0].isupper():
uppercase = "<FIRST_UPPER>"
else:
uppercase = None
if to_lower:
word = word.lower()
if word.isdigit():
answer = ["<DIGIT>"]
elif word.startswith("http://") or word.startswith("www."):
answer = ["<HTTP>"]
else:
answer = list(word)
if to_lower and uppercase is not None:
if append_case == "first":
answer = [uppercase] + answer
elif append_case == "last":
answer = answer + [uppercase]
return tuple(answer)
|
def process_word(word: str, to_lower: bool = False,
append_case: Optional[str] = None) -> Tuple[str]:
"""Converts word to a tuple of symbols, optionally converts it to lowercase
and adds capitalization label.
Args:
word: input word
to_lower: whether to lowercase
append_case: whether to add case mark
('<FIRST_UPPER>' for first capital and '<ALL_UPPER>' for all caps)
Returns:
a preprocessed word
"""
if all(x.isupper() for x in word) and len(word) > 1:
uppercase = "<ALL_UPPER>"
elif word[0].isupper():
uppercase = "<FIRST_UPPER>"
else:
uppercase = None
if to_lower:
word = word.lower()
if word.isdigit():
answer = ["<DIGIT>"]
elif word.startswith("http://") or word.startswith("www."):
answer = ["<HTTP>"]
else:
answer = list(word)
if to_lower and uppercase is not None:
if append_case == "first":
answer = [uppercase] + answer
elif append_case == "last":
answer = answer + [uppercase]
return tuple(answer)
|
[
"Converts",
"word",
"to",
"a",
"tuple",
"of",
"symbols",
"optionally",
"converts",
"it",
"to",
"lowercase",
"and",
"adds",
"capitalization",
"label",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/preprocessors/capitalization.py#L75-L108
|
[
"def",
"process_word",
"(",
"word",
":",
"str",
",",
"to_lower",
":",
"bool",
"=",
"False",
",",
"append_case",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"str",
"]",
":",
"if",
"all",
"(",
"x",
".",
"isupper",
"(",
")",
"for",
"x",
"in",
"word",
")",
"and",
"len",
"(",
"word",
")",
">",
"1",
":",
"uppercase",
"=",
"\"<ALL_UPPER>\"",
"elif",
"word",
"[",
"0",
"]",
".",
"isupper",
"(",
")",
":",
"uppercase",
"=",
"\"<FIRST_UPPER>\"",
"else",
":",
"uppercase",
"=",
"None",
"if",
"to_lower",
":",
"word",
"=",
"word",
".",
"lower",
"(",
")",
"if",
"word",
".",
"isdigit",
"(",
")",
":",
"answer",
"=",
"[",
"\"<DIGIT>\"",
"]",
"elif",
"word",
".",
"startswith",
"(",
"\"http://\"",
")",
"or",
"word",
".",
"startswith",
"(",
"\"www.\"",
")",
":",
"answer",
"=",
"[",
"\"<HTTP>\"",
"]",
"else",
":",
"answer",
"=",
"list",
"(",
"word",
")",
"if",
"to_lower",
"and",
"uppercase",
"is",
"not",
"None",
":",
"if",
"append_case",
"==",
"\"first\"",
":",
"answer",
"=",
"[",
"uppercase",
"]",
"+",
"answer",
"elif",
"append_case",
"==",
"\"last\"",
":",
"answer",
"=",
"answer",
"+",
"[",
"uppercase",
"]",
"return",
"tuple",
"(",
"answer",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
stacked_cnn
|
Number of convolutional layers stacked on top of each other
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
add_l2_losses: whether to add l2 losses on network kernels to
tf.GraphKeys.REGULARIZATION_LOSSES or not
Returns:
units: tensor at the output of the last convolutional layer
|
deeppavlov/core/layers/tf_layers.py
|
def stacked_cnn(units: tf.Tensor,
n_hidden_list: List,
filter_width=3,
use_batch_norm=False,
use_dilation=False,
training_ph=None,
add_l2_losses=False):
""" Number of convolutional layers stacked on top of each other
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
add_l2_losses: whether to add l2 losses on network kernels to
tf.GraphKeys.REGULARIZATION_LOSSES or not
Returns:
units: tensor at the output of the last convolutional layer
"""
l2_reg = tf.nn.l2_loss if add_l2_losses else None
for n_layer, n_hidden in enumerate(n_hidden_list):
if use_dilation:
dilation_rate = 2 ** n_layer
else:
dilation_rate = 1
units = tf.layers.conv1d(units,
n_hidden,
filter_width,
padding='same',
dilation_rate=dilation_rate,
kernel_initializer=INITIALIZER(),
kernel_regularizer=l2_reg)
if use_batch_norm:
assert training_ph is not None
units = tf.layers.batch_normalization(units, training=training_ph)
units = tf.nn.relu(units)
return units
|
def stacked_cnn(units: tf.Tensor,
n_hidden_list: List,
filter_width=3,
use_batch_norm=False,
use_dilation=False,
training_ph=None,
add_l2_losses=False):
""" Number of convolutional layers stacked on top of each other
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
add_l2_losses: whether to add l2 losses on network kernels to
tf.GraphKeys.REGULARIZATION_LOSSES or not
Returns:
units: tensor at the output of the last convolutional layer
"""
l2_reg = tf.nn.l2_loss if add_l2_losses else None
for n_layer, n_hidden in enumerate(n_hidden_list):
if use_dilation:
dilation_rate = 2 ** n_layer
else:
dilation_rate = 1
units = tf.layers.conv1d(units,
n_hidden,
filter_width,
padding='same',
dilation_rate=dilation_rate,
kernel_initializer=INITIALIZER(),
kernel_regularizer=l2_reg)
if use_batch_norm:
assert training_ph is not None
units = tf.layers.batch_normalization(units, training=training_ph)
units = tf.nn.relu(units)
return units
|
[
"Number",
"of",
"convolutional",
"layers",
"stacked",
"on",
"top",
"of",
"each",
"other"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L30-L71
|
[
"def",
"stacked_cnn",
"(",
"units",
":",
"tf",
".",
"Tensor",
",",
"n_hidden_list",
":",
"List",
",",
"filter_width",
"=",
"3",
",",
"use_batch_norm",
"=",
"False",
",",
"use_dilation",
"=",
"False",
",",
"training_ph",
"=",
"None",
",",
"add_l2_losses",
"=",
"False",
")",
":",
"l2_reg",
"=",
"tf",
".",
"nn",
".",
"l2_loss",
"if",
"add_l2_losses",
"else",
"None",
"for",
"n_layer",
",",
"n_hidden",
"in",
"enumerate",
"(",
"n_hidden_list",
")",
":",
"if",
"use_dilation",
":",
"dilation_rate",
"=",
"2",
"**",
"n_layer",
"else",
":",
"dilation_rate",
"=",
"1",
"units",
"=",
"tf",
".",
"layers",
".",
"conv1d",
"(",
"units",
",",
"n_hidden",
",",
"filter_width",
",",
"padding",
"=",
"'same'",
",",
"dilation_rate",
"=",
"dilation_rate",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
",",
"kernel_regularizer",
"=",
"l2_reg",
")",
"if",
"use_batch_norm",
":",
"assert",
"training_ph",
"is",
"not",
"None",
"units",
"=",
"tf",
".",
"layers",
".",
"batch_normalization",
"(",
"units",
",",
"training",
"=",
"training_ph",
")",
"units",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"units",
")",
"return",
"units"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
dense_convolutional_network
|
Densely connected convolutional layers. Based on the paper:
[Gao 17] https://arxiv.org/abs/1608.06993
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
|
deeppavlov/core/layers/tf_layers.py
|
def dense_convolutional_network(units: tf.Tensor,
n_hidden_list: List,
filter_width=3,
use_dilation=False,
use_batch_norm=False,
training_ph=None):
""" Densely connected convolutional layers. Based on the paper:
[Gao 17] https://arxiv.org/abs/1608.06993
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
"""
units_list = [units]
for n_layer, n_filters in enumerate(n_hidden_list):
total_units = tf.concat(units_list, axis=-1)
if use_dilation:
dilation_rate = 2 ** n_layer
else:
dilation_rate = 1
units = tf.layers.conv1d(total_units,
n_filters,
filter_width,
dilation_rate=dilation_rate,
padding='same',
kernel_initializer=INITIALIZER())
if use_batch_norm:
units = tf.layers.batch_normalization(units, training=training_ph)
units = tf.nn.relu(units)
units_list.append(units)
return units
|
def dense_convolutional_network(units: tf.Tensor,
n_hidden_list: List,
filter_width=3,
use_dilation=False,
use_batch_norm=False,
training_ph=None):
""" Densely connected convolutional layers. Based on the paper:
[Gao 17] https://arxiv.org/abs/1608.06993
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
"""
units_list = [units]
for n_layer, n_filters in enumerate(n_hidden_list):
total_units = tf.concat(units_list, axis=-1)
if use_dilation:
dilation_rate = 2 ** n_layer
else:
dilation_rate = 1
units = tf.layers.conv1d(total_units,
n_filters,
filter_width,
dilation_rate=dilation_rate,
padding='same',
kernel_initializer=INITIALIZER())
if use_batch_norm:
units = tf.layers.batch_normalization(units, training=training_ph)
units = tf.nn.relu(units)
units_list.append(units)
return units
|
[
"Densely",
"connected",
"convolutional",
"layers",
".",
"Based",
"on",
"the",
"paper",
":",
"[",
"Gao",
"17",
"]",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1608",
".",
"06993"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L74-L113
|
[
"def",
"dense_convolutional_network",
"(",
"units",
":",
"tf",
".",
"Tensor",
",",
"n_hidden_list",
":",
"List",
",",
"filter_width",
"=",
"3",
",",
"use_dilation",
"=",
"False",
",",
"use_batch_norm",
"=",
"False",
",",
"training_ph",
"=",
"None",
")",
":",
"units_list",
"=",
"[",
"units",
"]",
"for",
"n_layer",
",",
"n_filters",
"in",
"enumerate",
"(",
"n_hidden_list",
")",
":",
"total_units",
"=",
"tf",
".",
"concat",
"(",
"units_list",
",",
"axis",
"=",
"-",
"1",
")",
"if",
"use_dilation",
":",
"dilation_rate",
"=",
"2",
"**",
"n_layer",
"else",
":",
"dilation_rate",
"=",
"1",
"units",
"=",
"tf",
".",
"layers",
".",
"conv1d",
"(",
"total_units",
",",
"n_filters",
",",
"filter_width",
",",
"dilation_rate",
"=",
"dilation_rate",
",",
"padding",
"=",
"'same'",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"if",
"use_batch_norm",
":",
"units",
"=",
"tf",
".",
"layers",
".",
"batch_normalization",
"(",
"units",
",",
"training",
"=",
"training_ph",
")",
"units",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"units",
")",
"units_list",
".",
"append",
"(",
"units",
")",
"return",
"units"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
bi_rnn
|
Bi directional recurrent neural network. GRU or LSTM
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden: list with number of hidden units at the ouput of each layer
seq_lengths: length of sequences for different length sequences in batch
can be None for maximum length as a length for every sample in the batch
cell_type: 'lstm' or 'gru'
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
use_peepholes: whether to use peephole connections (only 'lstm' case affected)
name: what variable_scope to use for the network parameters
Returns:
units: tensor at the output of the last recurrent layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
last_units: tensor of last hidden states for GRU and tuple
of last hidden stated and last cell states for LSTM
dimensionality of cell states and hidden states are
similar and equal to [B x 2 * H], where B - batch
size and H is number of hidden units
|
deeppavlov/core/layers/tf_layers.py
|
def bi_rnn(units: tf.Tensor,
n_hidden: List,
cell_type='gru',
seq_lengths=None,
trainable_initial_states=False,
use_peepholes=False,
name='Bi-'):
""" Bi directional recurrent neural network. GRU or LSTM
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden: list with number of hidden units at the ouput of each layer
seq_lengths: length of sequences for different length sequences in batch
can be None for maximum length as a length for every sample in the batch
cell_type: 'lstm' or 'gru'
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
use_peepholes: whether to use peephole connections (only 'lstm' case affected)
name: what variable_scope to use for the network parameters
Returns:
units: tensor at the output of the last recurrent layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
last_units: tensor of last hidden states for GRU and tuple
of last hidden stated and last cell states for LSTM
dimensionality of cell states and hidden states are
similar and equal to [B x 2 * H], where B - batch
size and H is number of hidden units
"""
with tf.variable_scope(name + '_' + cell_type.upper()):
if cell_type == 'gru':
forward_cell = tf.nn.rnn_cell.GRUCell(n_hidden, kernel_initializer=INITIALIZER())
backward_cell = tf.nn.rnn_cell.GRUCell(n_hidden, kernel_initializer=INITIALIZER())
if trainable_initial_states:
initial_state_fw = tf.tile(tf.get_variable('init_fw_h', [1, n_hidden]), (tf.shape(units)[0], 1))
initial_state_bw = tf.tile(tf.get_variable('init_bw_h', [1, n_hidden]), (tf.shape(units)[0], 1))
else:
initial_state_fw = initial_state_bw = None
elif cell_type == 'lstm':
forward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes, initializer=INITIALIZER())
backward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes, initializer=INITIALIZER())
if trainable_initial_states:
initial_state_fw = tf.nn.rnn_cell.LSTMStateTuple(
tf.tile(tf.get_variable('init_fw_c', [1, n_hidden]), (tf.shape(units)[0], 1)),
tf.tile(tf.get_variable('init_fw_h', [1, n_hidden]), (tf.shape(units)[0], 1)))
initial_state_bw = tf.nn.rnn_cell.LSTMStateTuple(
tf.tile(tf.get_variable('init_bw_c', [1, n_hidden]), (tf.shape(units)[0], 1)),
tf.tile(tf.get_variable('init_bw_h', [1, n_hidden]), (tf.shape(units)[0], 1)))
else:
initial_state_fw = initial_state_bw = None
else:
raise RuntimeError('cell_type must be either "gru" or "lstm"s')
(rnn_output_fw, rnn_output_bw), (fw, bw) = \
tf.nn.bidirectional_dynamic_rnn(forward_cell,
backward_cell,
units,
dtype=tf.float32,
sequence_length=seq_lengths,
initial_state_fw=initial_state_fw,
initial_state_bw=initial_state_bw)
kernels = [var for var in forward_cell.trainable_variables +
backward_cell.trainable_variables if 'kernel' in var.name]
for kernel in kernels:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, tf.nn.l2_loss(kernel))
return (rnn_output_fw, rnn_output_bw), (fw, bw)
|
def bi_rnn(units: tf.Tensor,
n_hidden: List,
cell_type='gru',
seq_lengths=None,
trainable_initial_states=False,
use_peepholes=False,
name='Bi-'):
""" Bi directional recurrent neural network. GRU or LSTM
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden: list with number of hidden units at the ouput of each layer
seq_lengths: length of sequences for different length sequences in batch
can be None for maximum length as a length for every sample in the batch
cell_type: 'lstm' or 'gru'
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
use_peepholes: whether to use peephole connections (only 'lstm' case affected)
name: what variable_scope to use for the network parameters
Returns:
units: tensor at the output of the last recurrent layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
last_units: tensor of last hidden states for GRU and tuple
of last hidden stated and last cell states for LSTM
dimensionality of cell states and hidden states are
similar and equal to [B x 2 * H], where B - batch
size and H is number of hidden units
"""
with tf.variable_scope(name + '_' + cell_type.upper()):
if cell_type == 'gru':
forward_cell = tf.nn.rnn_cell.GRUCell(n_hidden, kernel_initializer=INITIALIZER())
backward_cell = tf.nn.rnn_cell.GRUCell(n_hidden, kernel_initializer=INITIALIZER())
if trainable_initial_states:
initial_state_fw = tf.tile(tf.get_variable('init_fw_h', [1, n_hidden]), (tf.shape(units)[0], 1))
initial_state_bw = tf.tile(tf.get_variable('init_bw_h', [1, n_hidden]), (tf.shape(units)[0], 1))
else:
initial_state_fw = initial_state_bw = None
elif cell_type == 'lstm':
forward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes, initializer=INITIALIZER())
backward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes, initializer=INITIALIZER())
if trainable_initial_states:
initial_state_fw = tf.nn.rnn_cell.LSTMStateTuple(
tf.tile(tf.get_variable('init_fw_c', [1, n_hidden]), (tf.shape(units)[0], 1)),
tf.tile(tf.get_variable('init_fw_h', [1, n_hidden]), (tf.shape(units)[0], 1)))
initial_state_bw = tf.nn.rnn_cell.LSTMStateTuple(
tf.tile(tf.get_variable('init_bw_c', [1, n_hidden]), (tf.shape(units)[0], 1)),
tf.tile(tf.get_variable('init_bw_h', [1, n_hidden]), (tf.shape(units)[0], 1)))
else:
initial_state_fw = initial_state_bw = None
else:
raise RuntimeError('cell_type must be either "gru" or "lstm"s')
(rnn_output_fw, rnn_output_bw), (fw, bw) = \
tf.nn.bidirectional_dynamic_rnn(forward_cell,
backward_cell,
units,
dtype=tf.float32,
sequence_length=seq_lengths,
initial_state_fw=initial_state_fw,
initial_state_bw=initial_state_bw)
kernels = [var for var in forward_cell.trainable_variables +
backward_cell.trainable_variables if 'kernel' in var.name]
for kernel in kernels:
tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, tf.nn.l2_loss(kernel))
return (rnn_output_fw, rnn_output_bw), (fw, bw)
|
[
"Bi",
"directional",
"recurrent",
"neural",
"network",
".",
"GRU",
"or",
"LSTM"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L116-L181
|
[
"def",
"bi_rnn",
"(",
"units",
":",
"tf",
".",
"Tensor",
",",
"n_hidden",
":",
"List",
",",
"cell_type",
"=",
"'gru'",
",",
"seq_lengths",
"=",
"None",
",",
"trainable_initial_states",
"=",
"False",
",",
"use_peepholes",
"=",
"False",
",",
"name",
"=",
"'Bi-'",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
"+",
"'_'",
"+",
"cell_type",
".",
"upper",
"(",
")",
")",
":",
"if",
"cell_type",
"==",
"'gru'",
":",
"forward_cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"GRUCell",
"(",
"n_hidden",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"backward_cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"GRUCell",
"(",
"n_hidden",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"if",
"trainable_initial_states",
":",
"initial_state_fw",
"=",
"tf",
".",
"tile",
"(",
"tf",
".",
"get_variable",
"(",
"'init_fw_h'",
",",
"[",
"1",
",",
"n_hidden",
"]",
")",
",",
"(",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
"initial_state_bw",
"=",
"tf",
".",
"tile",
"(",
"tf",
".",
"get_variable",
"(",
"'init_bw_h'",
",",
"[",
"1",
",",
"n_hidden",
"]",
")",
",",
"(",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
"else",
":",
"initial_state_fw",
"=",
"initial_state_bw",
"=",
"None",
"elif",
"cell_type",
"==",
"'lstm'",
":",
"forward_cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"LSTMCell",
"(",
"n_hidden",
",",
"use_peepholes",
"=",
"use_peepholes",
",",
"initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"backward_cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"LSTMCell",
"(",
"n_hidden",
",",
"use_peepholes",
"=",
"use_peepholes",
",",
"initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"if",
"trainable_initial_states",
":",
"initial_state_fw",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"LSTMStateTuple",
"(",
"tf",
".",
"tile",
"(",
"tf",
".",
"get_variable",
"(",
"'init_fw_c'",
",",
"[",
"1",
",",
"n_hidden",
"]",
")",
",",
"(",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
",",
"tf",
".",
"tile",
"(",
"tf",
".",
"get_variable",
"(",
"'init_fw_h'",
",",
"[",
"1",
",",
"n_hidden",
"]",
")",
",",
"(",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
")",
"initial_state_bw",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"LSTMStateTuple",
"(",
"tf",
".",
"tile",
"(",
"tf",
".",
"get_variable",
"(",
"'init_bw_c'",
",",
"[",
"1",
",",
"n_hidden",
"]",
")",
",",
"(",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
",",
"tf",
".",
"tile",
"(",
"tf",
".",
"get_variable",
"(",
"'init_bw_h'",
",",
"[",
"1",
",",
"n_hidden",
"]",
")",
",",
"(",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
")",
"else",
":",
"initial_state_fw",
"=",
"initial_state_bw",
"=",
"None",
"else",
":",
"raise",
"RuntimeError",
"(",
"'cell_type must be either \"gru\" or \"lstm\"s'",
")",
"(",
"rnn_output_fw",
",",
"rnn_output_bw",
")",
",",
"(",
"fw",
",",
"bw",
")",
"=",
"tf",
".",
"nn",
".",
"bidirectional_dynamic_rnn",
"(",
"forward_cell",
",",
"backward_cell",
",",
"units",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"sequence_length",
"=",
"seq_lengths",
",",
"initial_state_fw",
"=",
"initial_state_fw",
",",
"initial_state_bw",
"=",
"initial_state_bw",
")",
"kernels",
"=",
"[",
"var",
"for",
"var",
"in",
"forward_cell",
".",
"trainable_variables",
"+",
"backward_cell",
".",
"trainable_variables",
"if",
"'kernel'",
"in",
"var",
".",
"name",
"]",
"for",
"kernel",
"in",
"kernels",
":",
"tf",
".",
"add_to_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"REGULARIZATION_LOSSES",
",",
"tf",
".",
"nn",
".",
"l2_loss",
"(",
"kernel",
")",
")",
"return",
"(",
"rnn_output_fw",
",",
"rnn_output_bw",
")",
",",
"(",
"fw",
",",
"bw",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
stacked_bi_rnn
|
Stackted recurrent neural networks GRU or LSTM
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
seq_lengths: length of sequences for different length sequences in batch
can be None for maximum length as a length for every sample in the batch
cell_type: 'lstm' or 'gru'
use_peepholes: whether to use peephole connections (only 'lstm' case affected)
name: what variable_scope to use for the network parameters
Returns:
units: tensor at the output of the last recurrent layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
last_units: tensor of last hidden states for GRU and tuple
of last hidden stated and last cell states for LSTM
dimensionality of cell states and hidden states are
similar and equal to [B x 2 * H], where B - batch
size and H is number of hidden units
|
deeppavlov/core/layers/tf_layers.py
|
def stacked_bi_rnn(units: tf.Tensor,
n_hidden_list: List,
cell_type='gru',
seq_lengths=None,
use_peepholes=False,
name='RNN_layer'):
""" Stackted recurrent neural networks GRU or LSTM
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
seq_lengths: length of sequences for different length sequences in batch
can be None for maximum length as a length for every sample in the batch
cell_type: 'lstm' or 'gru'
use_peepholes: whether to use peephole connections (only 'lstm' case affected)
name: what variable_scope to use for the network parameters
Returns:
units: tensor at the output of the last recurrent layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
last_units: tensor of last hidden states for GRU and tuple
of last hidden stated and last cell states for LSTM
dimensionality of cell states and hidden states are
similar and equal to [B x 2 * H], where B - batch
size and H is number of hidden units
"""
for n, n_hidden in enumerate(n_hidden_list):
with tf.variable_scope(name + '_' + str(n)):
if cell_type == 'gru':
forward_cell = tf.nn.rnn_cell.GRUCell(n_hidden)
backward_cell = tf.nn.rnn_cell.GRUCell(n_hidden)
elif cell_type == 'lstm':
forward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes)
backward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes)
else:
raise RuntimeError('cell_type must be either gru or lstm')
(rnn_output_fw, rnn_output_bw), (fw, bw) = \
tf.nn.bidirectional_dynamic_rnn(forward_cell,
backward_cell,
units,
dtype=tf.float32,
sequence_length=seq_lengths)
units = tf.concat([rnn_output_fw, rnn_output_bw], axis=2)
if cell_type == 'gru':
last_units = tf.concat([fw, bw], axis=1)
else:
(c_fw, h_fw), (c_bw, h_bw) = fw, bw
c = tf.concat([c_fw, c_bw], axis=1)
h = tf.concat([h_fw, h_bw], axis=1)
last_units = (h, c)
return units, last_units
|
def stacked_bi_rnn(units: tf.Tensor,
n_hidden_list: List,
cell_type='gru',
seq_lengths=None,
use_peepholes=False,
name='RNN_layer'):
""" Stackted recurrent neural networks GRU or LSTM
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
seq_lengths: length of sequences for different length sequences in batch
can be None for maximum length as a length for every sample in the batch
cell_type: 'lstm' or 'gru'
use_peepholes: whether to use peephole connections (only 'lstm' case affected)
name: what variable_scope to use for the network parameters
Returns:
units: tensor at the output of the last recurrent layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
last_units: tensor of last hidden states for GRU and tuple
of last hidden stated and last cell states for LSTM
dimensionality of cell states and hidden states are
similar and equal to [B x 2 * H], where B - batch
size and H is number of hidden units
"""
for n, n_hidden in enumerate(n_hidden_list):
with tf.variable_scope(name + '_' + str(n)):
if cell_type == 'gru':
forward_cell = tf.nn.rnn_cell.GRUCell(n_hidden)
backward_cell = tf.nn.rnn_cell.GRUCell(n_hidden)
elif cell_type == 'lstm':
forward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes)
backward_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, use_peepholes=use_peepholes)
else:
raise RuntimeError('cell_type must be either gru or lstm')
(rnn_output_fw, rnn_output_bw), (fw, bw) = \
tf.nn.bidirectional_dynamic_rnn(forward_cell,
backward_cell,
units,
dtype=tf.float32,
sequence_length=seq_lengths)
units = tf.concat([rnn_output_fw, rnn_output_bw], axis=2)
if cell_type == 'gru':
last_units = tf.concat([fw, bw], axis=1)
else:
(c_fw, h_fw), (c_bw, h_bw) = fw, bw
c = tf.concat([c_fw, c_bw], axis=1)
h = tf.concat([h_fw, h_bw], axis=1)
last_units = (h, c)
return units, last_units
|
[
"Stackted",
"recurrent",
"neural",
"networks",
"GRU",
"or",
"LSTM"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L184-L234
|
[
"def",
"stacked_bi_rnn",
"(",
"units",
":",
"tf",
".",
"Tensor",
",",
"n_hidden_list",
":",
"List",
",",
"cell_type",
"=",
"'gru'",
",",
"seq_lengths",
"=",
"None",
",",
"use_peepholes",
"=",
"False",
",",
"name",
"=",
"'RNN_layer'",
")",
":",
"for",
"n",
",",
"n_hidden",
"in",
"enumerate",
"(",
"n_hidden_list",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
"+",
"'_'",
"+",
"str",
"(",
"n",
")",
")",
":",
"if",
"cell_type",
"==",
"'gru'",
":",
"forward_cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"GRUCell",
"(",
"n_hidden",
")",
"backward_cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"GRUCell",
"(",
"n_hidden",
")",
"elif",
"cell_type",
"==",
"'lstm'",
":",
"forward_cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"LSTMCell",
"(",
"n_hidden",
",",
"use_peepholes",
"=",
"use_peepholes",
")",
"backward_cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"LSTMCell",
"(",
"n_hidden",
",",
"use_peepholes",
"=",
"use_peepholes",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'cell_type must be either gru or lstm'",
")",
"(",
"rnn_output_fw",
",",
"rnn_output_bw",
")",
",",
"(",
"fw",
",",
"bw",
")",
"=",
"tf",
".",
"nn",
".",
"bidirectional_dynamic_rnn",
"(",
"forward_cell",
",",
"backward_cell",
",",
"units",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"sequence_length",
"=",
"seq_lengths",
")",
"units",
"=",
"tf",
".",
"concat",
"(",
"[",
"rnn_output_fw",
",",
"rnn_output_bw",
"]",
",",
"axis",
"=",
"2",
")",
"if",
"cell_type",
"==",
"'gru'",
":",
"last_units",
"=",
"tf",
".",
"concat",
"(",
"[",
"fw",
",",
"bw",
"]",
",",
"axis",
"=",
"1",
")",
"else",
":",
"(",
"c_fw",
",",
"h_fw",
")",
",",
"(",
"c_bw",
",",
"h_bw",
")",
"=",
"fw",
",",
"bw",
"c",
"=",
"tf",
".",
"concat",
"(",
"[",
"c_fw",
",",
"c_bw",
"]",
",",
"axis",
"=",
"1",
")",
"h",
"=",
"tf",
".",
"concat",
"(",
"[",
"h_fw",
",",
"h_bw",
"]",
",",
"axis",
"=",
"1",
")",
"last_units",
"=",
"(",
"h",
",",
"c",
")",
"return",
"units",
",",
"last_units"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
u_shape
|
Network architecture inspired by One Hundred layer Tiramisu.
https://arxiv.org/abs/1611.09326. U-Net like.
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
|
deeppavlov/core/layers/tf_layers.py
|
def u_shape(units: tf.Tensor,
n_hidden_list: List,
filter_width=7,
use_batch_norm=False,
training_ph=None):
""" Network architecture inspired by One Hundred layer Tiramisu.
https://arxiv.org/abs/1611.09326. U-Net like.
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
"""
# Bread Crumbs
units_for_skip_conn = []
conv_net_params = {'filter_width': filter_width,
'use_batch_norm': use_batch_norm,
'training_ph': training_ph}
# Go down the rabbit hole
for n_hidden in n_hidden_list:
units = stacked_cnn(units, [n_hidden], **conv_net_params)
units_for_skip_conn.append(units)
units = tf.layers.max_pooling1d(units, pool_size=2, strides=2, padding='same')
units = stacked_cnn(units, [n_hidden], **conv_net_params)
# Up to the sun light
for down_step, n_hidden in enumerate(n_hidden_list[::-1]):
units = tf.expand_dims(units, axis=2)
units = tf.layers.conv2d_transpose(units, n_hidden, filter_width, strides=(2, 1), padding='same')
units = tf.squeeze(units, axis=2)
# Skip connection
skip_units = units_for_skip_conn[-(down_step + 1)]
if skip_units.get_shape().as_list()[-1] != n_hidden:
skip_units = tf.layers.dense(skip_units, n_hidden)
units = skip_units + units
units = stacked_cnn(units, [n_hidden], **conv_net_params)
return units
|
def u_shape(units: tf.Tensor,
n_hidden_list: List,
filter_width=7,
use_batch_norm=False,
training_ph=None):
""" Network architecture inspired by One Hundred layer Tiramisu.
https://arxiv.org/abs/1611.09326. U-Net like.
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the ouput of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
"""
# Bread Crumbs
units_for_skip_conn = []
conv_net_params = {'filter_width': filter_width,
'use_batch_norm': use_batch_norm,
'training_ph': training_ph}
# Go down the rabbit hole
for n_hidden in n_hidden_list:
units = stacked_cnn(units, [n_hidden], **conv_net_params)
units_for_skip_conn.append(units)
units = tf.layers.max_pooling1d(units, pool_size=2, strides=2, padding='same')
units = stacked_cnn(units, [n_hidden], **conv_net_params)
# Up to the sun light
for down_step, n_hidden in enumerate(n_hidden_list[::-1]):
units = tf.expand_dims(units, axis=2)
units = tf.layers.conv2d_transpose(units, n_hidden, filter_width, strides=(2, 1), padding='same')
units = tf.squeeze(units, axis=2)
# Skip connection
skip_units = units_for_skip_conn[-(down_step + 1)]
if skip_units.get_shape().as_list()[-1] != n_hidden:
skip_units = tf.layers.dense(skip_units, n_hidden)
units = skip_units + units
units = stacked_cnn(units, [n_hidden], **conv_net_params)
return units
|
[
"Network",
"architecture",
"inspired",
"by",
"One",
"Hundred",
"layer",
"Tiramisu",
".",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1611",
".",
"09326",
".",
"U",
"-",
"Net",
"like",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L237-L285
|
[
"def",
"u_shape",
"(",
"units",
":",
"tf",
".",
"Tensor",
",",
"n_hidden_list",
":",
"List",
",",
"filter_width",
"=",
"7",
",",
"use_batch_norm",
"=",
"False",
",",
"training_ph",
"=",
"None",
")",
":",
"# Bread Crumbs",
"units_for_skip_conn",
"=",
"[",
"]",
"conv_net_params",
"=",
"{",
"'filter_width'",
":",
"filter_width",
",",
"'use_batch_norm'",
":",
"use_batch_norm",
",",
"'training_ph'",
":",
"training_ph",
"}",
"# Go down the rabbit hole",
"for",
"n_hidden",
"in",
"n_hidden_list",
":",
"units",
"=",
"stacked_cnn",
"(",
"units",
",",
"[",
"n_hidden",
"]",
",",
"*",
"*",
"conv_net_params",
")",
"units_for_skip_conn",
".",
"append",
"(",
"units",
")",
"units",
"=",
"tf",
".",
"layers",
".",
"max_pooling1d",
"(",
"units",
",",
"pool_size",
"=",
"2",
",",
"strides",
"=",
"2",
",",
"padding",
"=",
"'same'",
")",
"units",
"=",
"stacked_cnn",
"(",
"units",
",",
"[",
"n_hidden",
"]",
",",
"*",
"*",
"conv_net_params",
")",
"# Up to the sun light",
"for",
"down_step",
",",
"n_hidden",
"in",
"enumerate",
"(",
"n_hidden_list",
"[",
":",
":",
"-",
"1",
"]",
")",
":",
"units",
"=",
"tf",
".",
"expand_dims",
"(",
"units",
",",
"axis",
"=",
"2",
")",
"units",
"=",
"tf",
".",
"layers",
".",
"conv2d_transpose",
"(",
"units",
",",
"n_hidden",
",",
"filter_width",
",",
"strides",
"=",
"(",
"2",
",",
"1",
")",
",",
"padding",
"=",
"'same'",
")",
"units",
"=",
"tf",
".",
"squeeze",
"(",
"units",
",",
"axis",
"=",
"2",
")",
"# Skip connection",
"skip_units",
"=",
"units_for_skip_conn",
"[",
"-",
"(",
"down_step",
"+",
"1",
")",
"]",
"if",
"skip_units",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"-",
"1",
"]",
"!=",
"n_hidden",
":",
"skip_units",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"skip_units",
",",
"n_hidden",
")",
"units",
"=",
"skip_units",
"+",
"units",
"units",
"=",
"stacked_cnn",
"(",
"units",
",",
"[",
"n_hidden",
"]",
",",
"*",
"*",
"conv_net_params",
")",
"return",
"units"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
stacked_highway_cnn
|
Highway convolutional network. Skip connection with gating
mechanism.
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the output of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
|
deeppavlov/core/layers/tf_layers.py
|
def stacked_highway_cnn(units: tf.Tensor,
n_hidden_list: List,
filter_width=3,
use_batch_norm=False,
use_dilation=False,
training_ph=None):
""" Highway convolutional network. Skip connection with gating
mechanism.
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the output of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
"""
for n_layer, n_hidden in enumerate(n_hidden_list):
input_units = units
# Projection if needed
if input_units.get_shape().as_list()[-1] != n_hidden:
input_units = tf.layers.dense(input_units, n_hidden)
if use_dilation:
dilation_rate = 2 ** n_layer
else:
dilation_rate = 1
units = tf.layers.conv1d(units,
n_hidden,
filter_width,
padding='same',
dilation_rate=dilation_rate,
kernel_initializer=INITIALIZER())
if use_batch_norm:
units = tf.layers.batch_normalization(units, training=training_ph)
sigmoid_gate = tf.layers.dense(input_units, 1, activation=tf.sigmoid, kernel_initializer=INITIALIZER())
input_units = sigmoid_gate * input_units + (1 - sigmoid_gate) * units
input_units = tf.nn.relu(input_units)
units = input_units
return units
|
def stacked_highway_cnn(units: tf.Tensor,
n_hidden_list: List,
filter_width=3,
use_batch_norm=False,
use_dilation=False,
training_ph=None):
""" Highway convolutional network. Skip connection with gating
mechanism.
Args:
units: a tensorflow tensor with dimensionality [None, n_tokens, n_features]
n_hidden_list: list with number of hidden units at the output of each layer
filter_width: width of the kernel in tokens
use_batch_norm: whether to use batch normalization between layers
use_dilation: use power of 2 dilation scheme [1, 2, 4, 8 .. ] for layers 1, 2, 3, 4 ...
training_ph: boolean placeholder determining whether is training phase now or not.
It is used only for batch normalization to determine whether to use
current batch average (std) or memory stored average (std)
Returns:
units: tensor at the output of the last convolutional layer
with dimensionality [None, n_tokens, n_hidden_list[-1]]
"""
for n_layer, n_hidden in enumerate(n_hidden_list):
input_units = units
# Projection if needed
if input_units.get_shape().as_list()[-1] != n_hidden:
input_units = tf.layers.dense(input_units, n_hidden)
if use_dilation:
dilation_rate = 2 ** n_layer
else:
dilation_rate = 1
units = tf.layers.conv1d(units,
n_hidden,
filter_width,
padding='same',
dilation_rate=dilation_rate,
kernel_initializer=INITIALIZER())
if use_batch_norm:
units = tf.layers.batch_normalization(units, training=training_ph)
sigmoid_gate = tf.layers.dense(input_units, 1, activation=tf.sigmoid, kernel_initializer=INITIALIZER())
input_units = sigmoid_gate * input_units + (1 - sigmoid_gate) * units
input_units = tf.nn.relu(input_units)
units = input_units
return units
|
[
"Highway",
"convolutional",
"network",
".",
"Skip",
"connection",
"with",
"gating",
"mechanism",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L288-L332
|
[
"def",
"stacked_highway_cnn",
"(",
"units",
":",
"tf",
".",
"Tensor",
",",
"n_hidden_list",
":",
"List",
",",
"filter_width",
"=",
"3",
",",
"use_batch_norm",
"=",
"False",
",",
"use_dilation",
"=",
"False",
",",
"training_ph",
"=",
"None",
")",
":",
"for",
"n_layer",
",",
"n_hidden",
"in",
"enumerate",
"(",
"n_hidden_list",
")",
":",
"input_units",
"=",
"units",
"# Projection if needed",
"if",
"input_units",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"-",
"1",
"]",
"!=",
"n_hidden",
":",
"input_units",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"input_units",
",",
"n_hidden",
")",
"if",
"use_dilation",
":",
"dilation_rate",
"=",
"2",
"**",
"n_layer",
"else",
":",
"dilation_rate",
"=",
"1",
"units",
"=",
"tf",
".",
"layers",
".",
"conv1d",
"(",
"units",
",",
"n_hidden",
",",
"filter_width",
",",
"padding",
"=",
"'same'",
",",
"dilation_rate",
"=",
"dilation_rate",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"if",
"use_batch_norm",
":",
"units",
"=",
"tf",
".",
"layers",
".",
"batch_normalization",
"(",
"units",
",",
"training",
"=",
"training_ph",
")",
"sigmoid_gate",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"input_units",
",",
"1",
",",
"activation",
"=",
"tf",
".",
"sigmoid",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"input_units",
"=",
"sigmoid_gate",
"*",
"input_units",
"+",
"(",
"1",
"-",
"sigmoid_gate",
")",
"*",
"units",
"input_units",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"input_units",
")",
"units",
"=",
"input_units",
"return",
"units"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
embedding_layer
|
Token embedding layer. Create matrix of for token embeddings.
Can be initialized with given matrix (for example pre-trained
with word2ve algorithm
Args:
token_indices: token indices tensor of type tf.int32
token_embedding_matrix: matrix of embeddings with dimensionality
[n_tokens, embeddings_dimension]
n_tokens: total number of unique tokens
token_embedding_dim: dimensionality of embeddings, typical 100..300
name: embedding matrix name (variable name)
trainable: whether to set the matrix trainable or not
Returns:
embedded_tokens: tf tensor of size [B, T, E], where B - batch size
T - number of tokens, E - token_embedding_dim
|
deeppavlov/core/layers/tf_layers.py
|
def embedding_layer(token_indices=None,
token_embedding_matrix=None,
n_tokens=None,
token_embedding_dim=None,
name: str = None,
trainable=True):
""" Token embedding layer. Create matrix of for token embeddings.
Can be initialized with given matrix (for example pre-trained
with word2ve algorithm
Args:
token_indices: token indices tensor of type tf.int32
token_embedding_matrix: matrix of embeddings with dimensionality
[n_tokens, embeddings_dimension]
n_tokens: total number of unique tokens
token_embedding_dim: dimensionality of embeddings, typical 100..300
name: embedding matrix name (variable name)
trainable: whether to set the matrix trainable or not
Returns:
embedded_tokens: tf tensor of size [B, T, E], where B - batch size
T - number of tokens, E - token_embedding_dim
"""
if token_embedding_matrix is not None:
tok_mat = token_embedding_matrix
if trainable:
Warning('Matrix of embeddings is passed to the embedding_layer, '
'possibly there is a pre-trained embedding matrix. '
'Embeddings paramenters are set to Trainable!')
else:
tok_mat = np.random.randn(n_tokens, token_embedding_dim).astype(np.float32) / np.sqrt(token_embedding_dim)
tok_emb_mat = tf.Variable(tok_mat, name=name, trainable=trainable)
embedded_tokens = tf.nn.embedding_lookup(tok_emb_mat, token_indices)
return embedded_tokens
|
def embedding_layer(token_indices=None,
token_embedding_matrix=None,
n_tokens=None,
token_embedding_dim=None,
name: str = None,
trainable=True):
""" Token embedding layer. Create matrix of for token embeddings.
Can be initialized with given matrix (for example pre-trained
with word2ve algorithm
Args:
token_indices: token indices tensor of type tf.int32
token_embedding_matrix: matrix of embeddings with dimensionality
[n_tokens, embeddings_dimension]
n_tokens: total number of unique tokens
token_embedding_dim: dimensionality of embeddings, typical 100..300
name: embedding matrix name (variable name)
trainable: whether to set the matrix trainable or not
Returns:
embedded_tokens: tf tensor of size [B, T, E], where B - batch size
T - number of tokens, E - token_embedding_dim
"""
if token_embedding_matrix is not None:
tok_mat = token_embedding_matrix
if trainable:
Warning('Matrix of embeddings is passed to the embedding_layer, '
'possibly there is a pre-trained embedding matrix. '
'Embeddings paramenters are set to Trainable!')
else:
tok_mat = np.random.randn(n_tokens, token_embedding_dim).astype(np.float32) / np.sqrt(token_embedding_dim)
tok_emb_mat = tf.Variable(tok_mat, name=name, trainable=trainable)
embedded_tokens = tf.nn.embedding_lookup(tok_emb_mat, token_indices)
return embedded_tokens
|
[
"Token",
"embedding",
"layer",
".",
"Create",
"matrix",
"of",
"for",
"token",
"embeddings",
".",
"Can",
"be",
"initialized",
"with",
"given",
"matrix",
"(",
"for",
"example",
"pre",
"-",
"trained",
"with",
"word2ve",
"algorithm"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L335-L368
|
[
"def",
"embedding_layer",
"(",
"token_indices",
"=",
"None",
",",
"token_embedding_matrix",
"=",
"None",
",",
"n_tokens",
"=",
"None",
",",
"token_embedding_dim",
"=",
"None",
",",
"name",
":",
"str",
"=",
"None",
",",
"trainable",
"=",
"True",
")",
":",
"if",
"token_embedding_matrix",
"is",
"not",
"None",
":",
"tok_mat",
"=",
"token_embedding_matrix",
"if",
"trainable",
":",
"Warning",
"(",
"'Matrix of embeddings is passed to the embedding_layer, '",
"'possibly there is a pre-trained embedding matrix. '",
"'Embeddings paramenters are set to Trainable!'",
")",
"else",
":",
"tok_mat",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"n_tokens",
",",
"token_embedding_dim",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"/",
"np",
".",
"sqrt",
"(",
"token_embedding_dim",
")",
"tok_emb_mat",
"=",
"tf",
".",
"Variable",
"(",
"tok_mat",
",",
"name",
"=",
"name",
",",
"trainable",
"=",
"trainable",
")",
"embedded_tokens",
"=",
"tf",
".",
"nn",
".",
"embedding_lookup",
"(",
"tok_emb_mat",
",",
"token_indices",
")",
"return",
"embedded_tokens"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
character_embedding_network
|
Characters to vector. Every sequence of characters (token)
is embedded to vector space with dimensionality char_embedding_dim
Convolution plus max_pooling is used to obtain vector representations
of words.
Args:
char_placeholder: placeholder of int32 type with dimensionality [B, T, C]
B - batch size (can be None)
T - Number of tokens (can be None)
C - number of characters (can be None)
n_characters: total number of unique characters
emb_mat: if n_characters is not provided the emb_mat should be provided
it is a numpy array with dimensions [V, E], where V - vocabulary size
and E - embeddings dimension
char_embedding_dim: dimensionality of characters embeddings
filter_widths: array of width of kernel in convolutional embedding network
used in parallel
Returns:
embeddings: tf.Tensor with dimensionality [B, T, F],
where F is dimensionality of embeddings
|
deeppavlov/core/layers/tf_layers.py
|
def character_embedding_network(char_placeholder: tf.Tensor,
n_characters: int = None,
emb_mat: np.array = None,
char_embedding_dim: int = None,
filter_widths=(3, 4, 5, 7),
highway_on_top=False):
""" Characters to vector. Every sequence of characters (token)
is embedded to vector space with dimensionality char_embedding_dim
Convolution plus max_pooling is used to obtain vector representations
of words.
Args:
char_placeholder: placeholder of int32 type with dimensionality [B, T, C]
B - batch size (can be None)
T - Number of tokens (can be None)
C - number of characters (can be None)
n_characters: total number of unique characters
emb_mat: if n_characters is not provided the emb_mat should be provided
it is a numpy array with dimensions [V, E], where V - vocabulary size
and E - embeddings dimension
char_embedding_dim: dimensionality of characters embeddings
filter_widths: array of width of kernel in convolutional embedding network
used in parallel
Returns:
embeddings: tf.Tensor with dimensionality [B, T, F],
where F is dimensionality of embeddings
"""
if emb_mat is None:
emb_mat = np.random.randn(n_characters, char_embedding_dim).astype(np.float32) / np.sqrt(char_embedding_dim)
else:
char_embedding_dim = emb_mat.shape[1]
char_emb_var = tf.Variable(emb_mat, trainable=True)
with tf.variable_scope('Char_Emb_Network'):
# Character embedding layer
c_emb = tf.nn.embedding_lookup(char_emb_var, char_placeholder)
# Character embedding network
conv_results_list = []
for filter_width in filter_widths:
conv_results_list.append(tf.layers.conv2d(c_emb,
char_embedding_dim,
(1, filter_width),
padding='same',
kernel_initializer=INITIALIZER))
units = tf.concat(conv_results_list, axis=3)
units = tf.reduce_max(units, axis=2)
if highway_on_top:
sigmoid_gate = tf.layers.dense(units,
1,
activation=tf.sigmoid,
kernel_initializer=INITIALIZER,
kernel_regularizer=tf.nn.l2_loss)
deeper_units = tf.layers.dense(units,
tf.shape(units)[-1],
kernel_initializer=INITIALIZER,
kernel_regularizer=tf.nn.l2_loss)
units = sigmoid_gate * units + (1 - sigmoid_gate) * deeper_units
units = tf.nn.relu(units)
return units
|
def character_embedding_network(char_placeholder: tf.Tensor,
n_characters: int = None,
emb_mat: np.array = None,
char_embedding_dim: int = None,
filter_widths=(3, 4, 5, 7),
highway_on_top=False):
""" Characters to vector. Every sequence of characters (token)
is embedded to vector space with dimensionality char_embedding_dim
Convolution plus max_pooling is used to obtain vector representations
of words.
Args:
char_placeholder: placeholder of int32 type with dimensionality [B, T, C]
B - batch size (can be None)
T - Number of tokens (can be None)
C - number of characters (can be None)
n_characters: total number of unique characters
emb_mat: if n_characters is not provided the emb_mat should be provided
it is a numpy array with dimensions [V, E], where V - vocabulary size
and E - embeddings dimension
char_embedding_dim: dimensionality of characters embeddings
filter_widths: array of width of kernel in convolutional embedding network
used in parallel
Returns:
embeddings: tf.Tensor with dimensionality [B, T, F],
where F is dimensionality of embeddings
"""
if emb_mat is None:
emb_mat = np.random.randn(n_characters, char_embedding_dim).astype(np.float32) / np.sqrt(char_embedding_dim)
else:
char_embedding_dim = emb_mat.shape[1]
char_emb_var = tf.Variable(emb_mat, trainable=True)
with tf.variable_scope('Char_Emb_Network'):
# Character embedding layer
c_emb = tf.nn.embedding_lookup(char_emb_var, char_placeholder)
# Character embedding network
conv_results_list = []
for filter_width in filter_widths:
conv_results_list.append(tf.layers.conv2d(c_emb,
char_embedding_dim,
(1, filter_width),
padding='same',
kernel_initializer=INITIALIZER))
units = tf.concat(conv_results_list, axis=3)
units = tf.reduce_max(units, axis=2)
if highway_on_top:
sigmoid_gate = tf.layers.dense(units,
1,
activation=tf.sigmoid,
kernel_initializer=INITIALIZER,
kernel_regularizer=tf.nn.l2_loss)
deeper_units = tf.layers.dense(units,
tf.shape(units)[-1],
kernel_initializer=INITIALIZER,
kernel_regularizer=tf.nn.l2_loss)
units = sigmoid_gate * units + (1 - sigmoid_gate) * deeper_units
units = tf.nn.relu(units)
return units
|
[
"Characters",
"to",
"vector",
".",
"Every",
"sequence",
"of",
"characters",
"(",
"token",
")",
"is",
"embedded",
"to",
"vector",
"space",
"with",
"dimensionality",
"char_embedding_dim",
"Convolution",
"plus",
"max_pooling",
"is",
"used",
"to",
"obtain",
"vector",
"representations",
"of",
"words",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L371-L430
|
[
"def",
"character_embedding_network",
"(",
"char_placeholder",
":",
"tf",
".",
"Tensor",
",",
"n_characters",
":",
"int",
"=",
"None",
",",
"emb_mat",
":",
"np",
".",
"array",
"=",
"None",
",",
"char_embedding_dim",
":",
"int",
"=",
"None",
",",
"filter_widths",
"=",
"(",
"3",
",",
"4",
",",
"5",
",",
"7",
")",
",",
"highway_on_top",
"=",
"False",
")",
":",
"if",
"emb_mat",
"is",
"None",
":",
"emb_mat",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"n_characters",
",",
"char_embedding_dim",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"/",
"np",
".",
"sqrt",
"(",
"char_embedding_dim",
")",
"else",
":",
"char_embedding_dim",
"=",
"emb_mat",
".",
"shape",
"[",
"1",
"]",
"char_emb_var",
"=",
"tf",
".",
"Variable",
"(",
"emb_mat",
",",
"trainable",
"=",
"True",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"'Char_Emb_Network'",
")",
":",
"# Character embedding layer",
"c_emb",
"=",
"tf",
".",
"nn",
".",
"embedding_lookup",
"(",
"char_emb_var",
",",
"char_placeholder",
")",
"# Character embedding network",
"conv_results_list",
"=",
"[",
"]",
"for",
"filter_width",
"in",
"filter_widths",
":",
"conv_results_list",
".",
"append",
"(",
"tf",
".",
"layers",
".",
"conv2d",
"(",
"c_emb",
",",
"char_embedding_dim",
",",
"(",
"1",
",",
"filter_width",
")",
",",
"padding",
"=",
"'same'",
",",
"kernel_initializer",
"=",
"INITIALIZER",
")",
")",
"units",
"=",
"tf",
".",
"concat",
"(",
"conv_results_list",
",",
"axis",
"=",
"3",
")",
"units",
"=",
"tf",
".",
"reduce_max",
"(",
"units",
",",
"axis",
"=",
"2",
")",
"if",
"highway_on_top",
":",
"sigmoid_gate",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"units",
",",
"1",
",",
"activation",
"=",
"tf",
".",
"sigmoid",
",",
"kernel_initializer",
"=",
"INITIALIZER",
",",
"kernel_regularizer",
"=",
"tf",
".",
"nn",
".",
"l2_loss",
")",
"deeper_units",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"units",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"-",
"1",
"]",
",",
"kernel_initializer",
"=",
"INITIALIZER",
",",
"kernel_regularizer",
"=",
"tf",
".",
"nn",
".",
"l2_loss",
")",
"units",
"=",
"sigmoid_gate",
"*",
"units",
"+",
"(",
"1",
"-",
"sigmoid_gate",
")",
"*",
"deeper_units",
"units",
"=",
"tf",
".",
"nn",
".",
"relu",
"(",
"units",
")",
"return",
"units"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
expand_tile
|
Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2
|
deeppavlov/core/layers/tf_layers.py
|
def expand_tile(units, axis):
"""Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2
"""
assert axis in (1, 2)
n_time_steps = tf.shape(units)[1]
repetitions = [1, 1, 1, 1]
repetitions[axis] = n_time_steps
return tf.tile(tf.expand_dims(units, axis), repetitions)
|
def expand_tile(units, axis):
"""Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2
"""
assert axis in (1, 2)
n_time_steps = tf.shape(units)[1]
repetitions = [1, 1, 1, 1]
repetitions[axis] = n_time_steps
return tf.tile(tf.expand_dims(units, axis), repetitions)
|
[
"Expand",
"and",
"tile",
"tensor",
"along",
"given",
"axis",
"Args",
":",
"units",
":",
"tf",
"tensor",
"with",
"dimensions",
"[",
"batch_size",
"time_steps",
"n_input_features",
"]",
"axis",
":",
"axis",
"along",
"which",
"expand",
"and",
"tile",
".",
"Must",
"be",
"1",
"or",
"2"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L433-L444
|
[
"def",
"expand_tile",
"(",
"units",
",",
"axis",
")",
":",
"assert",
"axis",
"in",
"(",
"1",
",",
"2",
")",
"n_time_steps",
"=",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"1",
"]",
"repetitions",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
"repetitions",
"[",
"axis",
"]",
"=",
"n_time_steps",
"return",
"tf",
".",
"tile",
"(",
"tf",
".",
"expand_dims",
"(",
"units",
",",
"axis",
")",
",",
"repetitions",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
additive_self_attention
|
Computes additive self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)>
v is a learnable vector of n_hidden dimensionality,
W_1 and W_2 are learnable [n_hidden, n_input_features] matrices
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
|
deeppavlov/core/layers/tf_layers.py
|
def additive_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
""" Computes additive self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)>
v is a learnable vector of n_hidden dimensionality,
W_1 and W_2 are learnable [n_hidden, n_input_features] matrices
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
"""
n_input_features = units.get_shape().as_list()[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
units_pairs = tf.concat([expand_tile(units, 1), expand_tile(units, 2)], 3)
query = tf.layers.dense(units_pairs, n_hidden, activation=tf.tanh, kernel_initializer=INITIALIZER())
attention = tf.nn.softmax(tf.layers.dense(query, 1), dim=2)
attended_units = tf.reduce_sum(attention * expand_tile(units, 1), axis=2)
output = tf.layers.dense(attended_units, n_output_features, activation, kernel_initializer=INITIALIZER())
return output
|
def additive_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
""" Computes additive self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)>
v is a learnable vector of n_hidden dimensionality,
W_1 and W_2 are learnable [n_hidden, n_input_features] matrices
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
"""
n_input_features = units.get_shape().as_list()[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
units_pairs = tf.concat([expand_tile(units, 1), expand_tile(units, 2)], 3)
query = tf.layers.dense(units_pairs, n_hidden, activation=tf.tanh, kernel_initializer=INITIALIZER())
attention = tf.nn.softmax(tf.layers.dense(query, 1), dim=2)
attended_units = tf.reduce_sum(attention * expand_tile(units, 1), axis=2)
output = tf.layers.dense(attended_units, n_output_features, activation, kernel_initializer=INITIALIZER())
return output
|
[
"Computes",
"additive",
"self",
"attention",
"for",
"time",
"series",
"of",
"vectors",
"(",
"with",
"batch",
"dimension",
")",
"the",
"formula",
":",
"score",
"(",
"h_i",
"h_j",
")",
"=",
"<v",
"tanh",
"(",
"W_1",
"h_i",
"+",
"W_2",
"h_j",
")",
">",
"v",
"is",
"a",
"learnable",
"vector",
"of",
"n_hidden",
"dimensionality",
"W_1",
"and",
"W_2",
"are",
"learnable",
"[",
"n_hidden",
"n_input_features",
"]",
"matrices"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L447-L472
|
[
"def",
"additive_self_attention",
"(",
"units",
",",
"n_hidden",
"=",
"None",
",",
"n_output_features",
"=",
"None",
",",
"activation",
"=",
"None",
")",
":",
"n_input_features",
"=",
"units",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"2",
"]",
"if",
"n_hidden",
"is",
"None",
":",
"n_hidden",
"=",
"n_input_features",
"if",
"n_output_features",
"is",
"None",
":",
"n_output_features",
"=",
"n_input_features",
"units_pairs",
"=",
"tf",
".",
"concat",
"(",
"[",
"expand_tile",
"(",
"units",
",",
"1",
")",
",",
"expand_tile",
"(",
"units",
",",
"2",
")",
"]",
",",
"3",
")",
"query",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"units_pairs",
",",
"n_hidden",
",",
"activation",
"=",
"tf",
".",
"tanh",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"attention",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"tf",
".",
"layers",
".",
"dense",
"(",
"query",
",",
"1",
")",
",",
"dim",
"=",
"2",
")",
"attended_units",
"=",
"tf",
".",
"reduce_sum",
"(",
"attention",
"*",
"expand_tile",
"(",
"units",
",",
"1",
")",
",",
"axis",
"=",
"2",
")",
"output",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"attended_units",
",",
"n_output_features",
",",
"activation",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"return",
"output"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
multiplicative_self_attention
|
Computes multiplicative self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <W_1 h_i, W_2 h_j>, W_1 and W_2 are learnable matrices
with dimensionality [n_hidden, n_input_features], where <a, b> stands for a and b
dot product
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
|
deeppavlov/core/layers/tf_layers.py
|
def multiplicative_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
""" Computes multiplicative self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <W_1 h_i, W_2 h_j>, W_1 and W_2 are learnable matrices
with dimensionality [n_hidden, n_input_features], where <a, b> stands for a and b
dot product
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
"""
n_input_features = units.get_shape().as_list()[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
queries = tf.layers.dense(expand_tile(units, 1), n_hidden, kernel_initializer=INITIALIZER())
keys = tf.layers.dense(expand_tile(units, 2), n_hidden, kernel_initializer=INITIALIZER())
scores = tf.reduce_sum(queries * keys, axis=3, keep_dims=True)
attention = tf.nn.softmax(scores, dim=2)
attended_units = tf.reduce_sum(attention * expand_tile(units, 1), axis=2)
output = tf.layers.dense(attended_units, n_output_features, activation, kernel_initializer=INITIALIZER())
return output
|
def multiplicative_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
""" Computes multiplicative self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <W_1 h_i, W_2 h_j>, W_1 and W_2 are learnable matrices
with dimensionality [n_hidden, n_input_features], where <a, b> stands for a and b
dot product
Args:
units: tf tensor with dimensionality [batch_size, time_steps, n_input_features]
n_hidden: number of units in hidden representation of similarity measure
n_output_features: number of features in output dense layer
activation: activation at the output
Returns:
output: self attended tensor with dimensionality [batch_size, time_steps, n_output_features]
"""
n_input_features = units.get_shape().as_list()[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
queries = tf.layers.dense(expand_tile(units, 1), n_hidden, kernel_initializer=INITIALIZER())
keys = tf.layers.dense(expand_tile(units, 2), n_hidden, kernel_initializer=INITIALIZER())
scores = tf.reduce_sum(queries * keys, axis=3, keep_dims=True)
attention = tf.nn.softmax(scores, dim=2)
attended_units = tf.reduce_sum(attention * expand_tile(units, 1), axis=2)
output = tf.layers.dense(attended_units, n_output_features, activation, kernel_initializer=INITIALIZER())
return output
|
[
"Computes",
"multiplicative",
"self",
"attention",
"for",
"time",
"series",
"of",
"vectors",
"(",
"with",
"batch",
"dimension",
")",
"the",
"formula",
":",
"score",
"(",
"h_i",
"h_j",
")",
"=",
"<W_1",
"h_i",
"W_2",
"h_j",
">",
"W_1",
"and",
"W_2",
"are",
"learnable",
"matrices",
"with",
"dimensionality",
"[",
"n_hidden",
"n_input_features",
"]",
"where",
"<a",
"b",
">",
"stands",
"for",
"a",
"and",
"b",
"dot",
"product"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L475-L501
|
[
"def",
"multiplicative_self_attention",
"(",
"units",
",",
"n_hidden",
"=",
"None",
",",
"n_output_features",
"=",
"None",
",",
"activation",
"=",
"None",
")",
":",
"n_input_features",
"=",
"units",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"2",
"]",
"if",
"n_hidden",
"is",
"None",
":",
"n_hidden",
"=",
"n_input_features",
"if",
"n_output_features",
"is",
"None",
":",
"n_output_features",
"=",
"n_input_features",
"queries",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"expand_tile",
"(",
"units",
",",
"1",
")",
",",
"n_hidden",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"keys",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"expand_tile",
"(",
"units",
",",
"2",
")",
",",
"n_hidden",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"scores",
"=",
"tf",
".",
"reduce_sum",
"(",
"queries",
"*",
"keys",
",",
"axis",
"=",
"3",
",",
"keep_dims",
"=",
"True",
")",
"attention",
"=",
"tf",
".",
"nn",
".",
"softmax",
"(",
"scores",
",",
"dim",
"=",
"2",
")",
"attended_units",
"=",
"tf",
".",
"reduce_sum",
"(",
"attention",
"*",
"expand_tile",
"(",
"units",
",",
"1",
")",
",",
"axis",
"=",
"2",
")",
"output",
"=",
"tf",
".",
"layers",
".",
"dense",
"(",
"attended_units",
",",
"n_output_features",
",",
"activation",
",",
"kernel_initializer",
"=",
"INITIALIZER",
"(",
")",
")",
"return",
"output"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
cudnn_gru
|
Fast CuDNN GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
n_layers: number of layers
input_initial_h: initial hidden state, tensor
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
|
deeppavlov/core/layers/tf_layers.py
|
def cudnn_gru(units, n_hidden, n_layers=1, trainable_initial_states=False,
seq_lengths=None, input_initial_h=None, name='cudnn_gru', reuse=False):
""" Fast CuDNN GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
n_layers: number of layers
input_initial_h: initial hidden state, tensor
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
"""
with tf.variable_scope(name, reuse=reuse):
gru = tf.contrib.cudnn_rnn.CudnnGRU(num_layers=n_layers,
num_units=n_hidden)
if trainable_initial_states:
init_h = tf.get_variable('init_h', [n_layers, 1, n_hidden])
init_h = tf.tile(init_h, (1, tf.shape(units)[0], 1))
else:
init_h = tf.zeros([n_layers, tf.shape(units)[0], n_hidden])
initial_h = input_initial_h or init_h
h, h_last = gru(tf.transpose(units, (1, 0, 2)), (initial_h, ))
h = tf.transpose(h, (1, 0, 2))
h_last = tf.squeeze(h_last, axis=0)[-1] # extract last layer state
# Extract last states if they are provided
if seq_lengths is not None:
indices = tf.stack([tf.range(tf.shape(h)[0]), seq_lengths-1], axis=1)
h_last = tf.gather_nd(h, indices)
return h, h_last
|
def cudnn_gru(units, n_hidden, n_layers=1, trainable_initial_states=False,
seq_lengths=None, input_initial_h=None, name='cudnn_gru', reuse=False):
""" Fast CuDNN GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
n_layers: number of layers
input_initial_h: initial hidden state, tensor
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
"""
with tf.variable_scope(name, reuse=reuse):
gru = tf.contrib.cudnn_rnn.CudnnGRU(num_layers=n_layers,
num_units=n_hidden)
if trainable_initial_states:
init_h = tf.get_variable('init_h', [n_layers, 1, n_hidden])
init_h = tf.tile(init_h, (1, tf.shape(units)[0], 1))
else:
init_h = tf.zeros([n_layers, tf.shape(units)[0], n_hidden])
initial_h = input_initial_h or init_h
h, h_last = gru(tf.transpose(units, (1, 0, 2)), (initial_h, ))
h = tf.transpose(h, (1, 0, 2))
h_last = tf.squeeze(h_last, axis=0)[-1] # extract last layer state
# Extract last states if they are provided
if seq_lengths is not None:
indices = tf.stack([tf.range(tf.shape(h)[0]), seq_lengths-1], axis=1)
h_last = tf.gather_nd(h, indices)
return h, h_last
|
[
"Fast",
"CuDNN",
"GRU",
"implementation"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L504-L549
|
[
"def",
"cudnn_gru",
"(",
"units",
",",
"n_hidden",
",",
"n_layers",
"=",
"1",
",",
"trainable_initial_states",
"=",
"False",
",",
"seq_lengths",
"=",
"None",
",",
"input_initial_h",
"=",
"None",
",",
"name",
"=",
"'cudnn_gru'",
",",
"reuse",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"gru",
"=",
"tf",
".",
"contrib",
".",
"cudnn_rnn",
".",
"CudnnGRU",
"(",
"num_layers",
"=",
"n_layers",
",",
"num_units",
"=",
"n_hidden",
")",
"if",
"trainable_initial_states",
":",
"init_h",
"=",
"tf",
".",
"get_variable",
"(",
"'init_h'",
",",
"[",
"n_layers",
",",
"1",
",",
"n_hidden",
"]",
")",
"init_h",
"=",
"tf",
".",
"tile",
"(",
"init_h",
",",
"(",
"1",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
"else",
":",
"init_h",
"=",
"tf",
".",
"zeros",
"(",
"[",
"n_layers",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"n_hidden",
"]",
")",
"initial_h",
"=",
"input_initial_h",
"or",
"init_h",
"h",
",",
"h_last",
"=",
"gru",
"(",
"tf",
".",
"transpose",
"(",
"units",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
")",
",",
"(",
"initial_h",
",",
")",
")",
"h",
"=",
"tf",
".",
"transpose",
"(",
"h",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
")",
"h_last",
"=",
"tf",
".",
"squeeze",
"(",
"h_last",
",",
"axis",
"=",
"0",
")",
"[",
"-",
"1",
"]",
"# extract last layer state",
"# Extract last states if they are provided",
"if",
"seq_lengths",
"is",
"not",
"None",
":",
"indices",
"=",
"tf",
".",
"stack",
"(",
"[",
"tf",
".",
"range",
"(",
"tf",
".",
"shape",
"(",
"h",
")",
"[",
"0",
"]",
")",
",",
"seq_lengths",
"-",
"1",
"]",
",",
"axis",
"=",
"1",
")",
"h_last",
"=",
"tf",
".",
"gather_nd",
"(",
"h",
",",
"indices",
")",
"return",
"h",
",",
"h_last"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
cudnn_compatible_gru
|
CuDNN Compatible GRU implementation.
It should be used to load models saved with CudnnGRUCell to run on CPU.
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
n_layers: number of layers
input_initial_h: initial hidden state, tensor
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
|
deeppavlov/core/layers/tf_layers.py
|
def cudnn_compatible_gru(units, n_hidden, n_layers=1, trainable_initial_states=False,
seq_lengths=None, input_initial_h=None, name='cudnn_gru', reuse=False):
""" CuDNN Compatible GRU implementation.
It should be used to load models saved with CudnnGRUCell to run on CPU.
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
n_layers: number of layers
input_initial_h: initial hidden state, tensor
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
"""
with tf.variable_scope(name, reuse=reuse):
if trainable_initial_states:
init_h = tf.get_variable('init_h', [n_layers, 1, n_hidden])
init_h = tf.tile(init_h, (1, tf.shape(units)[0], 1))
else:
init_h = tf.zeros([n_layers, tf.shape(units)[0], n_hidden])
initial_h = input_initial_h or init_h
with tf.variable_scope('cudnn_gru', reuse=reuse):
def single_cell(): return tf.contrib.cudnn_rnn.CudnnCompatibleGRUCell(n_hidden)
cell = tf.nn.rnn_cell.MultiRNNCell([single_cell() for _ in range(n_layers)])
units = tf.transpose(units, (1, 0, 2))
h, h_last = tf.nn.dynamic_rnn(cell=cell, inputs=units, time_major=True,
initial_state=tuple(tf.unstack(initial_h, axis=0)))
h = tf.transpose(h, (1, 0, 2))
h_last = h_last[-1] # h_last is tuple: n_layers x batch_size x n_hidden
# Extract last states if they are provided
if seq_lengths is not None:
indices = tf.stack([tf.range(tf.shape(h)[0]), seq_lengths-1], axis=1)
h_last = tf.gather_nd(h, indices)
return h, h_last
|
def cudnn_compatible_gru(units, n_hidden, n_layers=1, trainable_initial_states=False,
seq_lengths=None, input_initial_h=None, name='cudnn_gru', reuse=False):
""" CuDNN Compatible GRU implementation.
It should be used to load models saved with CudnnGRUCell to run on CPU.
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
n_layers: number of layers
input_initial_h: initial hidden state, tensor
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
"""
with tf.variable_scope(name, reuse=reuse):
if trainable_initial_states:
init_h = tf.get_variable('init_h', [n_layers, 1, n_hidden])
init_h = tf.tile(init_h, (1, tf.shape(units)[0], 1))
else:
init_h = tf.zeros([n_layers, tf.shape(units)[0], n_hidden])
initial_h = input_initial_h or init_h
with tf.variable_scope('cudnn_gru', reuse=reuse):
def single_cell(): return tf.contrib.cudnn_rnn.CudnnCompatibleGRUCell(n_hidden)
cell = tf.nn.rnn_cell.MultiRNNCell([single_cell() for _ in range(n_layers)])
units = tf.transpose(units, (1, 0, 2))
h, h_last = tf.nn.dynamic_rnn(cell=cell, inputs=units, time_major=True,
initial_state=tuple(tf.unstack(initial_h, axis=0)))
h = tf.transpose(h, (1, 0, 2))
h_last = h_last[-1] # h_last is tuple: n_layers x batch_size x n_hidden
# Extract last states if they are provided
if seq_lengths is not None:
indices = tf.stack([tf.range(tf.shape(h)[0]), seq_lengths-1], axis=1)
h_last = tf.gather_nd(h, indices)
return h, h_last
|
[
"CuDNN",
"Compatible",
"GRU",
"implementation",
".",
"It",
"should",
"be",
"used",
"to",
"load",
"models",
"saved",
"with",
"CudnnGRUCell",
"to",
"run",
"on",
"CPU",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L552-L604
|
[
"def",
"cudnn_compatible_gru",
"(",
"units",
",",
"n_hidden",
",",
"n_layers",
"=",
"1",
",",
"trainable_initial_states",
"=",
"False",
",",
"seq_lengths",
"=",
"None",
",",
"input_initial_h",
"=",
"None",
",",
"name",
"=",
"'cudnn_gru'",
",",
"reuse",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"if",
"trainable_initial_states",
":",
"init_h",
"=",
"tf",
".",
"get_variable",
"(",
"'init_h'",
",",
"[",
"n_layers",
",",
"1",
",",
"n_hidden",
"]",
")",
"init_h",
"=",
"tf",
".",
"tile",
"(",
"init_h",
",",
"(",
"1",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
"else",
":",
"init_h",
"=",
"tf",
".",
"zeros",
"(",
"[",
"n_layers",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"n_hidden",
"]",
")",
"initial_h",
"=",
"input_initial_h",
"or",
"init_h",
"with",
"tf",
".",
"variable_scope",
"(",
"'cudnn_gru'",
",",
"reuse",
"=",
"reuse",
")",
":",
"def",
"single_cell",
"(",
")",
":",
"return",
"tf",
".",
"contrib",
".",
"cudnn_rnn",
".",
"CudnnCompatibleGRUCell",
"(",
"n_hidden",
")",
"cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"MultiRNNCell",
"(",
"[",
"single_cell",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"n_layers",
")",
"]",
")",
"units",
"=",
"tf",
".",
"transpose",
"(",
"units",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
")",
"h",
",",
"h_last",
"=",
"tf",
".",
"nn",
".",
"dynamic_rnn",
"(",
"cell",
"=",
"cell",
",",
"inputs",
"=",
"units",
",",
"time_major",
"=",
"True",
",",
"initial_state",
"=",
"tuple",
"(",
"tf",
".",
"unstack",
"(",
"initial_h",
",",
"axis",
"=",
"0",
")",
")",
")",
"h",
"=",
"tf",
".",
"transpose",
"(",
"h",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
")",
"h_last",
"=",
"h_last",
"[",
"-",
"1",
"]",
"# h_last is tuple: n_layers x batch_size x n_hidden",
"# Extract last states if they are provided",
"if",
"seq_lengths",
"is",
"not",
"None",
":",
"indices",
"=",
"tf",
".",
"stack",
"(",
"[",
"tf",
".",
"range",
"(",
"tf",
".",
"shape",
"(",
"h",
")",
"[",
"0",
"]",
")",
",",
"seq_lengths",
"-",
"1",
"]",
",",
"axis",
"=",
"1",
")",
"h_last",
"=",
"tf",
".",
"gather_nd",
"(",
"h",
",",
"indices",
")",
"return",
"h",
",",
"h_last"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
cudnn_lstm
|
Fast CuDNN LSTM implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
initial_h: optional initial hidden state, masks trainable_initial_states
if provided
initial_c: optional initial cell state, masks trainable_initial_states
if provided
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
|
deeppavlov/core/layers/tf_layers.py
|
def cudnn_lstm(units, n_hidden, n_layers=1, trainable_initial_states=None, seq_lengths=None, initial_h=None,
initial_c=None, name='cudnn_lstm', reuse=False):
""" Fast CuDNN LSTM implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
initial_h: optional initial hidden state, masks trainable_initial_states
if provided
initial_c: optional initial cell state, masks trainable_initial_states
if provided
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
"""
with tf.variable_scope(name, reuse=reuse):
lstm = tf.contrib.cudnn_rnn.CudnnLSTM(num_layers=n_layers,
num_units=n_hidden)
if trainable_initial_states:
init_h = tf.get_variable('init_h', [n_layers, 1, n_hidden])
init_h = tf.tile(init_h, (1, tf.shape(units)[0], 1))
init_c = tf.get_variable('init_c', [n_layers, 1, n_hidden])
init_c = tf.tile(init_c, (1, tf.shape(units)[0], 1))
else:
init_h = init_c = tf.zeros([n_layers, tf.shape(units)[0], n_hidden])
initial_h = initial_h or init_h
initial_c = initial_c or init_c
h, (h_last, c_last) = lstm(tf.transpose(units, (1, 0, 2)), (initial_h, initial_c))
h = tf.transpose(h, (1, 0, 2))
h_last = h_last[-1]
c_last = c_last[-1]
# Extract last states if they are provided
if seq_lengths is not None:
indices = tf.stack([tf.range(tf.shape(h)[0]), seq_lengths-1], axis=1)
h_last = tf.gather_nd(h, indices)
return h, (h_last, c_last)
|
def cudnn_lstm(units, n_hidden, n_layers=1, trainable_initial_states=None, seq_lengths=None, initial_h=None,
initial_c=None, name='cudnn_lstm', reuse=False):
""" Fast CuDNN LSTM implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
initial_h: optional initial hidden state, masks trainable_initial_states
if provided
initial_c: optional initial cell state, masks trainable_initial_states
if provided
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
"""
with tf.variable_scope(name, reuse=reuse):
lstm = tf.contrib.cudnn_rnn.CudnnLSTM(num_layers=n_layers,
num_units=n_hidden)
if trainable_initial_states:
init_h = tf.get_variable('init_h', [n_layers, 1, n_hidden])
init_h = tf.tile(init_h, (1, tf.shape(units)[0], 1))
init_c = tf.get_variable('init_c', [n_layers, 1, n_hidden])
init_c = tf.tile(init_c, (1, tf.shape(units)[0], 1))
else:
init_h = init_c = tf.zeros([n_layers, tf.shape(units)[0], n_hidden])
initial_h = initial_h or init_h
initial_c = initial_c or init_c
h, (h_last, c_last) = lstm(tf.transpose(units, (1, 0, 2)), (initial_h, initial_c))
h = tf.transpose(h, (1, 0, 2))
h_last = h_last[-1]
c_last = c_last[-1]
# Extract last states if they are provided
if seq_lengths is not None:
indices = tf.stack([tf.range(tf.shape(h)[0]), seq_lengths-1], axis=1)
h_last = tf.gather_nd(h, indices)
return h, (h_last, c_last)
|
[
"Fast",
"CuDNN",
"LSTM",
"implementation"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L624-L678
|
[
"def",
"cudnn_lstm",
"(",
"units",
",",
"n_hidden",
",",
"n_layers",
"=",
"1",
",",
"trainable_initial_states",
"=",
"None",
",",
"seq_lengths",
"=",
"None",
",",
"initial_h",
"=",
"None",
",",
"initial_c",
"=",
"None",
",",
"name",
"=",
"'cudnn_lstm'",
",",
"reuse",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"lstm",
"=",
"tf",
".",
"contrib",
".",
"cudnn_rnn",
".",
"CudnnLSTM",
"(",
"num_layers",
"=",
"n_layers",
",",
"num_units",
"=",
"n_hidden",
")",
"if",
"trainable_initial_states",
":",
"init_h",
"=",
"tf",
".",
"get_variable",
"(",
"'init_h'",
",",
"[",
"n_layers",
",",
"1",
",",
"n_hidden",
"]",
")",
"init_h",
"=",
"tf",
".",
"tile",
"(",
"init_h",
",",
"(",
"1",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
"init_c",
"=",
"tf",
".",
"get_variable",
"(",
"'init_c'",
",",
"[",
"n_layers",
",",
"1",
",",
"n_hidden",
"]",
")",
"init_c",
"=",
"tf",
".",
"tile",
"(",
"init_c",
",",
"(",
"1",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
"else",
":",
"init_h",
"=",
"init_c",
"=",
"tf",
".",
"zeros",
"(",
"[",
"n_layers",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"n_hidden",
"]",
")",
"initial_h",
"=",
"initial_h",
"or",
"init_h",
"initial_c",
"=",
"initial_c",
"or",
"init_c",
"h",
",",
"(",
"h_last",
",",
"c_last",
")",
"=",
"lstm",
"(",
"tf",
".",
"transpose",
"(",
"units",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
")",
",",
"(",
"initial_h",
",",
"initial_c",
")",
")",
"h",
"=",
"tf",
".",
"transpose",
"(",
"h",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
")",
"h_last",
"=",
"h_last",
"[",
"-",
"1",
"]",
"c_last",
"=",
"c_last",
"[",
"-",
"1",
"]",
"# Extract last states if they are provided",
"if",
"seq_lengths",
"is",
"not",
"None",
":",
"indices",
"=",
"tf",
".",
"stack",
"(",
"[",
"tf",
".",
"range",
"(",
"tf",
".",
"shape",
"(",
"h",
")",
"[",
"0",
"]",
")",
",",
"seq_lengths",
"-",
"1",
"]",
",",
"axis",
"=",
"1",
")",
"h_last",
"=",
"tf",
".",
"gather_nd",
"(",
"h",
",",
"indices",
")",
"return",
"h",
",",
"(",
"h_last",
",",
"c_last",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
cudnn_compatible_lstm
|
CuDNN Compatible LSTM implementation.
It should be used to load models saved with CudnnLSTMCell to run on CPU.
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
initial_h: optional initial hidden state, masks trainable_initial_states
if provided
initial_c: optional initial cell state, masks trainable_initial_states
if provided
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
|
deeppavlov/core/layers/tf_layers.py
|
def cudnn_compatible_lstm(units, n_hidden, n_layers=1, trainable_initial_states=None, seq_lengths=None, initial_h=None,
initial_c=None, name='cudnn_lstm', reuse=False):
""" CuDNN Compatible LSTM implementation.
It should be used to load models saved with CudnnLSTMCell to run on CPU.
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
initial_h: optional initial hidden state, masks trainable_initial_states
if provided
initial_c: optional initial cell state, masks trainable_initial_states
if provided
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
"""
with tf.variable_scope(name, reuse=reuse):
if trainable_initial_states:
init_h = tf.get_variable('init_h', [n_layers, 1, n_hidden])
init_h = tf.tile(init_h, (1, tf.shape(units)[0], 1))
init_c = tf.get_variable('init_c', [n_layers, 1, n_hidden])
init_c = tf.tile(init_c, (1, tf.shape(units)[0], 1))
else:
init_h = init_c = tf.zeros([n_layers, tf.shape(units)[0], n_hidden])
initial_h = initial_h or init_h
initial_c = initial_c or init_c
with tf.variable_scope('cudnn_lstm', reuse=reuse):
def single_cell(): return tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell(n_hidden)
cell = tf.nn.rnn_cell.MultiRNNCell([single_cell() for _ in range(n_layers)])
units = tf.transpose(units, (1, 0, 2))
init = tuple([tf.nn.rnn_cell.LSTMStateTuple(ic, ih) for ih, ic in
zip(tf.unstack(initial_h, axis=0), tf.unstack(initial_c, axis=0))])
h, state = tf.nn.dynamic_rnn(cell=cell, inputs=units, time_major=True, initial_state=init)
h = tf.transpose(h, (1, 0, 2))
h_last = state[-1].h
c_last = state[-1].c
# Extract last states if they are provided
if seq_lengths is not None:
indices = tf.stack([tf.range(tf.shape(h)[0]), seq_lengths-1], axis=1)
h_last = tf.gather_nd(h, indices)
return h, (h_last, c_last)
|
def cudnn_compatible_lstm(units, n_hidden, n_layers=1, trainable_initial_states=None, seq_lengths=None, initial_h=None,
initial_c=None, name='cudnn_lstm', reuse=False):
""" CuDNN Compatible LSTM implementation.
It should be used to load models saved with CudnnLSTMCell to run on CPU.
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
seq_lengths: tensor of sequence lengths with dimension [B]
initial_h: optional initial hidden state, masks trainable_initial_states
if provided
initial_c: optional initial cell state, masks trainable_initial_states
if provided
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H]
where H - number of hidden units
"""
with tf.variable_scope(name, reuse=reuse):
if trainable_initial_states:
init_h = tf.get_variable('init_h', [n_layers, 1, n_hidden])
init_h = tf.tile(init_h, (1, tf.shape(units)[0], 1))
init_c = tf.get_variable('init_c', [n_layers, 1, n_hidden])
init_c = tf.tile(init_c, (1, tf.shape(units)[0], 1))
else:
init_h = init_c = tf.zeros([n_layers, tf.shape(units)[0], n_hidden])
initial_h = initial_h or init_h
initial_c = initial_c or init_c
with tf.variable_scope('cudnn_lstm', reuse=reuse):
def single_cell(): return tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell(n_hidden)
cell = tf.nn.rnn_cell.MultiRNNCell([single_cell() for _ in range(n_layers)])
units = tf.transpose(units, (1, 0, 2))
init = tuple([tf.nn.rnn_cell.LSTMStateTuple(ic, ih) for ih, ic in
zip(tf.unstack(initial_h, axis=0), tf.unstack(initial_c, axis=0))])
h, state = tf.nn.dynamic_rnn(cell=cell, inputs=units, time_major=True, initial_state=init)
h = tf.transpose(h, (1, 0, 2))
h_last = state[-1].h
c_last = state[-1].c
# Extract last states if they are provided
if seq_lengths is not None:
indices = tf.stack([tf.range(tf.shape(h)[0]), seq_lengths-1], axis=1)
h_last = tf.gather_nd(h, indices)
return h, (h_last, c_last)
|
[
"CuDNN",
"Compatible",
"LSTM",
"implementation",
".",
"It",
"should",
"be",
"used",
"to",
"load",
"models",
"saved",
"with",
"CudnnLSTMCell",
"to",
"run",
"on",
"CPU",
"."
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L681-L746
|
[
"def",
"cudnn_compatible_lstm",
"(",
"units",
",",
"n_hidden",
",",
"n_layers",
"=",
"1",
",",
"trainable_initial_states",
"=",
"None",
",",
"seq_lengths",
"=",
"None",
",",
"initial_h",
"=",
"None",
",",
"initial_c",
"=",
"None",
",",
"name",
"=",
"'cudnn_lstm'",
",",
"reuse",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"if",
"trainable_initial_states",
":",
"init_h",
"=",
"tf",
".",
"get_variable",
"(",
"'init_h'",
",",
"[",
"n_layers",
",",
"1",
",",
"n_hidden",
"]",
")",
"init_h",
"=",
"tf",
".",
"tile",
"(",
"init_h",
",",
"(",
"1",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
"init_c",
"=",
"tf",
".",
"get_variable",
"(",
"'init_c'",
",",
"[",
"n_layers",
",",
"1",
",",
"n_hidden",
"]",
")",
"init_c",
"=",
"tf",
".",
"tile",
"(",
"init_c",
",",
"(",
"1",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"1",
")",
")",
"else",
":",
"init_h",
"=",
"init_c",
"=",
"tf",
".",
"zeros",
"(",
"[",
"n_layers",
",",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
",",
"n_hidden",
"]",
")",
"initial_h",
"=",
"initial_h",
"or",
"init_h",
"initial_c",
"=",
"initial_c",
"or",
"init_c",
"with",
"tf",
".",
"variable_scope",
"(",
"'cudnn_lstm'",
",",
"reuse",
"=",
"reuse",
")",
":",
"def",
"single_cell",
"(",
")",
":",
"return",
"tf",
".",
"contrib",
".",
"cudnn_rnn",
".",
"CudnnCompatibleLSTMCell",
"(",
"n_hidden",
")",
"cell",
"=",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"MultiRNNCell",
"(",
"[",
"single_cell",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"n_layers",
")",
"]",
")",
"units",
"=",
"tf",
".",
"transpose",
"(",
"units",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
")",
"init",
"=",
"tuple",
"(",
"[",
"tf",
".",
"nn",
".",
"rnn_cell",
".",
"LSTMStateTuple",
"(",
"ic",
",",
"ih",
")",
"for",
"ih",
",",
"ic",
"in",
"zip",
"(",
"tf",
".",
"unstack",
"(",
"initial_h",
",",
"axis",
"=",
"0",
")",
",",
"tf",
".",
"unstack",
"(",
"initial_c",
",",
"axis",
"=",
"0",
")",
")",
"]",
")",
"h",
",",
"state",
"=",
"tf",
".",
"nn",
".",
"dynamic_rnn",
"(",
"cell",
"=",
"cell",
",",
"inputs",
"=",
"units",
",",
"time_major",
"=",
"True",
",",
"initial_state",
"=",
"init",
")",
"h",
"=",
"tf",
".",
"transpose",
"(",
"h",
",",
"(",
"1",
",",
"0",
",",
"2",
")",
")",
"h_last",
"=",
"state",
"[",
"-",
"1",
"]",
".",
"h",
"c_last",
"=",
"state",
"[",
"-",
"1",
"]",
".",
"c",
"# Extract last states if they are provided",
"if",
"seq_lengths",
"is",
"not",
"None",
":",
"indices",
"=",
"tf",
".",
"stack",
"(",
"[",
"tf",
".",
"range",
"(",
"tf",
".",
"shape",
"(",
"h",
")",
"[",
"0",
"]",
")",
",",
"seq_lengths",
"-",
"1",
"]",
",",
"axis",
"=",
"1",
")",
"h_last",
"=",
"tf",
".",
"gather_nd",
"(",
"h",
",",
"indices",
")",
"return",
"h",
",",
"(",
"h_last",
",",
"c_last",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
cudnn_bi_gru
|
Fast CuDNN Bi-GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
|
deeppavlov/core/layers/tf_layers.py
|
def cudnn_bi_gru(units,
n_hidden,
seq_lengths=None,
n_layers=1,
trainable_initial_states=False,
name='cudnn_bi_gru',
reuse=False):
""" Fast CuDNN Bi-GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
"""
with tf.variable_scope(name, reuse=reuse):
if seq_lengths is None:
seq_lengths = tf.ones([tf.shape(units)[0]], dtype=tf.int32) * tf.shape(units)[1]
with tf.variable_scope('Forward'):
h_fw, h_last_fw = cudnn_gru_wrapper(units,
n_hidden,
n_layers=n_layers,
trainable_initial_states=trainable_initial_states,
seq_lengths=seq_lengths,
reuse=reuse)
with tf.variable_scope('Backward'):
reversed_units = tf.reverse_sequence(units, seq_lengths=seq_lengths, seq_dim=1, batch_dim=0)
h_bw, h_last_bw = cudnn_gru_wrapper(reversed_units,
n_hidden,
n_layers=n_layers,
trainable_initial_states=trainable_initial_states,
seq_lengths=seq_lengths,
reuse=reuse)
h_bw = tf.reverse_sequence(h_bw, seq_lengths=seq_lengths, seq_dim=1, batch_dim=0)
return (h_fw, h_bw), (h_last_fw, h_last_bw)
|
def cudnn_bi_gru(units,
n_hidden,
seq_lengths=None,
n_layers=1,
trainable_initial_states=False,
name='cudnn_bi_gru',
reuse=False):
""" Fast CuDNN Bi-GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
"""
with tf.variable_scope(name, reuse=reuse):
if seq_lengths is None:
seq_lengths = tf.ones([tf.shape(units)[0]], dtype=tf.int32) * tf.shape(units)[1]
with tf.variable_scope('Forward'):
h_fw, h_last_fw = cudnn_gru_wrapper(units,
n_hidden,
n_layers=n_layers,
trainable_initial_states=trainable_initial_states,
seq_lengths=seq_lengths,
reuse=reuse)
with tf.variable_scope('Backward'):
reversed_units = tf.reverse_sequence(units, seq_lengths=seq_lengths, seq_dim=1, batch_dim=0)
h_bw, h_last_bw = cudnn_gru_wrapper(reversed_units,
n_hidden,
n_layers=n_layers,
trainable_initial_states=trainable_initial_states,
seq_lengths=seq_lengths,
reuse=reuse)
h_bw = tf.reverse_sequence(h_bw, seq_lengths=seq_lengths, seq_dim=1, batch_dim=0)
return (h_fw, h_bw), (h_last_fw, h_last_bw)
|
[
"Fast",
"CuDNN",
"Bi",
"-",
"GRU",
"implementation"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L766-L817
|
[
"def",
"cudnn_bi_gru",
"(",
"units",
",",
"n_hidden",
",",
"seq_lengths",
"=",
"None",
",",
"n_layers",
"=",
"1",
",",
"trainable_initial_states",
"=",
"False",
",",
"name",
"=",
"'cudnn_bi_gru'",
",",
"reuse",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"if",
"seq_lengths",
"is",
"None",
":",
"seq_lengths",
"=",
"tf",
".",
"ones",
"(",
"[",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
"]",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"*",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"1",
"]",
"with",
"tf",
".",
"variable_scope",
"(",
"'Forward'",
")",
":",
"h_fw",
",",
"h_last_fw",
"=",
"cudnn_gru_wrapper",
"(",
"units",
",",
"n_hidden",
",",
"n_layers",
"=",
"n_layers",
",",
"trainable_initial_states",
"=",
"trainable_initial_states",
",",
"seq_lengths",
"=",
"seq_lengths",
",",
"reuse",
"=",
"reuse",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"'Backward'",
")",
":",
"reversed_units",
"=",
"tf",
".",
"reverse_sequence",
"(",
"units",
",",
"seq_lengths",
"=",
"seq_lengths",
",",
"seq_dim",
"=",
"1",
",",
"batch_dim",
"=",
"0",
")",
"h_bw",
",",
"h_last_bw",
"=",
"cudnn_gru_wrapper",
"(",
"reversed_units",
",",
"n_hidden",
",",
"n_layers",
"=",
"n_layers",
",",
"trainable_initial_states",
"=",
"trainable_initial_states",
",",
"seq_lengths",
"=",
"seq_lengths",
",",
"reuse",
"=",
"reuse",
")",
"h_bw",
"=",
"tf",
".",
"reverse_sequence",
"(",
"h_bw",
",",
"seq_lengths",
"=",
"seq_lengths",
",",
"seq_dim",
"=",
"1",
",",
"batch_dim",
"=",
"0",
")",
"return",
"(",
"h_fw",
",",
"h_bw",
")",
",",
"(",
"h_last_fw",
",",
"h_last_bw",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
cudnn_bi_lstm
|
Fast CuDNN Bi-LSTM implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
|
deeppavlov/core/layers/tf_layers.py
|
def cudnn_bi_lstm(units,
n_hidden,
seq_lengths=None,
n_layers=1,
trainable_initial_states=False,
name='cudnn_bi_gru',
reuse=False):
""" Fast CuDNN Bi-LSTM implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
"""
with tf.variable_scope(name, reuse=reuse):
if seq_lengths is None:
seq_lengths = tf.ones([tf.shape(units)[0]], dtype=tf.int32) * tf.shape(units)[1]
with tf.variable_scope('Forward'):
h_fw, (h_fw_last, c_fw_last) = cudnn_lstm_wrapper(units,
n_hidden,
n_layers=n_layers,
trainable_initial_states=trainable_initial_states,
seq_lengths=seq_lengths)
with tf.variable_scope('Backward'):
reversed_units = tf.reverse_sequence(units, seq_lengths=seq_lengths, seq_dim=1, batch_dim=0)
h_bw, (h_bw_last, c_bw_last) = cudnn_lstm_wrapper(reversed_units,
n_hidden,
n_layers=n_layers,
trainable_initial_states=trainable_initial_states,
seq_lengths=seq_lengths)
h_bw = tf.reverse_sequence(h_bw, seq_lengths=seq_lengths, seq_dim=1, batch_dim=0)
return (h_fw, h_bw), ((h_fw_last, c_fw_last), (h_bw_last, c_bw_last))
|
def cudnn_bi_lstm(units,
n_hidden,
seq_lengths=None,
n_layers=1,
trainable_initial_states=False,
name='cudnn_bi_gru',
reuse=False):
""" Fast CuDNN Bi-LSTM implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_layers: number of layers
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse:whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x F]
h_last - last hidden state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
c_last - last cell state, tf.Tensor with dimensionality [B x H * 2]
where H - number of hidden units
"""
with tf.variable_scope(name, reuse=reuse):
if seq_lengths is None:
seq_lengths = tf.ones([tf.shape(units)[0]], dtype=tf.int32) * tf.shape(units)[1]
with tf.variable_scope('Forward'):
h_fw, (h_fw_last, c_fw_last) = cudnn_lstm_wrapper(units,
n_hidden,
n_layers=n_layers,
trainable_initial_states=trainable_initial_states,
seq_lengths=seq_lengths)
with tf.variable_scope('Backward'):
reversed_units = tf.reverse_sequence(units, seq_lengths=seq_lengths, seq_dim=1, batch_dim=0)
h_bw, (h_bw_last, c_bw_last) = cudnn_lstm_wrapper(reversed_units,
n_hidden,
n_layers=n_layers,
trainable_initial_states=trainable_initial_states,
seq_lengths=seq_lengths)
h_bw = tf.reverse_sequence(h_bw, seq_lengths=seq_lengths, seq_dim=1, batch_dim=0)
return (h_fw, h_bw), ((h_fw_last, c_fw_last), (h_bw_last, c_bw_last))
|
[
"Fast",
"CuDNN",
"Bi",
"-",
"LSTM",
"implementation"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L820-L869
|
[
"def",
"cudnn_bi_lstm",
"(",
"units",
",",
"n_hidden",
",",
"seq_lengths",
"=",
"None",
",",
"n_layers",
"=",
"1",
",",
"trainable_initial_states",
"=",
"False",
",",
"name",
"=",
"'cudnn_bi_gru'",
",",
"reuse",
"=",
"False",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"if",
"seq_lengths",
"is",
"None",
":",
"seq_lengths",
"=",
"tf",
".",
"ones",
"(",
"[",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
"]",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"*",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"1",
"]",
"with",
"tf",
".",
"variable_scope",
"(",
"'Forward'",
")",
":",
"h_fw",
",",
"(",
"h_fw_last",
",",
"c_fw_last",
")",
"=",
"cudnn_lstm_wrapper",
"(",
"units",
",",
"n_hidden",
",",
"n_layers",
"=",
"n_layers",
",",
"trainable_initial_states",
"=",
"trainable_initial_states",
",",
"seq_lengths",
"=",
"seq_lengths",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"'Backward'",
")",
":",
"reversed_units",
"=",
"tf",
".",
"reverse_sequence",
"(",
"units",
",",
"seq_lengths",
"=",
"seq_lengths",
",",
"seq_dim",
"=",
"1",
",",
"batch_dim",
"=",
"0",
")",
"h_bw",
",",
"(",
"h_bw_last",
",",
"c_bw_last",
")",
"=",
"cudnn_lstm_wrapper",
"(",
"reversed_units",
",",
"n_hidden",
",",
"n_layers",
"=",
"n_layers",
",",
"trainable_initial_states",
"=",
"trainable_initial_states",
",",
"seq_lengths",
"=",
"seq_lengths",
")",
"h_bw",
"=",
"tf",
".",
"reverse_sequence",
"(",
"h_bw",
",",
"seq_lengths",
"=",
"seq_lengths",
",",
"seq_dim",
"=",
"1",
",",
"batch_dim",
"=",
"0",
")",
"return",
"(",
"h_fw",
",",
"h_bw",
")",
",",
"(",
"(",
"h_fw_last",
",",
"c_fw_last",
")",
",",
"(",
"h_bw_last",
",",
"c_bw_last",
")",
")"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
test
|
cudnn_stacked_bi_gru
|
Fast CuDNN Stacked Bi-GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_stacks: number of stacked Bi-GRU
keep_prob: dropout keep_prob between Bi-GRUs (intra-layer dropout)
concat_stacked_outputs: return last Bi-GRU output or concat outputs from every Bi-GRU,
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse: whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x ((n_hidden * 2) * n_stacks)]
|
deeppavlov/core/layers/tf_layers.py
|
def cudnn_stacked_bi_gru(units,
n_hidden,
seq_lengths=None,
n_stacks=2,
keep_prob=1.0,
concat_stacked_outputs=False,
trainable_initial_states=False,
name='cudnn_stacked_bi_gru',
reuse=False):
""" Fast CuDNN Stacked Bi-GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_stacks: number of stacked Bi-GRU
keep_prob: dropout keep_prob between Bi-GRUs (intra-layer dropout)
concat_stacked_outputs: return last Bi-GRU output or concat outputs from every Bi-GRU,
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse: whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x ((n_hidden * 2) * n_stacks)]
"""
if seq_lengths is None:
seq_lengths = tf.ones([tf.shape(units)[0]], dtype=tf.int32) * tf.shape(units)[1]
outputs = [units]
with tf.variable_scope(name, reuse=reuse):
for n in range(n_stacks):
if n == 0:
inputs = outputs[-1]
else:
inputs = variational_dropout(outputs[-1], keep_prob=keep_prob)
(h_fw, h_bw), _ = cudnn_bi_gru(inputs, n_hidden, seq_lengths,
n_layers=1,
trainable_initial_states=trainable_initial_states,
name='{}_cudnn_bi_gru'.format(n),
reuse=reuse)
outputs.append(tf.concat([h_fw, h_bw], axis=2))
if concat_stacked_outputs:
return tf.concat(outputs[1:], axis=2)
return outputs[-1]
|
def cudnn_stacked_bi_gru(units,
n_hidden,
seq_lengths=None,
n_stacks=2,
keep_prob=1.0,
concat_stacked_outputs=False,
trainable_initial_states=False,
name='cudnn_stacked_bi_gru',
reuse=False):
""" Fast CuDNN Stacked Bi-GRU implementation
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dimensionality of hidden state
seq_lengths: number of tokens in each sample in the batch
n_stacks: number of stacked Bi-GRU
keep_prob: dropout keep_prob between Bi-GRUs (intra-layer dropout)
concat_stacked_outputs: return last Bi-GRU output or concat outputs from every Bi-GRU,
trainable_initial_states: whether to create a special trainable variable
to initialize the hidden states of the network or use just zeros
name: name of the variable scope to use
reuse: whether to reuse already initialized variable
Returns:
h - all hidden states along T dimension,
tf.Tensor with dimensionality [B x T x ((n_hidden * 2) * n_stacks)]
"""
if seq_lengths is None:
seq_lengths = tf.ones([tf.shape(units)[0]], dtype=tf.int32) * tf.shape(units)[1]
outputs = [units]
with tf.variable_scope(name, reuse=reuse):
for n in range(n_stacks):
if n == 0:
inputs = outputs[-1]
else:
inputs = variational_dropout(outputs[-1], keep_prob=keep_prob)
(h_fw, h_bw), _ = cudnn_bi_gru(inputs, n_hidden, seq_lengths,
n_layers=1,
trainable_initial_states=trainable_initial_states,
name='{}_cudnn_bi_gru'.format(n),
reuse=reuse)
outputs.append(tf.concat([h_fw, h_bw], axis=2))
if concat_stacked_outputs:
return tf.concat(outputs[1:], axis=2)
return outputs[-1]
|
[
"Fast",
"CuDNN",
"Stacked",
"Bi",
"-",
"GRU",
"implementation"
] |
deepmipt/DeepPavlov
|
python
|
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/layers/tf_layers.py#L872-L927
|
[
"def",
"cudnn_stacked_bi_gru",
"(",
"units",
",",
"n_hidden",
",",
"seq_lengths",
"=",
"None",
",",
"n_stacks",
"=",
"2",
",",
"keep_prob",
"=",
"1.0",
",",
"concat_stacked_outputs",
"=",
"False",
",",
"trainable_initial_states",
"=",
"False",
",",
"name",
"=",
"'cudnn_stacked_bi_gru'",
",",
"reuse",
"=",
"False",
")",
":",
"if",
"seq_lengths",
"is",
"None",
":",
"seq_lengths",
"=",
"tf",
".",
"ones",
"(",
"[",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"0",
"]",
"]",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"*",
"tf",
".",
"shape",
"(",
"units",
")",
"[",
"1",
"]",
"outputs",
"=",
"[",
"units",
"]",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"reuse",
")",
":",
"for",
"n",
"in",
"range",
"(",
"n_stacks",
")",
":",
"if",
"n",
"==",
"0",
":",
"inputs",
"=",
"outputs",
"[",
"-",
"1",
"]",
"else",
":",
"inputs",
"=",
"variational_dropout",
"(",
"outputs",
"[",
"-",
"1",
"]",
",",
"keep_prob",
"=",
"keep_prob",
")",
"(",
"h_fw",
",",
"h_bw",
")",
",",
"_",
"=",
"cudnn_bi_gru",
"(",
"inputs",
",",
"n_hidden",
",",
"seq_lengths",
",",
"n_layers",
"=",
"1",
",",
"trainable_initial_states",
"=",
"trainable_initial_states",
",",
"name",
"=",
"'{}_cudnn_bi_gru'",
".",
"format",
"(",
"n",
")",
",",
"reuse",
"=",
"reuse",
")",
"outputs",
".",
"append",
"(",
"tf",
".",
"concat",
"(",
"[",
"h_fw",
",",
"h_bw",
"]",
",",
"axis",
"=",
"2",
")",
")",
"if",
"concat_stacked_outputs",
":",
"return",
"tf",
".",
"concat",
"(",
"outputs",
"[",
"1",
":",
"]",
",",
"axis",
"=",
"2",
")",
"return",
"outputs",
"[",
"-",
"1",
"]"
] |
f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.