_id stringlengths 98 184 | text stringlengths 91 10.9k |
|---|---|
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L732-L751 | def get_config(self):
"""
"""
config = {
'event_shape': self._event_shape,
'convert_to_tensor_fn': _serialize(self._convert_to_tensor_fn),
'sample_dtype': self._sample_dtype,
'validate_args': self._validate_args
}
base_config = super(IndependentBernoulli, self).get_co... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L144-L152 | def set_running_std(self, running_std):
"""
"""
callBigDlFunc(self.bigdl_type, "setRunningStd",
self.value, JTensor.from_ndarray(running_std))
return self |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/qubole_hook.py#L147-L162 | def kill(self, ti):
"""
"""
if self.cmd is None:
if not ti and not self.task_instance:
raise Exception("Unable to cancel Qubole Command, context is unavailable!")
elif not ti:
ti = self.task_instance
cmd_id = ti.xcom_pu... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L66-L71 | def make_name(super_name, default_super_name, sub_name):
""""""
name = super_name if super_name is not None else default_super_name
if sub_name is not None:
name += '_' + sub_name
return name |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/webhdfs_hook.py#L106-L132 | def load_file(self, source, destination, overwrite=True, parallelism=1, **kwargs):
"""
conn = self.get_conn()
conn.upload(hdfs_path=destination,
local_path=source,
overwrite=overwrite,
n_threads=parallelism,
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/joint_distribution_named.py#L245-L267 | def _prob_chain_rule_flatten(named_makers):
""""""
def _make(dist_fn, args):
if args is None:
return lambda *_: dist_fn
if not args:
return lambda *_: dist_fn()
def _fn(*xs):
kwargs = dict(zip(args, reversed(xs[-len(args):])))
kwargs.pop('_', None)
return dist_fn(**kwargs)
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/cassandra_to_gcs.py#L247-L255 | def convert_user_type(cls, name, value):
"""
"""
names = value._fields
values = [cls.convert_value(name, getattr(value, name)) for name in names]
return cls.generate_data_dict(names, values) |
https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/extractors/acfun.py#L42-L109 | def acfun_download_by_vid(vid, title, output_dir='.', merge=True, info_only=False, **kwargs):
"""
"""
#first call the main parasing API
info = json.loads(get_content('http://www.acfun.cn/video/getVideo.aspx?id=' + vid))
sourceType = info['sourceType']
#decide sourceId to know which extractor ... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/mssql_to_gcs.py#L127-L137 | def _query_mssql(self):
"""
"""
mssql = MsSqlHook(mssql_conn_id=self.mssql_conn_id)
conn = mssql.get_conn()
cursor = conn.cursor()
cursor.execute(self.sql)
return cursor |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/azure_cosmos_hook.py#L142-L160 | def create_database(self, database_name):
"""
"""
if database_name is None:
raise AirflowBadRequest("Database name cannot be None.")
# We need to check to see if this database already exists so we don't try
# to create it twice
existing_database = li... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/common.py#L576-L592 | def callBigDlFunc(bigdl_type, name, *args):
""" """
gateway = _get_gateway()
error = Exception("Cannot find function: %s" % name)
for jinvoker in JavaCreator.instance(bigdl_type, gateway).value:
# hasattr(jinvoker, name) always return true here,
# so you need to invoke the method to che... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/mcmc/elliptical_slice_sampler.py#L405-L417 | def _prepare_args(log_likelihood_fn, state,
log_likelihood=None, description='log_likelihood'):
""""""
state_parts = list(state) if mcmc_util.is_list_like(state) else [state]
state_parts = [tf.convert_to_tensor(s, name='current_state')
for s in state_parts]
log_likelihood = _... |
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) |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/examples/keras/keras_utils.py#L20-L26 | def save_keras_definition(keras_model, path):
"""
"""
model_json = keras_model.to_json()
with open(path, "w") as json_file:
json_file.write(model_json) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/normal.py#L241-L261 | def _kl_normal_normal(n_a, n_b, name=None):
"""
"""
with tf.name_scope(name or "kl_normal_normal"):
one = tf.constant(1, dtype=n_a.dtype)
two = tf.constant(2, dtype=n_a.dtype)
half = tf.constant(0.5, dtype=n_a.dtype)
s_a_squared = tf.square(n_a.scale)
s_b_squared = tf.square(n_b.scale)
rat... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/common.py#L215-L266 | def sparse(cls, a_ndarray, i_ndarray, shape, bigdl_type="float"):
"""
"""
if a_ndarray is None:
return None
assert isinstance(a_ndarray, np.ndarray), \
"values array should be a np.ndarray, not %s" % type(a_ndarray)
assert isinstance(i_ndarray, np... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/distribution.py#L173-L175 | def _remove_dict_keys_with_value(dict_, val):
""""""
return {k: v for k, v in dict_.items() if v is not val} |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/fun_mcmc/fun_mcmc_lib.py#L140-L157 | def call_and_grads(fn: TransitionOperator, args: Union[Tuple[Any], Any]
) -> Tuple[tf.Tensor, TensorNest, TensorNest]:
"""
"""
with tf.GradientTape() as tape:
tape.watch(args)
ret, extra = call_fn(fn, args)
grads = tape.gradient(ret, args)
return ret, extra, grads |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/dbapi_hook.py#L168-L177 | def set_autocommit(self, conn, autocommit):
"""
"""
if not self.supports_autocommit and autocommit:
self.log.warn(
("%s connection doesn't support "
"autocommit but autocommit activated."),
getattr(self, self.conn_name_attr))
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L74-L111 | def _choose_base_case(is_accepted,
accepted,
rejected,
name=None):
""""""
def _expand_is_accepted_like(x):
"""Helper to expand `is_accepted` like the shape of some input arg."""
with tf.compat.v1.name_scope('expand_is_accepted_like'):
e... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L680-L705 | def rotate(img, angle, resample=False, expand=False, center=None):
"""
"""
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.rotate(angle, resample, expand, center) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L287-L295 | def _numpy_text(tensor, is_repr=False):
""""""
if tensor.dtype.is_numpy_compatible:
text = repr(tensor.numpy()) if is_repr else str(tensor.numpy())
else:
text = "<unprintable>"
if "\n" in text:
text = "\n" + text
return text |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/moving_stats.py#L186-L245 | def moving_mean_variance(value, decay, name=None):
"""
"""
with tf.compat.v1.variable_scope(name, "moving_mean_variance",
[value, decay]):
value = tf.convert_to_tensor(value=value, name="value")
base_dtype = value.dtype.base_dtype
if not base_dtype.is_floating:
... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/transforms.py#L875-L905 | def get_params(brightness, contrast, saturation, hue):
"""
"""
transforms = []
if brightness is not None:
brightness_factor = random.uniform(brightness[0], brightness[1])
transforms.append(Lambda(lambda img: F.adjust_brightness(img, brightness_factor)))
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/task_runner/cgroup_task_runner.py#L90-L109 | def _delete_cgroup(self, path):
"""
"""
node = trees.Tree().root
path_split = path.split("/")
for path_element in path_split:
name_to_node = {x.name: x for x in node.children}
if path_element not in name_to_node:
self.log.warning("... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/security.py#L303-L312 | def _has_perm(self, permission_name, view_menu_name):
"""
"""
if hasattr(self, 'perms'):
if (permission_name, view_menu_name) in self.perms:
return True
# rebuild the permissions set
self._get_and_cache_perms()
return (permission_name,... |
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("E... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/common.py#L306-L345 | def from_ndarray(cls, features, labels, bigdl_type="float"):
"""
"""
if isinstance(features, np.ndarray):
features = [features]
else:
assert all(isinstance(feature, np.ndarray) for feature in features), \
"features should be a list of np.n... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1323-L1365 | def prefer_static_broadcast_shape(shape1,
shape2,
name="prefer_static_broadcast_shape"):
"""
"""
with tf.name_scope(name):
def make_shape_tensor(x):
return tf.convert_to_tensor(value=x, name="shape", dtype=tf.int32)
def get_tensor... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/joint_distribution_sequential.py#L210-L218 | def _build(self, model):
""""""
if not isinstance(model, collections.Sequence):
raise TypeError('`model` must be `list`-like (saw: {}).'.format(
type(model).__name__))
self._dist_fn = model
self._dist_fn_wrapped, self._dist_fn_args = zip(*[
_unify_call_signature(i, dist_fn)
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/linalg.py#L898-L911 | def _maybe_validate_matrix(a, validate_args):
""""""
assertions = []
if not a.dtype.is_floating:
raise TypeError('Input `a` must have `float`-like `dtype` '
'(saw {}).'.format(a.dtype.name))
if a.shape.ndims is not None:
if a.shape.ndims < 2:
raise ValueError('Input `a` must ha... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/lbfgs.py#L263-L274 | def _get_initial_state(value_and_gradients_function,
initial_position,
num_correction_pairs,
tolerance):
""""""
init_args = bfgs_utils.get_initial_state_args(
value_and_gradients_function,
initial_position,
tolerance)
empty_que... |
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 |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs.py#L289-L319 | def _inv_hessian_control_inputs(inv_hessian):
"""
"""
# The easiest way to validate if the inverse Hessian is positive definite is
# to compute its Cholesky decomposition.
is_positive_definite = tf.reduce_all(
input_tensor=tf.math.is_finite(tf.linalg.cholesky(inv_hessian)),
axis=[-1, -2])
# The... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L740-L762 | def maybe_get_static_value(x, dtype=None):
"""
"""
if x is None:
return x
try:
# This returns an np.ndarray.
x_ = tf.get_static_value(x)
except TypeError:
x_ = x
if x_ is None or dtype is None:
return x_
return np.array(x_, dtype) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/neutra/neutra_kernel.py#L350-L381 | def one_step(self, current_state, previous_kernel_results):
"""
"""
@tfp.mcmc.internal.util.make_innermost_setter
def set_num_leapfrog_steps(kernel_results, num_leapfrog_steps):
return kernel_results._replace(
accepted_results=kernel_results.accepted_results._replace(
num_... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcs_hook.py#L360-L378 | def get_md5hash(self, bucket_name, object_name):
"""
"""
self.log.info('Retrieving the MD5 hash of '
'object: %s in bucket: %s', object_name, bucket_name)
client = self.get_conn()
bucket = client.get_bucket(bucket_name=bucket_name)
blob = bu... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/keras/topology.py#L208-L216 | def from_jvalue(jvalue, bigdl_type="float"):
"""
"""
model = Sequential(jvalue=jvalue)
model.value = jvalue
return model |
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)):
utte... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/models/vgg.py#L100-L111 | def vgg11_bn(pretrained=False, **kwargs):
"""
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn']))
return model |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/datasets/utils.py#L54-L90 | def download_url(url, root, filename=None, md5=None):
"""
"""
from six.moves import urllib
root = os.path.expanduser(root)
if not filename:
filename = os.path.basename(url)
fpath = os.path.join(root, filename)
makedir_exist_ok(root)
# downloads file
if os.path.isfile(fpath... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/transform/vision/image.py#L226-L232 | def get_image(self, float_key="floats", to_chw=True):
"""
"""
tensors = callBigDlFunc(self.bigdl_type,
"localImageFrameToImageTensor", self.value, float_key, to_chw)
return map(lambda tensor: tensor.to_ndarray(), tensors) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/compression.py#L26-L43 | def uncompress_file(input_file_name, file_extension, dest_dir):
"""
"""
if file_extension.lower() not in ('.gz', '.bz2'):
raise NotImplementedError("Received {} format. Only gz and bz2 "
"files can currently be uncompressed."
.... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L372-L392 | def resized_crop(img, i, j, h, w, size, interpolation=Image.BILINEAR):
"""
"""
assert _is_pil_image(img), 'img should be PIL Image'
img = crop(img, i, j, h, w)
img = resize(img, size, interpolation)
return img |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L180-L201 | def check_s3_url(self, s3url):
"""
"""
bucket, key = S3Hook.parse_s3_url(s3url)
if not self.s3_hook.check_for_bucket(bucket_name=bucket):
raise AirflowException(
"The input S3 Bucket {} does not exist ".format(bucket))
if key and not self.s3_h... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L1979-L2007 | def _manage_executor_state(self, running):
"""
"""
executor = self.executor
for key, state in list(executor.get_event_buffer().items()):
if key not in running:
self.log.warning(
"%s state %s not in running=%s",
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1407-L1412 | def gen_new_seed(seed, salt):
""""""
if seed is None:
return None
string = (str(seed) + salt).encode("utf-8")
return int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L401-L410 | def _broadcast_maybelist_arg(states, secondary_arg, name):
""""""
if _is_list_like(secondary_arg):
if len(secondary_arg) != len(states):
raise ValueError('Argument `%s` was a list of different length ({}) than '
'`states` ({})'.format(name, len(states)))
else:
secondary_arg = ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/seasonal.py#L513-L526 | def build_is_last_day_of_season(num_steps_per_season):
""""""
num_steps_per_cycle = np.sum(num_steps_per_season)
changepoints = np.cumsum(np.ravel(num_steps_per_season)) - 1
def is_last_day_of_season(t):
t_ = dist_util.maybe_get_static_value(t)
if t_ is not None: # static case
step_in_cycle = t_ ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/blockwise.py#L229-L269 | def _kl_blockwise_blockwise(b0, b1, name=None):
"""
"""
if len(b0.distributions) != len(b1.distributions):
raise ValueError(
'Can only compute KL divergence between Blockwise distributions with '
'the same number of component distributions.')
# We also need to check that the event shapes ma... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dates.py#L214-L224 | def scale_time_units(time_seconds_arr, unit):
"""
"""
if unit == 'minutes':
return list(map(lambda x: x * 1.0 / 60, time_seconds_arr))
elif unit == 'hours':
return list(map(lambda x: x * 1.0 / (60 * 60), time_seconds_arr))
elif unit == 'days':
return list(map(lambda x: x... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L642-L683 | def assert_integer_form(x,
data=None,
summarize=None,
message=None,
int_dtype=None,
name="assert_integer_form"):
"""
"""
with tf.name_scope(name):
x = tf.convert_to_tensor(value=x, name="x")... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/mcmc/elliptical_slice_sampler.py#L228-L372 | def one_step(self, current_state, previous_kernel_results):
"""
"""
with tf.compat.v1.name_scope(
name=mcmc_util.make_name(self.name, 'elliptical_slice', 'one_step'),
values=[self._seed_stream,
current_state,
previous_kernel_results.log_likelihood]):
wit... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/S3_hook.py#L352-L382 | def load_string(self,
string_data,
key,
bucket_name=None,
replace=False,
encrypt=False,
encoding='utf-8'):
"""
"""
self.load_bytes(string_data.encode(encoding),
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/datastore_hook.py#L213-L233 | def delete_operation(self, name):
"""
"""
conn = self.get_conn()
resp = (conn
.projects()
.operations()
.delete(name=name)
.execute(num_retries=self.num_retries))
return resp |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/decomposition.py#L109-L219 | def decompose_by_component(model, observed_time_series, parameter_samples):
"""
"""
with tf.compat.v1.name_scope('decompose_by_component',
values=[observed_time_series]):
[
observed_time_series,
is_missing
] = sts_util.canonicalize_observed_time_series_with... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/fitting.py#L92-L264 | def build_factored_variational_loss(model,
observed_time_series,
init_batch_shape=(),
seed=None,
name=None):
"""
"""
with tf.compat.v1.name_scope(
name, 'build_fa... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/sensors/aws_glue_catalog_partition_sensor.py#L70-L81 | def poke(self, context):
"""
"""
if '.' in self.table_name:
self.database_name, self.table_name = self.table_name.split('.')
self.log.info(
'Poking for table %s. %s, expression %s', self.database_name, self.table_name, self.expression
)
r... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/pareto.py#L214-L245 | def _extend_support(self, x, f, alt):
"""
"""
# We need to do a series of broadcasts for the tf.where.
scale = self.scale + tf.zeros_like(self.concentration)
is_invalid = x < scale
scale = scale + tf.zeros_like(x)
x = x + tf.zeros_like(scale)
# We need to do this to ensure gradients are ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/seasonal.py#L573-L604 | def build_seasonal_transition_matrix(
num_seasons, is_last_day_of_season, dtype,
basis_change_matrix=None, basis_change_matrix_inv=None):
""""""
with tf.compat.v1.name_scope('build_seasonal_transition_matrix'):
# If the season is changing, the transition matrix permutes the latent
# state to shift ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/cholesky_outer_product.py#L190-L217 | def _make_columnar(self, x):
"""
"""
if tensorshape_util.rank(x.shape) is not None:
if tensorshape_util.rank(x.shape) == 1:
x = x[tf.newaxis, :]
return x
shape = tf.shape(input=x)
maybe_expanded_shape = tf.concat([
shape[:-1],
distribution_util.pick_vector(
... |
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 |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/transform/vision/image.py#L290-L295 | def get_predict(self, key="predict"):
"""
"""
predicts = callBigDlFunc(self.bigdl_type, "distributedImageFrameToPredict", self.value, key)
return predicts.map(lambda predict: (predict[0], predict[1].to_ndarray()) if predict[1] else (predict[0], None)) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/masked_autoregressive.py#L903-L954 | def _create_degrees(input_size,
hidden_units=None,
input_order="left-to-right",
hidden_degrees="equal"):
"""
"""
input_order = _create_input_order(input_size, input_order)
degrees = [input_order]
if hidden_units is None:
hidden_units = []
for... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L414-L424 | def predict_class(self, features):
"""
"""
if isinstance(features, RDD):
return self.predict_class_distributed(features)
else:
return self.predict_class_local(features) |
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 |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/kullback_leibler.py#L34-L47 | def _registered_kl(type_a, type_b):
""""""
hierarchy_a = tf_inspect.getmro(type_a)
hierarchy_b = tf_inspect.getmro(type_b)
dist_to_children = None
kl_fn = None
for mro_to_a, parent_a in enumerate(hierarchy_a):
for mro_to_b, parent_b in enumerate(hierarchy_b):
candidate_dist = mro_to_a + mro_to_b
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_sql_hook.py#L911-L923 | def retrieve_connection(self, session=None):
"""
"""
self.log.info("Retrieving connection %s", self.db_conn_id)
connections = session.query(Connection).filter(
Connection.conn_id == self.db_conn_id)
if connections.count():
return connections[0]
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1415-L1561 | def fill_triangular(x, upper=False, name=None):
"""
with tf.name_scope(name or "fill_triangular"):
x = tf.convert_to_tensor(value=x, name="x")
m = tf.compat.dimension_value(
tensorshape_util.with_rank_at_least(x.shape, 1)[-1])
if m is not None:
# Formula derived by solving for n: m = n... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/common.py#L630-L635 | def callJavaFunc(func, *args):
""" """
gateway = _get_gateway()
args = [_py2java(gateway, a) for a in args]
result = func(*args)
return _java2py(gateway, result) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_sql_hook.py#L984-L990 | def reserve_free_tcp_port(self):
"""
"""
self.reserved_tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.reserved_tcp_socket.bind(('127.0.0.1', 0))
self.sql_proxy_tcp_port = self.reserved_tcp_socket.getsockname()[1] |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L580-L602 | def harvest_simple_dags(self):
"""
"""
# Metadata and results to be harvested can be inconsistent,
# but it should not be a big problem.
self._sync_metadata()
# Heartbeating after syncing metadata so we do not restart manager
# if it processed all files f... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/masked_autoregressive.py#L854-L863 | def call(self, x):
""""""
with tf.compat.v2.name_scope(self.name or "AutoregressiveLayer_call"):
x = tf.convert_to_tensor(value=x, dtype=self.dtype, name="x")
input_shape = tf.shape(input=x)
# TODO(b/67594795): Better support for dynamic shapes.
if tensorshape_util.rank(x.shape) == 1:
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs.py#L494-L506 | def _batch_transpose(mat):
"""
"""
n = distribution_util.prefer_static_rank(mat)
perm = tf.range(n)
perm = tf.concat([perm[:-2], [perm[-1], perm[-2]]], axis=0)
return tf.transpose(a=mat, perm=perm) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L247-L290 | def smart_for_loop(loop_num_iter, body_fn, initial_loop_vars,
parallel_iterations=10, name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'smart_for_loop',
[loop_num_iter, initial_loop_vars]):
loop_num_iter_ = tf.get_static_value(loop_num_iter)
if (loop... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L329-L360 | def evaluate(self, *args):
"""
"""
if len(args) == 0:
callBigDlFunc(self.bigdl_type,
"evaluate", self.value)
return self
elif len(args) == 3:
dataset, batch_size, val_methods = args
if (isinstance(dataset,... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_speech_to_text_hook.py#L42-L51 | def get_conn(self):
"""
"""
if not self._client:
self._client = SpeechClient(credentials=self._get_credentials())
return self._client |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L60-L162 | def make_simple_step_size_update_policy(num_adaptation_steps,
target_rate=0.75,
decrement_multiplier=0.01,
increment_multiplier=0.01,
step_counter=None):
"""
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L459-L470 | def _accept_reflected_fn(simplex,
objective_values,
worst_index,
reflected,
objective_at_reflected):
""""""
def _replace_worst_with_reflected():
next_simplex = _replace_at_index(simplex, worst_index, reflected)
... |
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") |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/transform/vision/image.py#L283-L288 | def get_label(self):
"""
"""
tensor_rdd = callBigDlFunc(self.bigdl_type, "distributedImageFrameToLabelTensorRdd", self.value)
return tensor_rdd.map(lambda tensor: tensor.to_ndarray()) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dagrun.py#L191-L206 | def get_task_instance(self, task_id, session=None):
"""
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
TI = TaskInstance
ti = session.query(TI).filter(
TI.dag_id == self.dag_id,
TI.execution_date == self.executi... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/eight_schools_hmc.py#L63-L129 | def benchmark_eight_schools_hmc(
num_results=int(5e3),
num_burnin_steps=int(3e3),
num_leapfrog_steps=3,
step_size=0.4):
""""""
num_schools = 8
treatment_effects = tf.constant(
[28, 8, -3, 7, -1, 1, 18, 12],
dtype=np.float32,
name='treatment_effects')
treatment_stddevs = tf.con... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L1285-L1320 | def end(self):
"""
"""
pids_to_kill = self.get_all_pids()
if len(pids_to_kill) > 0:
# First try SIGTERM
this_process = psutil.Process(os.getpid())
# Only check child processes to ensure that we don't have a case
# where we kill the... |
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) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L90-L95 | def is_complex(dtype):
""""""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/taskinstance.py#L414-L421 | def error(self, session=None):
"""
"""
self.log.error("Recording the task instance as FAILED")
self.state = State.FAILED
session.merge(self)
session.commit() |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L395-L407 | def hflip(img):
"""
"""
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.transpose(Image.FLIP_LEFT_RIGHT) |
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 |
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 =... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/fitting.py#L285-L537 | def fit_with_hmc(model,
observed_time_series,
num_results=100,
num_warmup_steps=50,
num_leapfrog_steps=15,
initial_state=None,
initial_step_size=None,
chain_batch_shape=(),
num_variati... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/macros/__init__.py#L49-L66 | def ds_format(ds, input_format, output_format):
"""
"""
return datetime.strptime(ds, input_format).strftime(output_format) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/cassandra_hook.py#L108-L115 | def get_conn(self):
"""
"""
if self.session and not self.session.is_shutdown:
return self.session
self.session = self.cluster.connect(self.keyspace)
return self.session |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/linalg.py#L711-L735 | def _lu_solve_assertions(lower_upper, perm, rhs, validate_args):
""""""
assertions = _lu_reconstruct_assertions(lower_upper, perm, validate_args)
message = 'Input `rhs` must have at least 2 dimensions.'
if rhs.shape.ndims is not None:
if rhs.shape.ndims < 2:
raise ValueError(message)
elif validate_... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L213-L233 | def construct_task_instance(self, session=None, lock_for_update=False):
"""
"""
TI = airflow.models.TaskInstance
qry = session.query(TI).filter(
TI.dag_id == self._dag_id,
TI.task_id == self._task_id,
TI.execution_date == self._execution_date... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/vector_diffeomixture.py#L108-L199 | def quadrature_scheme_softmaxnormal_quantiles(
normal_loc, normal_scale, quadrature_size,
validate_args=False, name=None):
"""
"""
with tf.name_scope(name or "softmax_normal_grid_and_probs"):
normal_loc = tf.convert_to_tensor(value=normal_loc, name="normal_loc")
dt = dtype_util.base_dtype(normal_l... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/disentangled_vae.py#L283-L315 | def call(self, inputs, state):
"""
"""
# In order to allow the user to pass in a single example without a batch
# dimension, we always expand the input to at least two dimensions, then
# fix the output shape to remove the batch dimension if necessary.
original_shape = inputs.shape
if len(ori... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/mysql_to_gcs.py#L134-L142 | def _query_mysql(self):
"""
"""
mysql = MySqlHook(mysql_conn_id=self.mysql_conn_id)
conn = mysql.get_conn()
cursor = conn.cursor()
cursor.execute(self.sql)
return cursor |
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_we... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/presto_hook.py#L80-L88 | def get_records(self, hql, parameters=None):
"""
"""
try:
return super().get_records(
self._strip_sql(hql), parameters)
except DatabaseError as e:
raise PrestoException(self._get_pretty_exception_message(e)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.