_id stringlengths 98 184 | text stringlengths 91 10.9k |
|---|---|
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/generated_random_variables.py#L83-L94 | def _build_custom_rv(distribution, sample_shape, value, name):
""""""
# Program transformations (e.g., `make_log_joint_fn`) assume that
# the traced constructor has `name` and `value` kwargs, enabling
# them to override the value of an RV according to its name.
# User-defined RVs inherit their name from the p... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/assert_util.py#L44-L73 | def assert_finite(x, data=None, summarize=None, message=None, name=None):
"""
"""
with tf.compat.v2.name_scope(name or 'assert_finite'):
x_ = tf.get_static_value(x)
if x_ is not None:
if ~np.all(np.isfinite(x_)):
raise ValueError(message)
return x
assertion = tf.compat.v1.assert_eq... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L925-L929 | def _maybe_broadcast_volatility(volatility_parts,
state_parts):
""""""
return [v + tf.zeros_like(sp, dtype=sp.dtype.base_dtype)
for v, sp in zip(volatility_parts, state_parts)] |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/_vendor/slugify/slugify.py#L74-L175 | def slugify(text, entities=True, decimal=True, hexadecimal=True, max_length=0, word_boundary=False,
separator=DEFAULT_SEPARATOR, save_order=False, stopwords=(), regex_pattern=None, lowercase=True,
replacements=()):
"""
"""
# user-specific replacements
if replacements:
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L875-L886 | def _largest_integer_by_dtype(dt):
""""""
if not _is_known_dtype(dt):
raise TypeError("Unrecognized dtype: {}".format(dt.name))
if dt.is_floating:
return int(2**(np.finfo(dt.as_numpy_dtype).nmant + 1))
if dt.is_integer:
return np.iinfo(dt.as_numpy_dtype).max
if dt.base_dtype == tf.bool:
return... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/disentangled_vae.py#L358-L391 | def call(self, inputs):
"""
"""
# We explicitly broadcast f to the same shape as z other than the final
# dimension, because `tf.concat` can't automatically do this.
dynamic, static = inputs
timesteps = tf.shape(input=dynamic)[-2]
static = static[..., tf.newaxis, :] + tf.zeros([timesteps, 1]... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_vision_hook.py#L256-L267 | def get_product(self, location, product_id, project_id=None, retry=None, timeout=None, metadata=None):
"""
"""
client = self.get_conn()
name = ProductSearchClient.product_path(project_id, location, product_id)
self.log.info('Retrieving Product: %s', name)
respons... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/mysql_to_gcs.py#L210-L253 | def _write_local_schema_file(self, cursor):
"""
"""
schema_str = None
schema_file_mime_type = 'application/json'
tmp_schema_file_handle = NamedTemporaryFile(delete=True)
if self.schema is not None and isinstance(self.schema, string_types):
schema_str ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L259-L301 | def add_ema_control_dependencies(vector_quantizer,
one_hot_assignments,
codes,
commitment_loss,
decay):
"""
"""
# Use an exponential moving average to update the codebook.
updated_... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1002-L1098 | def embed_check_integer_casting_closed(x,
target_dtype,
assert_nonnegative=True,
assert_positive=False,
name="embed_check_casting_closed"):
"""
"""
with tf.n... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/dense_variational.py#L215-L254 | def get_config(self):
"""
"""
config = {
'units': self.units,
'activation': (tf.keras.activations.serialize(self.activation)
if self.activation else None),
'activity_regularizer':
tf.keras.initializers.serialize(self.activity_regularizer),
}
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/api/common/experimental/mark_tasks.py#L211-L239 | def set_dag_run_state_to_success(dag, execution_date, commit=False, session=None):
"""
"""
res = []
if not dag or not execution_date:
return res
# Mark the dag run to success.
if commit:
_set_dag_run_state(dag.dag_id, execution_date, State.SUCCESS, session)
# Mark all... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/affine.py#L34-L37 | def _as_tensor(x, name, dtype):
""""""
return None if x is None else tf.convert_to_tensor(
value=x, name=name, dtype=dtype) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/uniform.py#L144-L147 | def range(self, name="range"):
""""""
with self._name_scope(name):
return self.high - self.low |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/vector_diffeomixture.py#L853-L879 | def interpolate_loc(grid, loc):
""""""
if len(loc) != 2:
raise NotImplementedError("Currently only bimixtures are supported; "
"len(scale)={} is not 2.".format(len(loc)))
deg = tf.compat.dimension_value(
tensorshape_util.with_rank_at_least(grid.shape, 1)[-1])
if deg is No... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/spark_sql_hook.py#L136-L159 | def run_query(self, cmd="", **kwargs):
"""
"""
spark_sql_cmd = self._prepare_command(cmd)
self._sp = subprocess.Popen(spark_sql_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/opsgenie_alert_operator.py#L107-L124 | def _build_opsgenie_payload(self):
"""
"""
payload = {}
for key in [
"message", "alias", "description", "responders",
"visibleTo", "actions", "tags", "details", "entity",
"source", "priority", "user", "note"
]:
val = getat... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/awsbatch_operator.py#L117-L145 | def _wait_for_task_ended(self):
"""
"""
try:
waiter = self.client.get_waiter('job_execution_complete')
waiter.config.max_attempts = sys.maxsize # timeout is managed by airflow
waiter.wait(jobs=[self.jobId])
except ValueError:
# If... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/transforms.py#L624-L664 | def get_params(img, scale, ratio):
"""
"""
area = img.size[0] * img.size[1]
for attempt in range(10):
target_area = random.uniform(*scale) * area
log_ratio = (math.log(ratio[0]), math.log(ratio[1]))
aspect_ratio = math.exp(random.uniform(*log_ratio))
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/prefer_static.py#L41-L56 | def _prefer_static(original_fn, static_fn):
""""""
original_spec = tf_inspect.getfullargspec(original_fn)
static_spec = tf_inspect.getfullargspec(static_fn)
if original_spec != static_spec:
raise ValueError(
'Arg specs do not match: original={}, static={}, fn={}'.format(
original_spec, s... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mvn_linear_operator.py#L269-L340 | def _kl_brute_force(a, b, name=None):
"""
"""
def squared_frobenius_norm(x):
"""Helper to make KL calculation slightly more readable."""
# http://mathworld.wolfram.com/FrobeniusNorm.html
# The gradient of KL[p,q] is not defined when p==q. The culprit is
# tf.norm, i.e., we cannot use the commente... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/S3_hook.py#L279-L293 | def check_for_wildcard_key(self,
wildcard_key, bucket_name=None, delimiter=''):
"""
"""
return self.get_wildcard_key(wildcard_key=wildcard_key,
bucket_name=bucket_name,
delimiter=del... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/ftp_hook.py#L102-L117 | def describe_directory(self, path):
"""
"""
conn = self.get_conn()
conn.cwd(path)
try:
# only works in Python 3
files = dict(conn.mlsd())
except AttributeError:
files = dict(mlsd(conn))
return files |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L124-L158 | def plot_heldout_prediction(input_vals, probs,
fname, n=10, title=""):
"""
"""
fig = figure.Figure(figsize=(9, 3*n))
canvas = backend_agg.FigureCanvasAgg(fig)
for i in range(n):
ax = fig.add_subplot(n, 3, 3*i + 1)
ax.imshow(input_vals[i, :].reshape(IMAGE_SHAPE[:-1]), interp... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/dirichlet.py#L300-L315 | def _maybe_assert_valid_concentration(self, concentration, validate_args):
""""""
if not validate_args:
return concentration
return distribution_util.with_dependencies([
assert_util.assert_positive(
concentration, message="Concentration parameter must be positive."),
assert... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/internal/util.py#L201-L252 | def empirical_statistics(observed_time_series):
"""
"""
with tf.compat.v1.name_scope(
'empirical_statistics', values=[observed_time_series]):
[
observed_time_series,
mask
] = canonicalize_observed_time_series_with_mask(observed_time_series)
squeezed_series = observed_time_seri... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/imap_hook.py#L236-L264 | def get_attachments_by_name(self, name, check_regex, find_first=False):
"""
"""
attachments = []
for part in self.mail.walk():
mail_part = MailPart(part)
if mail_part.is_attachment():
found_attachment = mail_part.has_matching_name(name) i... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/tensorshape_util.py#L285-L303 | def with_rank_at_least(x, rank): # pylint: disable=redefined-outer-name
"""
"""
return type(x)(tf.TensorShape(x).with_rank_at_least(rank)) |
https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/extractors/sina.py#L54-L64 | def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False):
"""
"""
url = 'http://video.sina.com/v/flvideo/%s_0.flv' % vkey
type, ext, size = url_info(url)
print_info(site_info, title, 'flv', size)
if not info_only:
download_urls([url], title, 'flv', size,... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/triangular.py#L33-L38 | def _broadcast_to(tensor_to_broadcast, target_tensors):
""""""
output = tensor_to_broadcast
for tensor in target_tensors:
output += tf.zeros_like(tensor)
return output |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1158-L1195 | def build_backward_pass_step(get_transition_matrix_for_timestep):
"""
"""
def backward_pass_step(state,
filtered_parameters):
"""Run a single step of backward smoothing."""
(filtered_mean, filtered_cov,
predicted_mean, predicted_cov) = filtered_parameters
transition_mat... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/special_math.py#L383-L388 | def _log_ndtr_lower(x, series_order):
""""""
x_2 = tf.square(x)
# Log of the term multiplying (1 + sum)
log_scale = -0.5 * x_2 - tf.math.log(-x) - 0.5 * np.log(2. * np.pi)
return log_scale + tf.math.log(_log_ndtr_asymptotic_series(x, series_order)) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/sample_stats.py#L39-L209 | def auto_correlation(x,
axis=-1,
max_lags=None,
center=True,
normalize=True,
name='auto_correlation'):
"""
"""
# Implementation details:
# Extend length N / 2 1-D array x to length N by zero padding onto the... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/postgres_to_gcs_operator.py#L166-L192 | def _write_local_schema_file(self, cursor):
"""
"""
schema = []
for field in cursor.description:
# See PEP 249 for details about the description tuple.
field_name = field[0]
field_type = self.type_map(field[1])
field_mode = 'REPEAT... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_vision_hook.py#L527-L548 | def safe_search_detection(
self, image, max_results=None, retry=None, timeout=None, additional_properties=None
):
"""
"""
client = self.annotator_client
self.log.info("Detecting safe search")
if additional_properties is None:
additional_properti... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/decorators.py#L29-L58 | def action_logging(f):
"""
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
with create_session() as session:
if g.user.is_anonymous:
user = 'anonymous'
else:
user = g.user.username
log = Log(
event=f... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/_vendor/nvd3/NVD3Chart.py#L385-L405 | def buildcontainer(self):
""""""
if self.container:
return
# Create SVG div with style
if self.width:
if self.width[-1] != '%':
self.style += 'width:%spx;' % self.width
else:
self.style += 'width:%s;' % self.width
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1198-L1271 | def rotate_transpose(x, shift, name="rotate_transpose"):
"""
"""
with tf.name_scope(name):
x = tf.convert_to_tensor(value=x, name="x")
shift = tf.convert_to_tensor(value=shift, name="shift")
# We do not assign back to preserve constant-ness.
assert_util.assert_integer(shift)
shift_value_static... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/hive_hooks.py#L608-L638 | def get_partitions(
self, schema, table_name, filter=None):
"""
"""
with self.metastore as client:
table = client.get_table(dbname=schema, tbl_name=table_name)
if len(table.partitionKeys) == 0:
raise AirflowException("The table isn't p... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/azure_container_instance_hook.py#L80-L93 | def create_or_update(self, resource_group, name, container_group):
"""
"""
self.connection.container_groups.create_or_update(resource_group,
name,
container_group) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/spark_submit_hook.py#L448-L511 | def _start_driver_status_tracking(self):
"""
"""
# When your Spark Standalone cluster is not performing well
# due to misconfiguration or heavy loads.
# it is possible that the polling request will timeout.
# Therefore we use a simple retry mechanism.
mi... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/dingding_hook.py#L76-L98 | def _build_message(self):
"""
"""
if self.message_type in ['text', 'markdown']:
data = {
'msgtype': self.message_type,
self.message_type: {
'content': self.message
} if self.message_type == 'text' else self.... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L905-L999 | def embed_check_categorical_event_shape(
categorical_param, name="embed_check_categorical_event_shape"):
"""
"""
with tf.name_scope(name):
x = tf.convert_to_tensor(value=categorical_param, name="categorical_param")
# The size must not exceed both of:
# - The largest possible int32 (since categoric... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L185-L210 | def call_fn(fn, args):
"""
"""
if expand_as_args(args):
return fn(*args)
elif _expand_as_kwargs(args):
return fn(**args)
else:
return fn(args) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_sql_hook.py#L163-L180 | def delete_instance(self, instance, project_id=None):
"""
"""
response = self.get_conn().instances().delete(
project=project_id,
instance=instance,
).execute(num_retries=self.num_retries)
operation_name = response["name"]
self._wait_for_op... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L349-L360 | def new(params, event_size, validate_args=False, name=None):
""""""
with tf.compat.v1.name_scope(name, 'MultivariateNormalTriL',
[params, event_size]):
params = tf.convert_to_tensor(value=params, name='params')
scale_tril = tfb.ScaleTriL(
diag_shift=np.arra... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/emr_hook.py#L39-L57 | def create_job_flow(self, job_flow_overrides):
"""
"""
if not self.emr_conn_id:
raise AirflowException('emr_conn_id must be present to use create_job_flow')
emr_conn = self.get_connection(self.emr_conn_id)
config = emr_conn.extra_dejson.copy()
conf... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L363-L367 | def params_size(event_size, name=None):
""""""
with tf.compat.v1.name_scope(name, 'MultivariateNormalTriL_params_size',
[event_size]):
return event_size + event_size * (event_size + 1) // 2 |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L90-L121 | def plot_weight_posteriors(names, qm_vals, qs_vals, fname):
"""
"""
fig = figure.Figure(figsize=(6, 3))
canvas = backend_agg.FigureCanvasAgg(fig)
ax = fig.add_subplot(1, 2, 1)
for n, qm in zip(names, qm_vals):
sns.distplot(qm.flatten(), ax=ax, label=n)
ax.set_title("weight means")
ax.set_xlim([-1.5... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/backend/numpy/math.py#L172-L180 | def _max_mask_non_finite(x, axis=-1, keepdims=False, mask=0):
""""""
m = np.max(x, axis=_astuple(axis), keepdims=keepdims)
needs_masking = ~np.isfinite(m)
if needs_masking.ndim > 0:
m[needs_masking] = mask
elif needs_masking:
m = mask
return m |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L1973-L1990 | def _bq_cast(string_field, bq_type):
"""
"""
if string_field is None:
return None
elif bq_type == 'INTEGER':
return int(string_field)
elif bq_type == 'FLOAT' or bq_type == 'TIMESTAMP':
return float(string_field)
elif bq_type == 'BOOLEAN':
if string_field not ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L228-L268 | def make_decoder(activation, latent_size, output_shape, base_depth):
"""
"""
deconv = functools.partial(
tf.keras.layers.Conv2DTranspose, padding="SAME", activation=activation)
conv = functools.partial(
tf.keras.layers.Conv2D, padding="SAME", activation=activation)
decoder_net = tf.keras.Sequenti... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/transpose.py#L291-L318 | def _maybe_validate_perm(perm, validate_args, name=None):
""""""
with tf.name_scope(name or 'maybe_validate_perm'):
assertions = []
if not dtype_util.is_integer(perm.dtype):
raise TypeError('`perm` must be integer type')
msg = '`perm` must be a vector.'
if tensorshape_util.rank(perm.shape) is... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L537-L554 | def adjust_brightness(img, brightness_factor):
"""
"""
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
enhancer = ImageEnhance.Brightness(img)
img = enhancer.enhance(brightness_factor)
return img |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_vision_hook.py#L165-L178 | def get_product_set(
self, location, product_set_id, project_id=None, retry=None, timeout=None, metadata=None
):
"""
"""
client = self.get_conn()
name = ProductSearchClient.product_set_path(project_id, location, product_set_id)
self.log.info('Retrieving Produ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L32-L44 | def _operator(attr):
"""
"""
@functools.wraps(attr)
def func(a, *args):
return attr(a.value, *args)
return func |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/proximal_hessian_sparse.py#L74-L105 | def _sparse_or_dense_matmul_onehot(sparse_or_dense_matrix, col_index):
"""
"""
if isinstance(sparse_or_dense_matrix,
(tf.SparseTensor, tf.compat.v1.SparseTensorValue)):
# TODO(b/111924846): Implement better (ideally in a way that allows us to
# eliminate the `num_rows` arg, if possible).
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/structural_time_series.py#L134-L159 | def make_state_space_model(self,
num_timesteps,
param_vals=None,
initial_state_prior=None,
initial_step=0):
"""
"""
return self._make_state_space_model(
num_timesteps=num_timesteps,
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/chain.py#L40-L109 | def _compute_min_event_ndims(bijector_list, compute_forward=True):
"""
"""
min_event_ndims = 0
# This is a mouthful, but what this encapsulates is that if not for rank
# changing bijectors, we'd only need to compute the largest of the min
# required ndims. Hence "max_min". Due to rank changing bijectors, we... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/tensorshape_util.py#L192-L211 | def merge_with(x, other):
"""
"""
return type(x)(tf.TensorShape(x).merge_with(other)) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vq_vae.py#L324-L350 | def visualize_training(images_val,
reconstructed_images_val,
random_images_val,
log_dir, prefix, viz_n=10):
"""
"""
save_imgs(images_val[:viz_n],
os.path.join(log_dir, "{}_inputs.png".format(prefix)))
save_imgs(reconstructed_images... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/kubernetes/worker_configuration.py#L45-L131 | def _get_init_containers(self):
""""""
# If we're using volume claims to mount the dags, no init container is needed
if self.kube_config.dags_volume_claim or \
self.kube_config.dags_volume_host or self.kube_config.dags_in_image:
return []
# Otherwise, define a git... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_transfer_hook.py#L361-L397 | def operations_contain_expected_statuses(operations, expected_statuses):
"""
"""
expected_statuses = (
{expected_statuses} if isinstance(expected_statuses, six.string_types) else set(expected_statuses)
)
if len(operations) == 0:
return False
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/fun_mcmc/fun_mcmc_lib.py#L160-L178 | def maybe_broadcast_structure(from_structure: Any, to_structure: Any) -> Any:
"""
"""
flat_from = tf.nest.flatten(from_structure)
flat_to = tf.nest.flatten(to_structure)
if len(flat_from) == 1:
flat_from *= len(flat_to)
return tf.nest.pack_sequence_as(to_structure, flat_from) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L330-L524 | def create_external_table(self,
external_project_dataset_table,
schema_fields,
source_uris,
source_format='CSV',
autodetect=False,
compressi... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/transformed_distribution.py#L657-L666 | def _maybe_rotate_dims(self, x, rotate_right=False):
""""""
needs_rotation_const = tf.get_static_value(self._needs_rotation)
if needs_rotation_const is not None and not needs_rotation_const:
return x
ndims = prefer_static.rank(x)
n = (ndims - self._rotate_ndims) if rotate_right else self._rota... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L792-L829 | def _prepare_args_with_initial_vertex(objective_function,
initial_vertex,
step_sizes,
objective_at_initial_vertex,
batch_evaluate_objective):
""""""
dim = tf.size(i... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L1915-L1927 | def fetchall(self):
"""
"""
result = []
while True:
one = self.fetchone()
if one is None:
break
else:
result.append(one)
return result |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L157-L178 | def configure_s3_resources(self, config):
"""
"""
s3_operations = config.pop('S3Operations', None)
if s3_operations is not None:
create_bucket_ops = s3_operations.get('S3CreateBucket', [])
upload_ops = s3_operations.get('S3Upload', [])
for op... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/vector_diffeomixture.py#L899-L933 | def linop_scale(w, op):
""""""
# We assume w > 0. (This assumption only relates to the is_* attributes.)
with tf.name_scope("linop_scale"):
# TODO(b/35301104): LinearOperatorComposition doesn't combine operators, so
# special case combinations here. Once it does, this function can be
# replaced by:
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/von_mises_fisher.py#L36-L73 | def _bessel_ive(v, z, cache=None):
""""""
# TODO(b/67497980): Switch to a more numerically faithful implementation.
z = tf.convert_to_tensor(value=z)
wrap = lambda result: tf.debugging.check_numerics(result, 'besseli{}'.format(v
))
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1535-L1574 | def build_kalman_mean_step(get_transition_matrix_for_timestep,
get_transition_noise_for_timestep,
get_observation_matrix_for_timestep,
get_observation_noise_for_timestep):
"""
"""
def mean_step(previous_means, t):
"""Single step... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/hive_hooks.py#L920-L938 | def get_records(self, hql, schema='default', hive_conf=None):
"""
"""
return self.get_results(hql, schema=schema, hive_conf=hive_conf)['data'] |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_natural_language_hook.py#L56-L80 | def analyze_entities(self, document, encoding_type=None, retry=None, timeout=None, metadata=None):
"""
"""
client = self.get_conn()
return client.analyze_entities(
document=document, encoding_type=encoding_type, retry=retry, timeout=timeout, metadata=metadata
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/salesforce_hook.py#L76-L93 | def make_query(self, query):
"""
"""
conn = self.get_conn()
self.log.info("Querying for all objects")
query_results = conn.query_all(query)
self.log.info("Received results: Total size: %s; Done: %s",
query_results['totalSize'], query_resul... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/api/common/experimental/mark_tasks.py#L30-L53 | def _create_dagruns(dag, execution_dates, state, run_id_template):
"""
"""
# find out if we need to create any dag runs
drs = DagRun.find(dag_id=dag.dag_id, execution_date=execution_dates)
dates_to_create = list(set(execution_dates) - set([dr.execution_date for dr in drs]))
for date in dat... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/von_mises_fisher.py#L358-L385 | def _sample_3d(self, n, seed=None):
""""""
seed = seed_stream.SeedStream(seed, salt='von_mises_fisher_3d')
u_shape = tf.concat([[n], self._batch_shape_tensor()], axis=0)
z = tf.random.uniform(u_shape, seed=seed(), dtype=self.dtype)
# TODO(bjp): Higher-order odd dim analytic CDFs are available in [1]... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L354-L375 | def get_broadcast_shape(*tensors):
"""
"""
# Try static.
s_shape = tensors[0].shape
for t in tensors[1:]:
s_shape = tf.broadcast_static_shape(s_shape, t.shape)
if tensorshape_util.is_fully_defined(s_shape):
return tensorshape_util.as_list(s_shape)
# Fallback on dynamic.
d_shape = tf.shape(input... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_container_hook.py#L131-L168 | def delete_cluster(self, name, project_id=None, retry=DEFAULT, timeout=DEFAULT):
"""
"""
self.log.info(
"Deleting (project_id=%s, zone=%s, cluster_id=%s)", self.project_id, self.location, name
)
try:
op = self.get_client().delete_cluster(project... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L1084-L1103 | def new(params, event_shape=(), validate_args=False, name=None):
""""""
with tf.compat.v1.name_scope(name, 'IndependentPoisson',
[params, event_shape]):
params = tf.convert_to_tensor(value=params, name='params')
event_shape = dist_util.expand_to_vector(
tf.... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/reshape.py#L243-L313 | def _replace_event_shape_in_shape_tensor(
input_shape, event_shape_in, event_shape_out, validate_args):
"""
"""
output_tensorshape, is_validated = _replace_event_shape_in_tensorshape(
tensorshape_util.constant_value_as_shape(input_shape),
event_shape_in,
event_shape_out)
# TODO(b/12424015... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_video_intelligence_hook.py#L51-L105 | def annotate_video(
self,
input_uri=None,
input_content=None,
features=None,
video_context=None,
output_uri=None,
location=None,
retry=None,
timeout=None,
metadata=None,
):
"""
"""
client = self.get_conn... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L39-L82 | def mixture_stddev(mixture_weight_vector, mean_vector, stddev_vector):
"""
"""
tensorshape_util.assert_has_rank(mixture_weight_vector.shape, 2)
if not tensorshape_util.is_compatible_with(mean_vector.shape,
mixture_weight_vector.shape):
raise ValueError("Expecting... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_spanner_hook.py#L212-L244 | def create_database(self, instance_id, database_id, ddl_statements, project_id=None):
"""
"""
instance = self._get_client(project_id=project_id).instance(
instance_id=instance_id)
if not instance.exists():
raise AirflowException("The instance {} does not... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L981-L1038 | def _joint_mean(self):
"""
"""
with tf.name_scope("mean_joint"):
# The initial timestep is a special case, since we sample the
# latent state from the prior rather than the transition model.
with tf.control_dependencies(self.runtime_assertions):
# Broadcast to ensure we represen... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/internal/util.py#L52-L116 | def pad_batch_dimension_for_multiple_chains(
observed_time_series, model, chain_batch_shape):
"""""""
# Running with multiple chains introduces an extra batch dimension. In
# general we also need to pad the observed time series with a matching batch
# dimension.
#
# For example, suppose our model has ba... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L380-L409 | def calculate_reshape(original_shape, new_shape, validate=False, name=None):
""""""
batch_shape_static = tensorshape_util.constant_value_as_shape(new_shape)
if tensorshape_util.is_fully_defined(batch_shape_static):
return np.int32(batch_shape_static), batch_shape_static, []
with tf.name_scope(name or "calcu... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_transfer_hook.py#L119-L132 | def create_transfer_job(self, body):
"""
"""
body = self._inject_project_id(body, BODY, PROJECT_ID)
return self.get_conn().transferJobs().create(body=body).execute(num_retries=self.num_retries) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L932-L997 | def _prepare_args(target_log_prob_fn,
volatility_fn,
state,
step_size,
target_log_prob=None,
grads_target_log_prob=None,
volatility=None,
grads_volatility_fn=None,
diffusion_dr... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dates.py#L195-L211 | def infer_time_unit(time_seconds_arr):
"""
"""
if len(time_seconds_arr) == 0:
return 'hours'
max_time_seconds = max(time_seconds_arr)
if max_time_seconds <= 60 * 2:
return 'seconds'
elif max_time_seconds <= 60 * 60 * 2:
return 'minutes'
elif max_time_seconds <= 2... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/vector_diffeomixture.py#L745-L755 | def _expand_base_distribution_mean(self):
""""""
single_draw_shape = concat_vectors(self.batch_shape_tensor(),
self.event_shape_tensor())
m = tf.reshape(
self.distribution.mean(), # A scalar.
shape=tf.ones_like(single_draw_shape, dtype=tf.int32))
m... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dagrun.py#L163-L188 | def get_task_instances(self, state=None, session=None):
"""
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
tis = session.query(TaskInstance).filter(
TaskInstance.dag_id == self.dag_id,
TaskInstance.execution_date == self... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/program_transformations.py#L138-L223 | def make_log_joint_fn(model):
"""
"""
def log_joint_fn(*args, **kwargs):
"""Log-probability of inputs according to a joint probability distribution.
Args:
*args: Positional arguments. They are the model's original inputs and can
alternatively be specified as part of `kwargs`.
**kwarg... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L1451-L1477 | def params_size(num_components, component_params_size, name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'MixtureSameFamily_params_size',
[num_components, component_params_size]):
num_components = tf.convert_to_tensor(
value=num_components, name='num_com... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L180-L278 | def make_diag_scale(loc=None,
scale_diag=None,
scale_identity_multiplier=None,
shape_hint=None,
validate_args=False,
assert_positive=False,
name=None,
dtype=None):
"""
"""
d... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/taskinstance.py#L424-L455 | def refresh_from_db(self, session=None, lock_for_update=False):
"""
"""
TI = TaskInstance
qry = session.query(TI).filter(
TI.dag_id == self.dag_id,
TI.task_id == self.task_id,
TI.execution_date == self.execution_date)
if lock_for_upd... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/slice_sampler_kernel.py#L555-L580 | def _right_pad(x, final_rank):
"""
"""
padded_shape = tf.concat(
[tf.shape(input=x),
tf.ones(final_rank - tf.rank(x), dtype=tf.int32)],
axis=0)
static_padded_shape = None
if x.shape.is_fully_defined() and isinstance(final_rank, int):
static_padded_shape = x.shape.as_list()
extra_dim... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/datasets/mnist.py#L262-L304 | def download(self):
""""""
import shutil
import zipfile
if self._check_exists():
return
makedir_exist_ok(self.raw_folder)
makedir_exist_ok(self.processed_folder)
# download files
filename = self.url.rpartition('/')[2]
file_path = os.... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/disentangled_vae.py#L264-L281 | def zero_state(self, sample_batch_shape=()):
"""
"""
h0 = tf.zeros([1, self.hidden_size])
c0 = tf.zeros([1, self.hidden_size])
combined_shape = tf.concat((tf.convert_to_tensor(
value=sample_batch_shape, dtype=tf.int32), [self.dimensions]),
axis=-1)
previous... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1799-L1849 | def softplus_inverse(x, name=None):
"""
"""
with tf.name_scope(name or "softplus_inverse"):
x = tf.convert_to_tensor(value=x, name="x")
# We begin by deriving a more numerically stable softplus_inverse:
# x = softplus(y) = Log[1 + exp{y}], (which means x > 0).
# ==> exp{x} = 1 + exp{y} ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.