本文整理汇总了Python中tensorflow.compat.v2.reshape方法的典型用法代码示例。如果您正苦于以下问题:Python v2.reshape方法的具体用法?Python v2.reshape怎么用?Python v2.reshape使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.reshape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: diagflat
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def diagflat(v, k=0):
"""Returns a 2-d array with flattened `v` as diagonal.
Args:
v: array_like of any rank. Gets flattened when setting as diagonal. Could be
an ndarray, a Tensor or any object that can be converted to a Tensor using
`tf.convert_to_tensor`.
k: Position of the diagonal. Defaults to 0, the main diagonal. Positive
values refer to diagonals shifted right, negative values refer to
diagonals shifted left.
Returns:
2-d ndarray.
"""
v = asarray(v)
return diag(tf.reshape(v.data, [-1]), k)
示例2: reshape
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [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)
示例3: take
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def take(a, indices, axis=None, out=None, mode='clip'):
"""out argument is not supported, and default mode is clip."""
if out is not None:
raise ValueError('out argument is not supported in take.')
if mode not in {'raise', 'clip', 'wrap'}:
raise ValueError("Invalid mode '{}' for take".format(mode))
a = asarray(a).data
indices = asarray(indices).data
if axis is None:
a = tf.reshape(a, [-1])
axis = 0
axis_size = tf.shape(a, indices.dtype)[axis]
if mode == 'clip':
indices = tf.clip_by_value(indices, 0, axis_size-1)
elif mode == 'wrap':
indices = tf.math.floormod(indices, axis_size)
else:
raise ValueError("The 'raise' mode to take is not supported.")
return utils.tensor_to_ndarray(tf.gather(a, indices, axis=axis))
示例4: argsort
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def argsort(a, axis=-1, kind='quicksort', order=None): # pylint: disable=missing-docstring
# TODO(nareshmodi): make string tensors also work.
if kind not in ('quicksort', 'stable'):
raise ValueError("Only 'quicksort' and 'stable' arguments are supported.")
if order is not None:
raise ValueError("'order' argument to sort is not supported.")
stable = (kind == 'stable')
a = array_ops.array(a).data
def _argsort(a, axis, stable):
if axis is None:
a = tf.reshape(a, [-1])
axis = 0
return tf.argsort(a, axis, stable=stable)
tf_ans = tf.cond(
tf.rank(a) == 0, lambda: tf.constant([0]),
lambda: _argsort(a, axis, stable))
return array_ops.array(tf_ans, dtype=np.intp)
示例5: hessian_as_matrix
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def hessian_as_matrix(function: Callable[[Parameters], tf.Tensor],
parameters: Parameters) -> tf.Tensor:
"""Computes the Hessian of a given function.
Same as `hessian`, although return a matrix of size [w_dim, w_dim], where
`w_dim` is the number of parameters, which makes it easier to work with.
Args:
function: A function for which we want to compute the Hessian.
parameters: Parameters with respect to the Hessian should be computed.
Returns:
A tensor of size [w_dim, w_dim] representing the Hessian.
"""
hessian_as_tensor_list = hessian(function, parameters)
hessian_as_tensor_list = [
tf.reshape(e, [e.shape[0], -1]) for e in hessian_as_tensor_list]
return tf.concat(hessian_as_tensor_list, axis=1)
示例6: test_default_construction_2d
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def test_default_construction_2d(self):
"""Tests the default parameters for 2 dimensional Brownian Motion."""
process = BrownianMotion(dim=2)
self.assertEqual(process.dim(), 2)
drift_fn = process.total_drift_fn()
# Drifts should be zero.
t0 = np.array([0.2, 0.7, 0.9])
delta_t = np.array([0.1, 0.8, 0.3])
t1 = t0 + delta_t
drifts = self.evaluate(drift_fn(t0, t1))
self.assertEqual(drifts.shape, (3, 2))
self.assertArrayNear(drifts.reshape([-1]), np.zeros([3 * 2]), 1e-10)
variances = self.evaluate(process.total_covariance_fn()(t0, t1))
self.assertEqual(variances.shape, (3, 2, 2))
expected_variances = np.eye(2) * delta_t.reshape([-1, 1, 1])
print(variances, expected_variances)
self.assertArrayNear(
variances.reshape([-1]), expected_variances.reshape([-1]), 1e-10)
示例7: test_time_dependent_construction
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def test_time_dependent_construction(self):
"""Tests with time dependent drift and variance."""
def vol_fn(t):
return tf.expand_dims(0.2 - 0.1 * tf.exp(-t), axis=-1)
def variance_fn(t0, t1):
# The instantaneous volatility is 0.2 - 0.1 e^(-t).
tot_var = (t1 - t0) * 0.04 - (tf.exp(-2 * t1) - tf.exp(-2 * t0)) * 0.005
tot_var += 0.04 * (tf.exp(-t1) - tf.exp(-t0))
return tf.reshape(tot_var, [-1, 1, 1])
process = BrownianMotion(
dim=1, drift=0.1, volatility=vol_fn, total_covariance_fn=variance_fn)
t0 = np.array([0.2, 0.7, 0.9])
delta_t = np.array([0.1, 0.8, 0.3])
t1 = t0 + delta_t
drifts = self.evaluate(process.total_drift_fn()(t0, t1))
self.assertArrayNear(drifts, 0.1 * delta_t, 1e-10)
variances = self.evaluate(process.total_covariance_fn()(t0, t1))
self.assertArrayNear(
variances.reshape([-1]), [0.00149104, 0.02204584, 0.00815789], 1e-8)
示例8: outer_multiply
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def outer_multiply(x, y):
"""Performs an outer multiplication of two tensors.
Given two `Tensor`s, `S` and `T` of shape `s` and `t` respectively, the outer
product `P` is a `Tensor` of shape `s + t` whose components are given by:
```none
P_{i1,...ik, j1, ... , jm} = S_{i1...ik} T_{j1, ... jm}
```
Args:
x: A `Tensor` of any shape and numeric dtype.
y: A `Tensor` of any shape and the same dtype as `x`.
Returns:
outer_product: A `Tensor` of shape Shape[x] + Shape[y] and the same dtype
as `x`.
"""
x_shape = tf.shape(x)
padded_shape = tf.concat(
[x_shape, tf.ones(tf.rank(y), dtype=x_shape.dtype)], axis=0)
return tf.reshape(x, padded_shape) * y
示例9: _reshape_inner_dims
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def _reshape_inner_dims(
tensor: tf.Tensor,
shape: tf.TensorShape,
new_shape: tf.TensorShape) -> tf.Tensor:
"""Reshapes tensor to: shape(tensor)[:-len(shape)] + new_shape."""
tensor_shape = tf.shape(tensor)
ndims = shape.rank
tensor.shape[-ndims:].assert_is_compatible_with(shape)
new_shape_inner_tensor = tf.cast(
[-1 if d is None else d for d in new_shape.as_list()], tf.int64)
new_shape_outer_tensor = tf.cast(
tensor_shape[:-ndims], tf.int64)
full_new_shape = tf.concat(
(new_shape_outer_tensor, new_shape_inner_tensor), axis=0)
new_tensor = tf.reshape(tensor, full_new_shape)
new_tensor.set_shape(tensor.shape[:-ndims] + new_shape)
return new_tensor
示例10: _prob
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [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: distance_metric
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def distance_metric(preds, targets):
"""Calculate distances between model predictions and targets within a batch."""
batch_size = preds.shape[0]
preds = tf.reshape(
preds, [batch_size, DOWNSCALED_PANO_HEIGHT, DOWNSCALED_PANO_WIDTH])
targets = tf.reshape(
targets, [batch_size, DOWNSCALED_PANO_HEIGHT, DOWNSCALED_PANO_WIDTH])
distances = []
for pred, target in zip(preds, targets):
pred_coord = np.unravel_index(np.argmax(pred), pred.shape)
target_coord = np.unravel_index(np.argmax(target), target.shape)
dist = np.sqrt((target_coord[0] - pred_coord[0])**2 +
(target_coord[1] - pred_coord[1])**2)
dist = dist * RESOLUTION_MULTIPLIER
distances.append(dist)
return distances
示例12: postprocessing
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def postprocessing(self, env_output):
observation = env_output.observation
# [time_step, 1]
is_start = observation[constants.IS_START].numpy()
cnt = 0
mask = []
for i in range(is_start.shape[0]):
cnt += is_start[i]
if cnt == 1:
mask.append(True)
else:
mask.append(False)
mask = tf.reshape(tf.convert_to_tensor(mask), is_start.shape)
observation[constants.DISC_MASK] = mask
env_output = env_output._replace(observation=observation)
return env_output
示例13: _generate_examples
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def _generate_examples(self, path):
"""Yields examples."""
clean_key = "clean"
adversarial_key = "adversarial"
def _parse(serialized_example):
ds_features = {
"height": tf.io.FixedLenFeature([], tf.int64),
"width": tf.io.FixedLenFeature([], tf.int64),
"label": tf.io.FixedLenFeature([], tf.int64),
"adv-image": tf.io.FixedLenFeature([], tf.string),
"clean-image": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(serialized_example, ds_features)
img_clean = tf.io.decode_raw(example["clean-image"], tf.float32)
img_adv = tf.io.decode_raw(example["adv-image"], tf.float32)
# float values are integers in [0.0, 255.0] for clean and adversarial
img_clean = tf.cast(img_clean, tf.uint8)
img_clean = tf.reshape(img_clean, (example["height"], example["width"], 3))
img_adv = tf.cast(img_adv, tf.uint8)
img_adv = tf.reshape(img_adv, (example["height"], example["width"], 3))
return {clean_key: img_clean, adversarial_key: img_adv}, example["label"]
ds = tf.data.TFRecordDataset(filenames=[path])
ds = ds.map(lambda x: _parse(x))
default_graph = tf.compat.v1.keras.backend.get_session().graph
ds = tfds.as_numpy(ds, graph=default_graph)
for i, (img, label) in enumerate(ds):
yield str(i), {
"images": img,
"label": label,
}
示例14: full
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def full(shape, fill_value, dtype=None): # pylint: disable=redefined-outer-name
"""Returns an array with given shape and dtype filled with `fill_value`.
Args:
shape: A valid shape object. Could be a native python object or an object
of type ndarray, numpy.ndarray or tf.TensorShape.
fill_value: array_like. Could be an ndarray, a Tensor or any object that can
be converted to a Tensor using `tf.convert_to_tensor`.
dtype: Optional, defaults to dtype of the `fill_value`. The type of the
resulting ndarray. Could be a python type, a NumPy type or a TensorFlow
`DType`.
Returns:
An ndarray.
Raises:
ValueError: if `fill_value` can not be broadcast to shape `shape`.
"""
fill_value = asarray(fill_value, dtype=dtype)
if utils.isscalar(shape):
shape = tf.reshape(shape, [1])
return arrays_lib.tensor_to_ndarray(tf.broadcast_to(fill_value.data, shape))
# Using doc only here since np full_like signature doesn't seem to have the
# shape argument (even though it exists in the documentation online).
示例15: ravel
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reshape [as 别名]
def ravel(a): # pylint: disable=missing-docstring
a = asarray(a)
if a.ndim == 1:
return a
return utils.tensor_to_ndarray(tf.reshape(a.data, [-1]))