本文整理汇总了Python中tensorflow.compat.v2.expand_dims方法的典型用法代码示例。如果您正苦于以下问题:Python v2.expand_dims方法的具体用法?Python v2.expand_dims怎么用?Python v2.expand_dims使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.expand_dims方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testHomogeneous
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def testHomogeneous(self, scheme, accuracy_order):
# Tests solving du/dt = At for a time step.
# Compares with exact solution u(t) = exp(At) u(0).
# Time step should be small enough to "resolve" different orders of accuracy
time_step = 0.0001
u = tf.constant([1, 2, -1, -2], dtype=tf.float64)
matrix = tf.constant(
[[1, -1, 0, 0], [3, 1, 2, 0], [0, -2, 1, 4], [0, 0, 3, 1]],
dtype=tf.float64)
tridiag_form = self._convert_to_tridiagonal_format(matrix)
actual = self.evaluate(
scheme(u, 0, time_step, lambda t: (tridiag_form, None)))
expected = self.evaluate(
tf.squeeze(
tf.matmul(tf.linalg.expm(matrix * time_step), tf.expand_dims(u,
1))))
error_tolerance = 30 * time_step**(accuracy_order + 1)
self.assertLess(np.max(np.abs(actual - expected)), error_tolerance)
示例2: testHomogeneousBackwards
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def testHomogeneousBackwards(self, scheme, accuracy_order):
# Tests solving du/dt = At for a backward time step.
# Compares with exact solution u(0) = exp(-At) u(t).
time_step = 0.0001
u = tf.constant([1, 2, -1, -2], dtype=tf.float64)
matrix = tf.constant(
[[1, -1, 0, 0], [3, 1, 2, 0], [0, -2, 1, 4], [0, 0, 3, 1]],
dtype=tf.float64)
tridiag_form = self._convert_to_tridiagonal_format(matrix)
actual = self.evaluate(
scheme(u, time_step, 0, lambda t: (tridiag_form, None)))
expected = self.evaluate(
tf.squeeze(
tf.matmul(
tf.linalg.expm(-matrix * time_step), tf.expand_dims(u, 1))))
error_tolerance = 30 * time_step**(accuracy_order + 1)
self.assertLess(np.max(np.abs(actual - expected)), error_tolerance)
示例3: testInhomogeneous
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def testInhomogeneous(self, scheme, accuracy_order):
# Tests solving du/dt = At + b for a time step.
# Compares with exact solution u(t) = exp(At) u(0) + (exp(At) - 1) A^(-1) b.
time_step = 0.0001
u = tf.constant([1, 2, -1, -2], dtype=tf.float64)
matrix = tf.constant(
[[1, -1, 0, 0], [3, 1, 2, 0], [0, -2, 1, 4], [0, 0, 3, 1]],
dtype=tf.float64)
b = tf.constant([1, -1, -2, 2], dtype=tf.float64)
tridiag_form = self._convert_to_tridiagonal_format(matrix)
actual = self.evaluate(scheme(u, 0, time_step, lambda t: (tridiag_form, b)))
exponent = tf.linalg.expm(matrix * time_step)
eye = tf.eye(4, 4, dtype=tf.float64)
u = tf.expand_dims(u, 1)
b = tf.expand_dims(b, 1)
expected = (
tf.matmul(exponent, u) +
tf.matmul(exponent - eye, tf.matmul(tf.linalg.inv(matrix), b)))
expected = self.evaluate(tf.squeeze(expected))
error_tolerance = 30 * time_step**(accuracy_order + 1)
self.assertLess(np.max(np.abs(actual - expected)), error_tolerance)
示例4: testInhomogeneousBackwards
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def testInhomogeneousBackwards(self, scheme, accuracy_order):
# Tests solving du/dt = At + b for a backward time step.
# Compares with exact solution u(0) = exp(-At) u(t)
# + (exp(-At) - 1) A^(-1) b.
time_step = 0.0001
u = tf.constant([1, 2, -1, -2], dtype=tf.float64)
matrix = tf.constant(
[[1, -1, 0, 0], [3, 1, 2, 0], [0, -2, 1, 4], [0, 0, 3, 1]],
dtype=tf.float64)
b = tf.constant([1, -1, -2, 2], dtype=tf.float64)
tridiag_form = self._convert_to_tridiagonal_format(matrix)
actual = self.evaluate(scheme(u, time_step, 0, lambda t: (tridiag_form, b)))
exponent = tf.linalg.expm(-matrix * time_step)
eye = tf.eye(4, 4, dtype=tf.float64)
u = tf.expand_dims(u, 1)
b = tf.expand_dims(b, 1)
expected = (
tf.matmul(exponent, u) +
tf.matmul(exponent - eye, tf.matmul(tf.linalg.inv(matrix), b)))
expected = self.evaluate(tf.squeeze(expected))
error_tolerance = 30 * time_step**(accuracy_order + 1)
self.assertLess(np.max(np.abs(actual - expected)), error_tolerance)
示例5: _apply_tridiag_matrix_explicitly
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [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
示例6: setUp
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def setUp(self):
"""Sets `samples` as in the Longstaff-Schwartz paper."""
super(LsmTest, self).setUp()
# See Longstaff, F.A. and Schwartz, E.S., 2001. Valuing American options by
# simulation: a simple least-squares approach.
samples = [[1.0, 1.09, 1.08, 1.34],
[1.0, 1.16, 1.26, 1.54],
[1.0, 1.22, 1.07, 1.03],
[1.0, 0.93, 0.97, 0.92],
[1.0, 1.11, 1.56, 1.52],
[1.0, 0.76, 0.77, 0.90],
[1.0, 0.92, 0.84, 1.01],
[1.0, 0.88, 1.22, 1.34]]
# Expand dims to reflect that `samples` represent sample paths of
# a 1-dimensional process
self.samples = np.expand_dims(samples, -1)
# Interest rates between exercise times
interest_rates = [0.06, 0.06, 0.06]
# Corresponding discount factors
self.discount_factors = np.exp(-np.cumsum(interest_rates))
示例7: test_expected_continuation
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def test_expected_continuation(self):
"""Tests that expected continuation works in V=1 case.
In particular this verifies that the regression done to get the expected
continuation value is performed on those elements which have a positive
exercise value.
"""
for dtype in (np.float32, np.float64):
a = tf.range(start=-2, limit=3, delta=1, dtype=dtype)
design = tf.concat([a, a], axis=0)
design = tf.concat([[tf.ones_like(design), design]], axis=1)
# These values ensure that the expected continuation value is `(1,...,1).`
exercise_now = tf.expand_dims(
tf.concat([tf.ones_like(a), tf.zeros_like(a)], axis=0), -1)
cashflow = tf.expand_dims(
tf.concat([tf.ones_like(a), -tf.ones_like(a)], axis=0), -1)
expected_exercise = lsm.expected_exercise_fn(
design, cashflow, exercise_now)
self.assertAllClose(expected_exercise, tf.ones_like(cashflow))
示例8: _updated_cashflow
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def _updated_cashflow(num_times, exercise_index, exercise_value,
expected_continuation, cashflow):
"""Revises the cashflow tensor where options will be exercised earlier."""
do_exercise_bool = exercise_value > expected_continuation
do_exercise = tf.cast(do_exercise_bool, exercise_value.dtype)
# Shape [num_samples, payoff_dim]
scaled_do_exercise = tf.where(do_exercise_bool, exercise_value,
tf.zeros_like(exercise_value))
# This picks out the samples where we now wish to exercise.
# Shape [num_samples, payoff_dim, 1]
new_samp_masked = tf.expand_dims(scaled_do_exercise, axis=2)
# This should be one on the current time step and zero otherwise.
# This is an array with nonzero entries showing newly exercised payoffs.
zeros = tf.zeros_like(cashflow)
mask = tf.equal(tf.range(0, num_times), exercise_index - 1)
new_cash = tf.where(mask, new_samp_masked, zeros)
# Has shape [num_samples, payoff_dim, 1]
old_mask = tf.expand_dims(1 - do_exercise, axis=2)
mask = tf.range(0, num_times) >= exercise_index
old_mask = tf.where(mask, old_mask, zeros)
# Shape [num_samples, payoff_dim, num_times]
old_cash = old_mask * cashflow
return new_cash + old_cash
示例9: test_time_dependent_construction
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [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)
示例10: _euler_step
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def _euler_step(*, i, written_count, current_state, result,
drift_fn, volatility_fn, wiener_mean,
num_samples, times, dt, sqrt_dt, keep_mask,
random_type, seed, normal_draws):
"""Performs one step of Euler scheme."""
current_time = times[i + 1]
written_count = tf.cast(written_count, tf.int32)
if normal_draws is not None:
dw = normal_draws[i]
else:
dw = random.mv_normal_sample(
(num_samples,), mean=wiener_mean, random_type=random_type,
seed=seed)
dw = dw * sqrt_dt[i]
dt_inc = dt[i] * drift_fn(current_time, current_state) # pylint: disable=not-callable
dw_inc = tf.linalg.matvec(volatility_fn(current_time, current_state), dw) # pylint: disable=not-callable
next_state = current_state + dt_inc + dw_inc
result = utils.maybe_update_along_axis(
tensor=result,
do_update=keep_mask[i + 1],
ind=written_count,
axis=1,
new_tensor=tf.expand_dims(next_state, axis=1))
written_count += tf.cast(keep_mask[i + 1], dtype=tf.int32)
return i + 1, written_count, next_state, result
示例11: _exact_discretization_setup
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def _exact_discretization_setup(self, dim):
"""Initial setup for efficient computations."""
self._zero_padding = tf.zeros((dim, 1), dtype=self._dtype)
self._jump_locations = tf.concat(
[self._volatility.jump_locations(),
self._mean_reversion.jump_locations()], axis=-1)
self._jump_values_vol = self._volatility(self._jump_locations)
self._jump_values_mr = self._mean_reversion(self._jump_locations)
if dim == 1:
self._padded_knots = tf.concat([
self._zero_padding,
tf.expand_dims(self._jump_locations[:-1], axis=0)
], axis=1)
self._jump_values_vol = tf.expand_dims(self._jump_values_vol, axis=0)
self._jump_values_mr = tf.expand_dims(self._jump_values_mr, axis=0)
self._jump_locations = tf.expand_dims(self._jump_locations, axis=0)
else:
self._padded_knots = tf.concat(
[self._zero_padding, self._jump_locations[:, :-1]], axis=1)
示例12: _compute_yt
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def _compute_yt(self, t, mr_t, sigma_t):
"""Computes y(t) as described in [1], section 10.1.6.1."""
t = tf.repeat(tf.expand_dims(t, axis=0), self._dim, axis=0)
time_index = tf.searchsorted(self._jump_locations, t)
y_between_vol_knots = self._y_integral(
self._padded_knots, self._jump_locations, self._jump_values_vol,
self._jump_values_mr)
y_at_vol_knots = tf.concat(
[self._zero_padding,
_cumsum_using_matvec(y_between_vol_knots)], axis=1)
vn = tf.concat(
[self._zero_padding, self._jump_locations], axis=1)
y_t = self._y_integral(
tf.gather(vn, time_index, batch_dims=1), t, sigma_t, mr_t)
y_t = y_t + tf.gather(y_at_vol_knots, time_index, batch_dims=1)
return tf.math.exp(-2 * mr_t * t) * y_t
示例13: _conditional_variance_x
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def _conditional_variance_x(self, t, mr_t, sigma_t):
"""Computes the variance of x(t), see [1], Eq. 10.41."""
t = tf.repeat(tf.expand_dims(t, axis=0), self._dim, axis=0)
var_x_between_vol_knots = self._variance_int(self._padded_knots,
self._jump_locations,
self._jump_values_vol,
self._jump_values_mr)
varx_at_vol_knots = tf.concat(
[self._zero_padding,
_cumsum_using_matvec(var_x_between_vol_knots)],
axis=1)
time_index = tf.searchsorted(self._jump_locations, t)
vn = tf.concat(
[self._zero_padding,
self._jump_locations], axis=1)
var_x_t = self._variance_int(
tf.gather(vn, time_index, batch_dims=1), t, sigma_t, mr_t)
var_x_t = var_x_t + tf.gather(varx_at_vol_knots, time_index, batch_dims=1)
var_x_t = (var_x_t[:, 1:] - var_x_t[:, :-1]) * tf.math.exp(
-2 * tf.broadcast_to(mr_t, t.shape)[:, 1:] * t[:, 1:])
return var_x_t
示例14: _apply_op
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [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()
示例15: test_call
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import expand_dims [as 别名]
def test_call(self):
env_output = self._env.reset()
observation = tf.nest.map_structure(lambda t: tf.expand_dims(t, 0),
env_output.observation)
initial_agent_state = self._agent.get_initial_state(
observation, batch_size=1)
# Agent always expects time,batch dimensions. First add and then remove.
env_output = utils.add_time_batch_dim(env_output)
agent_output, _ = self._agent(env_output, initial_agent_state)
initial_agent_state = ([
(tf.random.normal([self.batch_size,
512]), tf.random.normal([self.batch_size, 512])),
(tf.random.normal([self.batch_size,
512]), tf.random.normal([self.batch_size, 512]))
], tf.random.normal([self.batch_size, 5, 512]))
agent_output, _ = self._agent(self._test_environment, initial_agent_state)
self.assertEqual(agent_output.policy_logits.shape, [3, 1, 1])