本文整理汇总了Python中tensorflow.fill方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.fill方法的具体用法?Python tensorflow.fill怎么用?Python tensorflow.fill使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.fill方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testRandomPixelValueScale
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def testRandomPixelValueScale(self):
preprocessing_options = []
preprocessing_options.append((preprocessor.normalize_image, {
'original_minval': 0,
'original_maxval': 255,
'target_minval': 0,
'target_maxval': 1
}))
preprocessing_options.append((preprocessor.random_pixel_value_scale, {}))
images = self.createTestImages()
tensor_dict = {fields.InputDataFields.image: images}
tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options)
images_min = tf.to_float(images) * 0.9 / 255.0
images_max = tf.to_float(images) * 1.1 / 255.0
images = tensor_dict[fields.InputDataFields.image]
values_greater = tf.greater_equal(images, images_min)
values_less = tf.less_equal(images, images_max)
values_true = tf.fill([1, 4, 4, 3], True)
with self.test_session() as sess:
(values_greater_, values_less_, values_true_) = sess.run(
[values_greater, values_less, values_true])
self.assertAllClose(values_greater_, values_true_)
self.assertAllClose(values_less_, values_true_)
示例2: simulate
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def simulate(self, action):
with tf.name_scope("environment/simulate"): # Do we need this?
initializer = (tf.zeros_like(self._observ),
tf.fill((len(self),), 0.0), tf.fill((len(self),), False))
def not_done_step(a, _):
reward, done = self._batch_env.simulate(action)
with tf.control_dependencies([reward, done]):
# TODO(piotrmilos): possibly ignore envs with done
r0 = tf.maximum(a[0], self._batch_env.observ)
r1 = tf.add(a[1], reward)
r2 = tf.logical_or(a[2], done)
return (r0, r1, r2)
simulate_ret = tf.scan(not_done_step, tf.range(self.skip),
initializer=initializer, parallel_iterations=1,
infer_shape=False)
simulate_ret = [ret[-1, ...] for ret in simulate_ret]
with tf.control_dependencies([self._observ.assign(simulate_ret[0])]):
return tf.identity(simulate_ret[1]), tf.identity(simulate_ret[2])
示例3: initialize
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def initialize(self, dtype=tf.float64):
if self.tf_mean is None:
if self.mean is not None:
self.tf_mean = tf.Variable(self.mean, dtype=dtype)
else:
self.tf_mean = tf.Variable(tf.cast(tf.fill([self.dims], 0.0), dtype))
if self.tf_covariance is None:
if self.covariance is not None:
self.tf_covariance = self.covariance
else:
self.tf_covariance = FullCovariance(self.dims)
self.tf_covariance.initialize(dtype)
if self.tf_ln2piD is None:
self.tf_ln2piD = tf.constant(np.log(2 * np.pi) * self.dims, dtype=dtype)
示例4: plot_fitted_data
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def plot_fitted_data(points, c_means, c_variances):
"""Plots the data and given Gaussian components"""
plt.plot(points[:, 0], points[:, 1], "b.", zorder=0)
plt.plot(c_means[:, 0], c_means[:, 1], "r.", zorder=1)
for i in range(c_means.shape[0]):
std = np.sqrt(c_variances[i])
plt.axes().add_artist(pat.Ellipse(
c_means[i], 2 * std[0], 2 * std[1],
fill=False, color="red", linewidth=2, zorder=1
))
plt.show()
# PREPARING DATA
# generating DATA_POINTS points from a GMM with COMPONENTS components
示例5: soften_labels
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def soften_labels(bool_labels, softness=0.05, scope='soften_labels'):
"""Converts boolean labels into float32.
Args:
bool_labels: Tensor with dtype `boolean`
softness: The float value to use for False. 1 - softness is implicitly used
for True
scope: passed to op_scope
Returns:
Tensor with same shape as bool_labels with dtype `float32` and values 0.05
for False and 0.95 for True.
"""
with tf.op_scope([bool_labels, softness], scope):
label_shape = tf.shape(bool_labels, name='label_shape')
return tf.where(bool_labels,
tf.fill(label_shape, 1.0 - softness, name='soft_true'),
tf.fill(label_shape, softness, name='soft_false'))
示例6: where
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def where(cond, true, false, name=None):
"""Similar to tf.where, but broadcasts scalar values."""
with tf.name_scope(name, 'where', [cond, true, false]) as name:
cond = tf.convert_to_tensor(cond, name='cond', dtype=tf.bool)
true = tf.convert_to_tensor(true, name='true',
dtype=false.dtype if isinstance(false, tf.Tensor) else None)
false = tf.convert_to_tensor(false, name='false', dtype=true.dtype)
if true.shape.rank == false.shape.rank == 0:
shape = tf.shape(cond)
true = tf.fill(shape, true)
false = tf.fill(shape, false)
elif true.shape.rank == 0:
true = tf.fill(tf.shape(false), true)
elif false.shape.rank == 0:
false = tf.fill(tf.shape(true), false)
return tf.where(cond, true, false, name=name)
示例7: update_state
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def update_state(self, y_true, y_pred, sample_weight=None):
"""
Maybe have more fast implementation.
"""
b = tf.shape(y_true)[0]
max_width = tf.maximum(tf.shape(y_true)[1], tf.shape(y_pred)[1])
logit_length = tf.fill([tf.shape(y_pred)[0]], tf.shape(y_pred)[1])
decoded, _ = tf.nn.ctc_greedy_decoder(
inputs=tf.transpose(y_pred, perm=[1, 0, 2]),
sequence_length=logit_length)
y_true = tf.sparse.reset_shape(y_true, [b, max_width])
y_pred = tf.sparse.reset_shape(decoded[0], [b, max_width])
y_true = tf.sparse.to_dense(y_true, default_value=-1)
y_pred = tf.sparse.to_dense(y_pred, default_value=-1)
y_true = tf.cast(y_true, tf.int32)
y_pred = tf.cast(y_pred, tf.int32)
values = tf.math.reduce_any(tf.math.not_equal(y_true, y_pred), axis=1)
values = tf.cast(values, tf.int32)
values = tf.reduce_sum(values)
self.total.assign_add(b)
self.count.assign_add(b - values)
示例8: decode
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def decode(self, inputs, from_pred=True, method='greedy'):
if from_pred:
logit_length = tf.fill([tf.shape(inputs)[0]], tf.shape(inputs)[1])
if method == 'greedy':
decoded, _ = tf.nn.ctc_greedy_decoder(
inputs=tf.transpose(inputs, perm=[1, 0, 2]),
sequence_length=logit_length,
merge_repeated=self.merge_repeated)
elif method == 'beam_search':
decoded, _ = tf.nn.ctc_beam_search_decoder(
inputs=tf.transpose(inputs, perm=[1, 0, 2]),
sequence_length=logit_length)
inputs = decoded[0]
decoded = tf.sparse.to_dense(inputs,
default_value=self.blank_index).numpy()
decoded = self.map2string(decoded)
return decoded
示例9: Uniform
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def Uniform(name=None):
X = tf.placeholder(config.dtype, name=name)
Distribution.logp = tf.fill(tf.shape(X), config.dtype(0))
def integral(lower, upper):
return tf.cond(
tf.logical_or(
tf.is_inf(tf.cast(lower, config.dtype)),
tf.is_inf(tf.cast(upper, config.dtype))
),
lambda: tf.constant(1, dtype=config.dtype),
lambda: tf.cast(upper, config.dtype) - tf.cast(lower, config.dtype),
)
Distribution.integral = integral
return X
示例10: UniformInt
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def UniformInt(name=None):
X = tf.placeholder(config.int_dtype, name=name)
Distribution.logp = tf.fill(tf.shape(X), config.dtype(0))
def integral(lower, upper):
val = tf.cond(
tf.logical_or(
tf.is_inf(tf.ceil(tf.cast(lower, config.dtype))),
tf.is_inf(tf.floor(tf.cast(upper, config.dtype)))
),
lambda: tf.constant(1, dtype=config.dtype),
lambda: tf.cast(upper, config.dtype) - tf.cast(lower, config.dtype),
)
return val
Distribution.integral = integral
return X
示例11: version_1
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def version_1(cls, node, **kwargs):
tensor_dict = kwargs["tensor_dict"]
if "shape" in node.attrs:
shape = node.attrs["shape"]
else:
shape = tensor_dict[
node.inputs[0]].get_shape().as_list() if node.attrs.get(
"input_as_shape", 0) == 0 else tensor_dict[node.inputs[0]]
if "extra_shape" in node.attrs:
shape = tf.concat([shape, node.attrs["extra_shape"]], 0)
value = node.attrs.get("value", 0.)
if "dtype" in node.attrs:
return [tf.cast(tf.fill(shape, value), dtype=node.attrs["dtype"])]
return [cls.make_tensor_from_onnx_node(node, inputs=[shape], **kwargs)]
示例12: reset
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def reset(self, entries_to_reset):
"""Reset the entries in the memory.
Args:
entries_to_reset: a 1D tensor.
Returns:
the reset op.
"""
num_updates = tf.size(entries_to_reset)
update_vals = tf.scatter_update(
self.mem_vals, entries_to_reset,
tf.tile(tf.expand_dims(
tf.fill([self.memory_size, self.val_depth], .0), 0),
[num_updates, 1, 1]))
update_logits = tf.scatter_update(
self.mean_logits, entries_to_reset,
tf.tile(tf.expand_dims(
tf.fill([self.memory_size], .0), 0),
[num_updates, 1]))
reset_op = tf.group([update_vals, update_logits])
return reset_op
示例13: get_multi_dataset
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def get_multi_dataset(datasets, pmf=None):
"""Returns a Dataset that samples records from one or more Datasets.
Args:
datasets: A list of one or more Dataset objects to sample from.
pmf: A tensor of shape [len(datasets)], the probabilities to sample each
dataset with. This tensor is often constructed with the global_step. If
this is None, we sample from the datasets uniformly at random.
Returns:
A Dataset object containing records from multiple datasets. Note that
because this dataset iterates through other datasets it is stateful, thus
you will need to call make_initializable_iterator instead of
make_one_shot_iterator.
"""
pmf = tf.fill([len(datasets)], 1.0 / len(datasets)) if pmf is None else pmf
samplers = [d.repeat().make_one_shot_iterator().get_next for d in datasets]
sample = lambda _: categorical_case(pmf, samplers)
return tf.data.Dataset.from_tensors([]).repeat().map(sample)
示例14: _build
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def _build(self, obs_input, act_input, name=None):
"""Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
act_input (tf.Tensor): Tensor input for action.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
garage.tf.models.Sequential.
Return:
tf.Tensor: Tensor output of the model.
"""
del name
del act_input
return_var = tf.compat.v1.get_variable(
'return_var', (), initializer=tf.constant_initializer(0.5))
return tf.fill((tf.shape(obs_input)[0], self.output_dim), return_var)
示例15: _build
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import fill [as 别名]
def _build(self, obs_input, name=None):
"""Build model given input placeholder(s).
Args:
obs_input (tf.Tensor): Tensor input for state.
name (str): Inner model name, also the variable scope of the
inner model, if exist. One example is
garage.tf.models.Sequential.
Return:
tf.Tensor: Tensor output of the model.
"""
del name
return_var = tf.compat.v1.get_variable(
'return_var', (), initializer=tf.constant_initializer(0.5))
return tf.fill((tf.shape(obs_input)[0], self.output_dim), return_var)