本文整理汇总了Python中tensorflow.compat.v2.transpose方法的典型用法代码示例。如果您正苦于以下问题:Python v2.transpose方法的具体用法?Python v2.transpose怎么用?Python v2.transpose使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.transpose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reshape
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def reshape(a, newshape, order='C'):
"""order argument can only b 'C' or 'F'."""
if order not in {'C', 'F'}:
raise ValueError('Unsupported order argument {}'.format(order))
a = asarray(a)
if isinstance(newshape, arrays_lib.ndarray):
newshape = newshape.data
if isinstance(newshape, int):
newshape = [newshape]
if order == 'F':
r = tf.transpose(tf.reshape(tf.transpose(a.data), newshape[::-1]))
else:
r = tf.reshape(a.data, newshape)
return utils.tensor_to_ndarray(r)
示例2: transpose
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def transpose(a, axes=None):
"""Permutes dimensions of the array.
Args:
a: array_like. Could be an ndarray, a Tensor or any object that can
be converted to a Tensor using `tf.convert_to_tensor`.
axes: array_like. A list of ints with length rank(a) or None specifying the
order of permutation. The i'th dimension of the output array corresponds
to axes[i]'th dimension of the `a`. If None, the axes are reversed.
Returns:
An ndarray.
"""
a = asarray(a)
if axes is not None:
axes = asarray(axes)
return utils.tensor_to_ndarray(tf.transpose(a=a.data, perm=axes))
示例3: rot90
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def rot90(m, k=1, axes=(0, 1)): # pylint: disable=missing-docstring
m_rank = tf.rank(m)
ax1, ax2 = utils._canonicalize_axes(axes, m_rank) # pylint: disable=protected-access
k = k % 4
if k == 0:
return m
elif k == 2:
return flip(flip(m, ax1), ax2)
else:
perm = tf.range(m_rank)
perm = tf.tensor_scatter_nd_update(perm, [[ax1], [ax2]], [ax2, ax1])
if k == 1:
return transpose(flip(m, ax2), perm)
else:
return flip(transpose(m, perm), ax2)
示例4: _apply_tridiag_matrix_explicitly
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _apply_tridiag_matrix_explicitly(values, superdiag, diag, subdiag,
dim, n_dims):
"""Applies tridiagonal matrix explicitly."""
perm = _get_permutation(values, n_dims, dim)
# Make the given dimension the last one in the tensors, treat all the
# other spatial dimensions as batch dimensions.
if perm is not None:
values = tf.transpose(values, perm)
superdiag, diag, subdiag = (
tf.transpose(c, perm) for c in (superdiag, diag, subdiag))
values = tf.squeeze(
tf.linalg.tridiagonal_matmul((superdiag, diag, subdiag),
tf.expand_dims(values, -1),
diagonals_format='sequence'), -1)
# Transpose back to how it was.
if perm is not None:
values = tf.transpose(values, perm)
return values
示例5: _get_parameters
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _get_parameters(times, *params):
"""Gets parameter values at at specified `times`."""
res = []
for param in params:
if isinstance(param, piecewise.PiecewiseConstantFunc):
jump_locations = param.jump_locations()
if len(jump_locations.shape) > 1:
# If `jump_locations` has batch dimension, transpose the result
# Shape [num_times, dim]
res.append(tf.transpose(param(times)))
else:
# Shape [num_times, dim]
res.append(param(times))
elif callable(param):
# Used only in drift and volatility computation.
# Here `times` is of shape [1]
t = tf.squeeze(times)
# The result has to have shape [1] + param.shape
res.append(tf.expand_dims(param(t), 0))
else:
res.append(param + tf.zeros(times.shape + param.shape, dtype=times.dtype))
return res
示例6: _apply_op
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _apply_op(self, op_fn):
"""Applies given tensor-to-tensor op.
This method is used for implementing ops that take a tensor and return a new
tensor, such as tf.expand_dims or tf.transpose. Implementing wrappers
should apply `op_fn` to the backing tensor(s) and return an new wrapper
instance with the updated backing tensor.
Args:
op_fn: Callable that applies tensor-to-tensor op to the given Tensor.
E.g. applies tf.expand_dims.
Returns:
A TensorWrapper instance with updated backing tensor(s).
"""
raise NotImplementedError()
示例7: _info
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _info(self):
return tfds.core.DatasetInfo(
builder=self,
description=(
"The EMNIST dataset is a set of handwritten character digits "
"derived from the NIST Special Database 19 and converted to "
"a 28x28 pixel image format and dataset structure that directly "
"matches the MNIST dataset.\n\n"
"Note: Like the original EMNIST data, images provided here are "
"inverted horizontally and rotated 90 anti-clockwise. You can use "
"`tf.transpose` within `ds.map` to convert the images to a "
"human-friendlier format."),
features=tfds.features.FeaturesDict({
"image":
tfds.features.Image(shape=MNIST_IMAGE_SHAPE),
"label":
tfds.features.ClassLabel(
num_classes=self.builder_config.class_number),
}),
supervised_keys=("image", "label"),
homepage=("https://www.nist.gov/itl/products-and-services/"
"emnist-dataset"),
citation=_EMNIST_CITATION,
)
示例8: labels_of_top_ranked_predictions_in_batch
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def labels_of_top_ranked_predictions_in_batch(labels, predictions):
"""Applying tf.metrics.mean to this gives precision at 1.
Args:
labels: minibatch of dense 0/1 labels, shape [batch_size rows, num_classes]
predictions: minibatch of predictions of the same shape
Returns:
one-dimension tensor top_labels, where top_labels[i]=1.0 iff the
top-scoring prediction for batch element i has label 1.0
"""
indices_of_top_preds = tf.cast(tf.argmax(input=predictions, axis=1), tf.int32)
batch_size = tf.reduce_sum(input_tensor=tf.ones_like(indices_of_top_preds))
row_indices = tf.range(batch_size)
thresholded_labels = tf.where(labels > 0.0, tf.ones_like(labels),
tf.zeros_like(labels))
label_indices_to_gather = tf.transpose(
a=tf.stack([row_indices, indices_of_top_preds]))
return tf.gather_nd(thresholded_labels, label_indices_to_gather)
示例9: set_initial_value
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def set_initial_value(self, rel_name, m):
"""Provide value that will be used to initialize a relation matrix.
Args:
rel_name: string name of relation
m: a matrix that can used as argument to scipy.coo_matrix, for a sparse
relation, or any matrix, for a dense relation
Raises:
RelationNameError: If the relation cannot be found.
ValueError: If the relation and initial_value have different shapes.
"""
if not self.is_relation(rel_name):
raise RelationNameError(rel_name, 'Relation is not defined.')
expected_shape = self.get_shape(rel_name)
if m.shape[1] != expected_shape[1]:
raise ValueError(
'relation and initial_value have different columns: %d vs %d' %
(expected_shape[1], m.shape[1]))
if self.is_dense(rel_name):
self._np_initval[rel_name] = m.transpose()
else:
self._np_initval[rel_name] = scipy.sparse.coo_matrix(m.transpose())
示例10: _prob
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _prob(self, y):
"""Called by the base class to compute likelihoods."""
# Convert to (channels, 1, batch) format by collapsing dimensions and then
# commuting channels to front.
y = tf.broadcast_to(
y, tf.broadcast_dynamic_shape(tf.shape(y), self.batch_shape_tensor()))
shape = tf.shape(y)
y = tf.reshape(y, (-1, 1, self.batch_shape.num_elements()))
y = tf.transpose(y, (2, 1, 0))
# Evaluate densities.
# We can use the special rule below to only compute differences in the left
# tail of the sigmoid. This increases numerical stability: sigmoid(x) is 1
# for large x, 0 for small x. Subtracting two numbers close to 0 can be done
# with much higher precision than subtracting two numbers close to 1.
lower = self._logits_cumulative(y - .5)
upper = self._logits_cumulative(y + .5)
# Flip signs if we can move more towards the left tail of the sigmoid.
sign = tf.stop_gradient(-tf.math.sign(lower + upper))
p = abs(tf.sigmoid(sign * upper) - tf.sigmoid(sign * lower))
# Convert back to (broadcasted) input tensor shape.
p = tf.transpose(p, (2, 1, 0))
p = tf.reshape(p, shape)
return p
示例11: swapaxes
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def swapaxes(a, axis1, axis2): # pylint: disable=missing-docstring
a = asarray(a)
a_rank = tf.rank(a)
if axis1 < 0:
axis1 += a_rank
if axis2 < 0:
axis2 += a_rank
perm = tf.range(a_rank)
perm = tf.tensor_scatter_nd_update(perm, [[axis1], [axis2]], [axis2, axis1])
a = tf.transpose(a, perm)
return utils.tensor_to_ndarray(a)
示例12: _apply_correction
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _apply_correction(theta, values, explicit_contribution, superdiag, diag,
subdiag, inhomog_term_delta, t1, t2, dim, n_dims):
"""Applies correction for the given dimension."""
rhs = (
values - theta * explicit_contribution +
theta * inhomog_term_delta * (t2 - t1))
# Make the given dimension the last one in the tensors, treat all the
# other spatial dimensions as batch dimensions.
perm = _get_permutation(values, n_dims, dim)
if perm is not None:
rhs = tf.transpose(rhs, perm)
superdiag, diag, subdiag = (
tf.transpose(c, perm) for c in (superdiag, diag, subdiag))
subdiag = -theta * subdiag * (t2 - t1)
diag = 1 - theta * diag * (t2 - t1)
superdiag = -theta * superdiag * (t2 - t1)
result = tf.linalg.tridiagonal_solve((superdiag, diag, subdiag),
rhs,
diagonals_format='sequence',
partial_pivoting=False)
# Transpose back to how it was.
if perm is not None:
result = tf.transpose(result, perm)
return result
示例13: _expected_exercise_fn
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _expected_exercise_fn(design, continuation_value, exercise_value):
"""Returns the expected continuation value for each path.
Args:
design: A real `Tensor` of shape `[basis_size, num_samples]`.
continuation_value: A `Tensor` of shape `[num_samples, payoff_dim]` and of
the same dtype as `design`. The optimal value of the option conditional on
not exercising now or earlier, taking future information into account.
exercise_value: A `Tensor` of the same shape and dtype as
`continuation_value`. Value of the option if exercised immideately at
the current time
Returns:
A `Tensor` of the same shape and dtype as `continuation_value` whose
`(n, v)`-th entry represents the expected continuation value of sample path
`n` under the `v`-th payoff scheme.
"""
batch_design = tf.broadcast_to(
design[..., None], design.shape + [continuation_value.shape[-1]])
mask = tf.cast(exercise_value > 0, design.dtype)
# Zero out contributions from samples we'd never exercise at this point (i.e.,
# these extra observations do not change the regression coefficients).
masked = tf.transpose(batch_design * mask, perm=(2, 1, 0))
# For design matrix X and response y, the coefficients beta of the best linear
# unbiased estimate are contained in the equation X'X beta = X'y. Here `lhs`
# is X'X and `rhs` is X'y, or rather a tensor of such left hand and right hand
# sides, one for each payoff dimension.
lhs = tf.matmul(masked, masked, transpose_a=True)
# Use pseudo inverse for the regression matrix to ensure stability of the
# algorithm.
lhs_pinv = tf.linalg.pinv(lhs)
rhs = tf.matmul(
masked,
tf.expand_dims(tf.transpose(continuation_value), axis=-1),
transpose_a=True)
beta = tf.matmul(lhs_pinv, rhs)
continuation = tf.matmul(tf.transpose(batch_design, perm=(2, 1, 0)), beta)
return tf.maximum(tf.transpose(tf.squeeze(continuation, -1)), 0.0)
示例14: _backward_pde_coeffs
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _backward_pde_coeffs(drift_fn, volatility_fn, discounting):
"""Returns coeffs of the backward PDE."""
def second_order_coeff_fn(t, coord_grid):
sigma = volatility_fn(t, _coord_grid_to_mesh_grid(coord_grid))
sigma_times_sigma_t = tf.linalg.matmul(sigma, sigma, transpose_b=True)
# We currently have [dim, dim] as innermost dimensions, but the returned
# tensor must have [dim, dim] as outermost dimensions.
rank = len(sigma.shape.as_list())
perm = [rank - 2, rank - 1] + list(range(rank - 2))
sigma_times_sigma_t = tf.transpose(sigma_times_sigma_t, perm)
return sigma_times_sigma_t / 2
def first_order_coeff_fn(t, coord_grid):
mu = drift_fn(t, _coord_grid_to_mesh_grid(coord_grid))
# We currently have [dim] as innermost dimension, but the returned
# tensor must have [dim] as outermost dimension.
rank = len(mu.shape.as_list())
perm = [rank - 1] + list(range(rank - 1))
mu = tf.transpose(mu, perm)
return mu
def zeroth_order_coeff_fn(t, coord_grid):
if not discounting:
return None
return -discounting(t, _coord_grid_to_mesh_grid(coord_grid))
return second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn
示例15: _sample_paths
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import transpose [as 别名]
def _sample_paths(self,
times,
num_requested_times,
initial_state,
num_samples,
random_type,
seed,
skip):
"""Returns a sample of paths from the process."""
# Normal draws needed for sampling
normal_draws = utils.generate_mc_normal_draws(
num_normal_draws=1, num_time_steps=num_requested_times,
num_sample_paths=num_samples, random_type=random_type,
seed=seed,
dtype=self._dtype, skip=skip)
times = tf.concat([[0], times], -1)
dt = times[1:] - times[:-1]
# The logarithm of all the increments between the times.
log_increments = ((self._mu - self._sigma**2 / 2) * dt
+ tf.sqrt(dt) * self._sigma
* tf.transpose(tf.squeeze(normal_draws, -1)))
# Since the implementation of tf.math.cumsum is single-threaded we
# use lower-triangular matrix multiplication instead
once = tf.ones([num_requested_times, num_requested_times],
dtype=self._dtype)
lower_triangular = tf.linalg.band_part(once, -1, 0)
cumsum = tf.linalg.matvec(lower_triangular,
log_increments)
samples = initial_state * tf.math.exp(cumsum)
return tf.expand_dims(samples, -1)
# TODO(b/152967694): Remove the duplicate methods.