本文整理汇总了Python中tensorflow.compat.v1.convert_to_tensor方法的典型用法代码示例。如果您正苦于以下问题:Python v1.convert_to_tensor方法的具体用法?Python v1.convert_to_tensor怎么用?Python v1.convert_to_tensor使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v1
的用法示例。
在下文中一共展示了v1.convert_to_tensor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def __init__(self):
similarity_calc = region_similarity_calculator.IouSimilarity()
matcher = argmax_matcher.ArgMaxMatcher(
matched_threshold=ssd_constants.MATCH_THRESHOLD,
unmatched_threshold=ssd_constants.MATCH_THRESHOLD,
negatives_lower_than_unmatched=True,
force_match_for_each_row=True)
box_coder = faster_rcnn_box_coder.FasterRcnnBoxCoder(
scale_factors=ssd_constants.BOX_CODER_SCALES)
self.default_boxes = DefaultBoxes()('ltrb')
self.default_boxes = box_list.BoxList(
tf.convert_to_tensor(self.default_boxes))
self.assigner = target_assigner.TargetAssigner(
similarity_calc, matcher, box_coder)
示例2: global_pool
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def global_pool(input_tensor, pool_op=tf.nn.avg_pool):
"""Applies avg pool to produce 1x1 output.
NOTE: This function is funcitonally equivalenet to reduce_mean, but it has
baked in average pool which has better support across hardware.
Args:
input_tensor: input tensor
pool_op: pooling op (avg pool is default)
Returns:
a tensor batch_size x 1 x 1 x depth.
"""
shape = input_tensor.get_shape().as_list()
if shape[1] is None or shape[2] is None:
kernel_size = tf.convert_to_tensor(
[1, tf.shape(input_tensor)[1],
tf.shape(input_tensor)[2], 1])
else:
kernel_size = [1, shape[1], shape[2], 1]
output = pool_op(
input_tensor, ksize=kernel_size, strides=[1, 1, 1, 1], padding='VALID')
# Recover output shape, for unknown shape.
output.set_shape([None, 1, 1, None])
return output
示例3: get_synthetic_inputs
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def get_synthetic_inputs(self, input_name, nclass):
inputs = tf.random_uniform(self.get_input_shapes('train')[0],
dtype=self.get_input_data_types('train')[0])
inputs = variables.VariableV1(inputs, trainable=False,
collections=[tf.GraphKeys.LOCAL_VARIABLES],
name=input_name)
labels = tf.convert_to_tensor(
np.random.randint(28, size=[self.batch_size, self.max_label_length]))
input_lengths = tf.convert_to_tensor(
[self.max_time_steps] * self.batch_size)
label_lengths = tf.convert_to_tensor(
[self.max_label_length] * self.batch_size)
return [inputs, labels, input_lengths, label_lengths]
# TODO(laigd): support fp16.
# TODO(laigd): support multiple gpus.
示例4: test_temperature_normal
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def test_temperature_normal(self, temperature):
with tf.Graph().as_default():
rng = np.random.RandomState(0)
# in numpy, so that multiple calls don't trigger different random numbers.
loc_t = tf.convert_to_tensor(rng.randn(5, 5))
scale_t = tf.convert_to_tensor(rng.rand(5, 5))
tempered_normal = glow_ops.TemperedNormal(
loc=loc_t, scale=scale_t, temperature=temperature)
# smoke test for a single sample.
smoke_sample = tempered_normal.sample()
samples = tempered_normal.sample((10000,), seed=0)
with tf.Session() as sess:
ops = [samples, loc_t, scale_t, smoke_sample]
samples_np, loc_exp, scale_exp, _ = sess.run(ops)
scale_exp *= temperature
loc_act = np.mean(samples_np, axis=0)
scale_act = np.std(samples_np, axis=0)
self.assertTrue(np.allclose(loc_exp, loc_act, atol=1e-2))
self.assertTrue(np.allclose(scale_exp, scale_act, atol=1e-2))
示例5: linear_interpolate_rank
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def linear_interpolate_rank(self):
with tf.Graph().as_default():
# Since rank is 1, the first channel should remain 1.0.
# and the second channel should be interpolated between 1.0 and 6.0
z1 = np.ones(shape=(4, 4, 2))
z2 = np.copy(z1)
z2[:, :, 0] += 0.01
z2[:, :, 1] += 5.0
coeffs = np.linspace(0.0, 1.0, 11)
z1 = np.expand_dims(z1, axis=0)
z2 = np.expand_dims(z2, axis=0)
tensor1 = tf.convert_to_tensor(z1, dtype=tf.float32)
tensor2 = tf.convert_to_tensor(z2, dtype=tf.float32)
lin_interp_max = glow_ops.linear_interpolate_rank(
tensor1, tensor2, coeffs)
with tf.Session() as sess:
lin_interp_np_max = sess.run(lin_interp_max)
for lin_interp_np, coeff in zip(lin_interp_np_max, coeffs):
exp_val = 1.0 + coeff * (6.0 - 1.0)
self.assertTrue(np.allclose(lin_interp_np[:, :, 0], 1.0))
self.assertTrue(np.allclose(lin_interp_np[:, :, 1], exp_val))
示例6: shape_list
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def shape_list(x):
"""Return list of dims, statically where possible."""
x = tf.convert_to_tensor(x)
# If unknown rank, return dynamic shape
if x.get_shape().dims is None:
return tf.shape(x)
static = x.get_shape().as_list()
shape = tf.shape(x)
ret = []
for i, dim in enumerate(static):
if dim is None:
dim = shape[i]
ret.append(dim)
return ret
示例7: cast_like
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def cast_like(x, y):
"""Cast x to y's dtype, if necessary."""
x = tf.convert_to_tensor(x)
y = tf.convert_to_tensor(y)
if x.dtype.base_dtype == y.dtype.base_dtype:
return x
cast_x = tf.cast(x, y.dtype)
if cast_x.device != x.device:
x_name = "(eager Tensor)"
try:
x_name = x.name
except AttributeError:
pass
tf.logging.warning("Cast for %s may induce copy from '%s' to '%s'", x_name,
x.device, cast_x.device)
return cast_x
示例8: testRightShiftBlockwiseND
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def testRightShiftBlockwiseND(self):
tensor = tf.convert_to_tensor(np.array([[
[[1], [2], [3], [4]],
[[5], [6], [7], [8]],
[[9], [10], [11], [12]],
[[13], [14], [15], [16]],
]], dtype=np.float32))
val = common_attention.right_shift_blockwise_nd(tensor, (2, 2))
res = self.evaluate(val)
expected_val = np.array([[
[[0], [1], [6], [3]],
[[2], [5], [4], [7]],
[[8], [9], [14], [11]],
[[10], [13], [12], [15]],
]], dtype=np.float32)
self.assertAllClose(expected_val, res)
示例9: _aspect_preserving_resize
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def _aspect_preserving_resize(image, smallest_side):
"""Resize images preserving the original aspect ratio.
Args:
image: A 3-D image `Tensor`.
smallest_side: A python integer or scalar `Tensor` indicating the size of
the smallest side after resize.
Returns:
resized_image: A 3-D tensor containing the resized image.
"""
smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32)
shape = tf.shape(image)
height = shape[0]
width = shape[1]
new_height, new_width = _smallest_size_at_least(height, width, smallest_side)
image = tf.expand_dims(image, 0)
resized_image = tf.image.resize_images(
image, size=[new_height, new_width], method=tf.image.ResizeMethod.BICUBIC)
resized_image = tf.squeeze(resized_image)
resized_image.set_shape([None, None, 3])
return resized_image
示例10: testShapesAndReconstructions
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def testShapesAndReconstructions(self, transform_name, target_channels):
# Transform the data, test shape
transform = self.transform_pairs[transform_name][0]
target_shape = tuple([self.batch_size]
+ self.spec_shape + [target_channels])
with self.cached_session() as sess:
spectra_np = sess.run(transform(self.audio))
self.assertEqual(spectra_np.shape, target_shape)
# Reconstruct the audio, test shape
inv_transform = self.transform_pairs[transform_name][1]
with self.cached_session() as sess:
recon_np = sess.run(inv_transform(tf.convert_to_tensor(spectra_np)))
self.assertEqual(recon_np.shape, (self.batch_size, self.audio_length, 1))
# Test reconstruction error
# Mel compression adds differences so skip
if transform_name != 'melspecgrams':
# Edges have known differences due to windowing
edge = self.spec_shape[1] * 2
diff = np.abs(self.audio_np[:, edge:-edge] - recon_np[:, edge:-edge])
rms = np.mean(diff**2.0)**0.5
print(transform_name, 'RMS:', rms)
self.assertLessEqual(rms, 1e-5)
示例11: _call_sampler
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def _call_sampler(sample_n_fn, sample_shape, name=None):
"""Reshapes vector of samples."""
with tf.name_scope(name, "call_sampler", values=[sample_shape]):
sample_shape = tf.convert_to_tensor(
sample_shape, dtype=tf.int32, name="sample_shape")
# Ensure sample_shape is a vector (vs just a scalar).
pad = tf.cast(tf.equal(tf.rank(sample_shape), 0), tf.int32)
sample_shape = tf.reshape(
sample_shape,
tf.pad(tf.shape(sample_shape),
paddings=[[pad, 0]],
constant_values=1))
samples = sample_n_fn(tf.reduce_prod(sample_shape))
batch_event_shape = tf.shape(samples)[1:]
final_shape = tf.concat([sample_shape, batch_event_shape], 0)
return tf.reshape(samples, final_shape)
示例12: categorical_sample
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def categorical_sample(logits, dtype=tf.int32,
sample_shape=(), seed=None):
"""Samples from categorical distribution."""
logits = tf.convert_to_tensor(logits, name="logits")
event_size = tf.shape(logits)[-1]
batch_shape_tensor = tf.shape(logits)[:-1]
def _sample_n(n):
"""Sample vector of categoricals."""
if logits.shape.ndims == 2:
logits_2d = logits
else:
logits_2d = tf.reshape(logits, [-1, event_size])
sample_dtype = tf.int64 if logits.dtype.size > 4 else tf.int32
draws = tf.multinomial(
logits_2d, n, seed=seed, output_dtype=sample_dtype)
draws = tf.reshape(
tf.transpose(draws),
tf.concat([[n], batch_shape_tensor], 0))
return tf.cast(draws, dtype)
return _call_sampler(_sample_n, sample_shape)
示例13: __init__
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def __init__(self, sample_fn, sample_shape, sample_dtype,
start_inputs, end_fn, next_inputs_fn=None):
"""Initializer.
Args:
sample_fn: A callable that takes `outputs` and emits tensor `sample_ids`.
sample_shape: Either a list of integers, or a 1-D Tensor of type `int32`,
the shape of the each sample in the batch returned by `sample_fn`.
sample_dtype: the dtype of the sample returned by `sample_fn`.
start_inputs: The initial batch of inputs.
end_fn: A callable that takes `sample_ids` and emits a `bool` vector
shaped `[batch_size]` indicating whether each sample is an end token.
next_inputs_fn: (Optional) A callable that takes `sample_ids` and returns
the next batch of inputs. If not provided, `sample_ids` is used as the
next batch of inputs.
"""
self._sample_fn = sample_fn
self._end_fn = end_fn
self._sample_shape = tf.TensorShape(sample_shape)
self._sample_dtype = sample_dtype
self._next_inputs_fn = next_inputs_fn
self._batch_size = tf.shape(start_inputs)[0]
self._start_inputs = tf.convert_to_tensor(
start_inputs, name="start_inputs")
示例14: test_pad_image_tensor_to_spec_shape
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def test_pad_image_tensor_to_spec_shape(self):
varlen_spec = utils.ExtendedTensorSpec(
shape=(3, 2, 2, 1),
dtype=tf.uint8,
name='varlen',
data_format='png',
varlen_default_value=3.0)
test_data = [[
[[[1]] * 2] * 2,
[[[2]] * 2] * 2,
]]
prepadded_tensor = tf.convert_to_tensor(test_data, dtype=varlen_spec.dtype)
tensor = utils.pad_or_clip_tensor_to_spec_shape(prepadded_tensor,
varlen_spec)
with self.session() as sess:
np_tensor = sess.run(tensor)
self.assertAllEqual(
np_tensor,
np.array([[
[[[1]] * 2] * 2,
[[[2]] * 2] * 2,
[[[3]] * 2] * 2,
]]))
示例15: maybe_ignore_batch
# 需要导入模块: from tensorflow.compat import v1 [as 别名]
# 或者: from tensorflow.compat.v1 import convert_to_tensor [as 别名]
def maybe_ignore_batch(spec_or_tensors, ignore_batch = False):
"""Optionally strips the batch dimension and returns new spec.
Args:
spec_or_tensors: A dict, (named)tuple, list or a hierarchy thereof filled by
TensorSpecs(subclasses) or Tensors.
ignore_batch: If True, the spec_or_batch's batch dimensions are ignored for
shape comparison.
Returns:
spec_or_tensors: If ignore_batch=True we return a spec structure with the
stripped batch_dimension otherwise we return spec_or_tensors.
"""
if ignore_batch:
def map_fn(spec):
if isinstance(spec, np.ndarray):
spec = tf.convert_to_tensor(spec)
if isinstance(spec, tf.Tensor):
return ExtendedTensorSpec.from_tensor(spec[0])
else:
return ExtendedTensorSpec.from_spec(spec, shape=spec.shape[1:])
return nest.map_structure(
map_fn,
spec_or_tensors)
return spec_or_tensors