当前位置: 首页>>代码示例>>Python>>正文


Python v2.squeeze方法代码示例

本文整理汇总了Python中tensorflow.compat.v2.squeeze方法的典型用法代码示例。如果您正苦于以下问题:Python v2.squeeze方法的具体用法?Python v2.squeeze怎么用?Python v2.squeeze使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tensorflow.compat.v2的用法示例。


在下文中一共展示了v2.squeeze方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: squeeze

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [as 别名]
def squeeze(a, axis=None):
  """Removes single-element axes from 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`.
    axis: scalar or list/tuple of ints.

  TODO(srbs): tf.squeeze throws error when axis is a Tensor eager execution
  is enabled. So we cannot allow axis to be array_like here. Fix.

  Returns:
    An ndarray.
  """
  a = asarray(a)
  return utils.tensor_to_ndarray(tf.squeeze(a, axis)) 
开发者ID:google,项目名称:trax,代码行数:18,代码来源:array_ops.py

示例2: testHomogeneous

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [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) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:23,代码来源:time_marching_schemes_test.py

示例3: testHomogeneousBackwards

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [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) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:22,代码来源:time_marching_schemes_test.py

示例4: testInhomogeneous

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [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) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:26,代码来源:time_marching_schemes_test.py

示例5: testInhomogeneousBackwards

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [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) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:27,代码来源:time_marching_schemes_test.py

示例6: _apply_tridiag_matrix_explicitly

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [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 
开发者ID:google,项目名称:tf-quant-finance,代码行数:23,代码来源:douglas_adi.py

示例7: test_univariate_sample_mean_and_variance

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [as 别名]
def test_univariate_sample_mean_and_variance(self, dtype):
    """Tests the mean and vol of the univariate GBM sampled paths."""
    process = tff.models.GeometricBrownianMotion(0.05, 0.5, dtype=dtype)
    samples = process.sample_paths(
        times=[0.1, 0.5, 1.0], initial_state=2.0,
        random_type=tff.math.random.RandomType.SOBOL, num_samples=10000)
    log_s = tf.math.log(samples)
    mean = tf.reduce_mean(log_s, axis=0, keepdims=True)
    var = tf.reduce_mean((log_s - mean)**2, axis=0)
    expected_mean = ((process._mu - process._sigma**2 / 2)
                     * np.array([0.1, 0.5, 1.0]) + np.log(2.))
    expected_var = process._sigma**2 * np.array([0.1, 0.5, 1.0])
    with self.subTest("Drift"):
      self.assertAllClose(tf.squeeze(mean), expected_mean, atol=1e-3, rtol=1e-3)
    with self.subTest("Variance"):
      self.assertAllClose(tf.squeeze(var), expected_var, atol=1e-3, rtol=1e-3) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:18,代码来源:geometric_brownian_motion_test.py

示例8: _get_parameters

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [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 
开发者ID:google,项目名称:tf-quant-finance,代码行数:24,代码来源:vector_hull_white.py

示例9: sparse_top_k_categorical_accuracy

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [as 别名]
def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
  """TPU version of sparse_top_k_categorical_accuracy."""
  y_pred_rank = tf.convert_to_tensor(y_pred).get_shape().ndims
  y_true_rank = tf.convert_to_tensor(y_true).get_shape().ndims
  # If the shape of y_true is (num_samples, 1), squeeze to (num_samples,)
  if ((y_true_rank is not None) and
      (y_pred_rank is not None) and
      (len(tf.keras.backend.int_shape(y_true)) ==
       len(tf.keras.backend.int_shape(y_pred)))):
    y_true = tf.squeeze(y_true, [-1])

  y_true = tf.cast(y_true, 'int32')
  return tf.nn.in_top_k(y_true, y_pred, k) 
开发者ID:artyompal,项目名称:tpu_models,代码行数:15,代码来源:resnet50_tf2.py

示例10: test_data_fitting

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [as 别名]
def test_data_fitting(self):
    """Tests MLE estimation for a simple geometric GLM."""
    n, dim = 100, 3
    dtype = tf.float64
    np.random.seed(234095)
    x = np.random.choice([0, 1], size=[dim, n])
    s = 0.01 * np.sum(x, 0)
    p = 1. / (1 + np.exp(-s))
    y = np.random.geometric(p)
    x_data = tf.convert_to_tensor(value=x, dtype=dtype)
    y_data = tf.expand_dims(tf.convert_to_tensor(value=y, dtype=dtype), -1)

    def neg_log_likelihood(state):
      state_ext = tf.expand_dims(state, 0)
      linear_part = tf.matmul(state_ext, x_data)
      linear_part_ex = tf.stack([tf.zeros_like(linear_part), linear_part],
                                axis=0)
      term1 = tf.squeeze(
          tf.matmul(tf.reduce_logsumexp(linear_part_ex, axis=0), y_data), -1)
      term2 = (0.5 * tf.reduce_sum(state_ext * state_ext, axis=-1) -
               tf.reduce_sum(linear_part, axis=-1))
      return tf.squeeze(term1 + term2)

    self._check_algorithm(
        func=neg_log_likelihood,
        start_point=np.ones(shape=[dim]),
        expected_argmin=[-0.020460034354, 0.171708568111, 0.021200423717]) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:29,代码来源:conjugate_gradient_test.py

示例11: _adjust_convexity

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [as 别名]
def _adjust_convexity(self, valuation_date, market, model, pricing_context,
                        cms_rates, discount_factors):
    """Computes the convexity adjusted cms rate."""
    if model is None:
      return cms_rates
    elif model in (
        rc.InterestRateModelType.LOGNORMAL_SMILE_CONSISTENT_REPLICATION,
        rc.InterestRateModelType.NORMAL_SMILE_CONSISTENT_REPLICATION):
      return self._convexity_smile_replication(
          valuation_date, market, model, cms_rates, pricing_context)
    else:
      level = self._swap.annuity(valuation_date, market, None)
      expiry_time = dates.daycount_actual_365_fixed(
          start_date=valuation_date,
          end_date=self._coupon_start_dates,
          dtype=self._dtype)
      with tf.GradientTape() as g:
        g.watch(cms_rates)
        fx = self._fs(cms_rates)
      dfx = tf.squeeze(g.gradient(fx, cms_rates))
      swap_vol = tf.convert_to_tensor(pricing_context, dtype=self._dtype)
      if model == rc.InterestRateModelType.LOGNORMAL_RATE:
        cms_rates = cms_rates + dfx * level * (cms_rates**2) * (
            tf.math.exp(swap_vol**2 * expiry_time) - 1.0) / discount_factors
      else:
        cms_rates = cms_rates + dfx * level * (
            swap_vol**2 * expiry_time) / discount_factors
      return cms_rates 
开发者ID:google,项目名称:tf-quant-finance,代码行数:30,代码来源:cms_swap.py

示例12: _f_atm_first_derivative

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [as 别名]
def _f_atm_first_derivative(self, s, cms_rates):
    """Computes first order derivative of _f_atm."""
    with tf.GradientTape() as g:
      g.watch(s)
      fx = self._f_atm(s, cms_rates)
    dfx = tf.squeeze(g.gradient(fx, s))
    return dfx 
开发者ID:google,项目名称:tf-quant-finance,代码行数:9,代码来源:cms_swap.py

示例13: _f_atm_second_derivative

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [as 别名]
def _f_atm_second_derivative(self, s, cms_rates):
    """Computes second order derivative of _f_atm."""
    with tf.GradientTape() as g:
      g.watch(s)
      with tf.GradientTape() as gg:
        gg.watch(s)
        fx = self._f_atm(s, cms_rates)
      dfx = tf.squeeze(gg.gradient(fx, s))
    d2fx = tf.squeeze(g.gradient(dfx, s))
    return d2fx 
开发者ID:google,项目名称:tf-quant-finance,代码行数:12,代码来源:cms_swap.py

示例14: _put_valuer

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [as 别名]
def _put_valuer(sample_paths, time_index, strike_price, dtype=None, name=None):
  """Produces a callable from samples to payoff of a simple basket put option.

  Args:
    sample_paths: A `Tensor` of either `flaot32` or `float64` dtype and of
      shape `[num_samples, num_times, dim]`.
    time_index: An integer scalar `Tensor` that corresponds to the time
      coordinate at which the basis function is computed.
    strike_price: A `Tensor` of the same `dtype` as `sample_paths` and shape
      `[num_samples, num_strikes]`.
    dtype: Optional `dtype`. Either `tf.float32` or `tf.float64`. The `dtype`
      If supplied, represents the `dtype` for the 'strike_price' as well as
      for the input argument of the output payoff callable.
      Default value: `None`, which means that the `dtype` inferred by TensorFlow
      is used.
    name: Python `str` name prefixed to Ops created by the callable created
      by this function.
      Default value: `None` which is mapped to the default name 'put_valuer'

  Returns:
    A callable from `Tensor` of shape `[num_samples, num_exercise_times, dim]`
    and a scalar `Tensor` representing current time to a `Tensor` of shape
    `[num_samples, num_strikes]`.
  """
  name = name or "put_valuer"
  with tf.name_scope(name):
    strike_price = tf.convert_to_tensor(strike_price, dtype=dtype,
                                        name="strike_price")
    sample_paths = tf.convert_to_tensor(sample_paths, dtype=dtype,
                                        name="sample_paths")
    num_samples, _, dim = sample_paths.shape.as_list()

    slice_sample_paths = tf.slice(sample_paths, [0, time_index, 0],
                                  [num_samples, 1, dim])
    slice_sample_paths = tf.squeeze(slice_sample_paths, 1)
    average = tf.math.reduce_mean(slice_sample_paths, axis=-1, keepdims=True)
    return tf.nn.relu(strike_price - average) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:39,代码来源:payoff.py

示例15: _expected_exercise_fn

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import squeeze [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) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:40,代码来源:lsm_v2.py


注:本文中的tensorflow.compat.v2.squeeze方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。