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


Python v2.ones方法代码示例

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


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

示例1: ones

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def ones(shape, dtype=float):  # pylint: disable=redefined-outer-name
  """Returns an ndarray with the given shape and type filled with ones.

  Args:
    shape: A fully defined shape. Could be - NumPy array or a python scalar,
      list or tuple of integers, - TensorFlow tensor/ndarray of integer type and
      rank <=1.
    dtype: Optional, defaults to float. The type of the resulting ndarray. Could
      be a python type, a NumPy type or a TensorFlow `DType`.

  Returns:
    An ndarray.
  """
  if dtype:
    dtype = utils.result_type(dtype)
  if isinstance(shape, arrays_lib.ndarray):
    shape = shape.data
  return arrays_lib.tensor_to_ndarray(tf.ones(shape, dtype=dtype)) 
开发者ID:google,项目名称:trax,代码行数:20,代码来源:array_ops.py

示例2: tri

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def tri(N, M=None, k=0, dtype=None):  # pylint: disable=invalid-name,missing-docstring
  M = M if M is not None else N
  if dtype is not None:
    dtype = utils.result_type(dtype)
  else:
    dtype = dtypes.default_float_type()

  if k < 0:
    lower = -k - 1
    if lower > N:
      r = tf.zeros([N, M], dtype)
    else:
      # Keep as tf bool, since we create an upper triangular matrix and invert
      # it.
      o = tf.ones([N, M], dtype=tf.bool)
      r = tf.cast(tf.math.logical_not(tf.linalg.band_part(o, lower, -1)), dtype)
  else:
    o = tf.ones([N, M], dtype)
    if k > M:
      r = o
    else:
      r = tf.linalg.band_part(o, -1, k)
  return utils.tensor_to_ndarray(r) 
开发者ID:google,项目名称:trax,代码行数:25,代码来源:array_ops.py

示例3: test_lbfgs_minimize

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def test_lbfgs_minimize(self):
    """Use L-BFGS algorithm to optimize randomly generated quadratic bowls."""

    np.random.seed(12345)
    dim = 10
    batches = 50
    minima = np.random.randn(batches, dim)
    scales = np.exp(np.random.randn(batches, dim))

    @tff_math.make_val_and_grad_fn
    def quadratic(x):
      return tf.reduce_sum(input_tensor=scales * (x - minima) ** 2, axis=-1)

    start = tf.ones((batches, dim), dtype='float64')

    results = self.evaluate(tff_math.optimizer.lbfgs_minimize(
        quadratic, initial_position=start,
        stopping_condition=tff_math.optimizer.converged_any,
        tolerance=1e-8))

    self.assertTrue(results.converged.any())
    self.assertEqual(results.position.shape, minima.shape)
    self.assertNDArrayNear(
        results.position[results.converged], minima[results.converged], 1e-5) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:26,代码来源:optimizer_test.py

示例4: test_sample_paths_dtypes

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def test_sample_paths_dtypes(self):
    """Sampled paths have the expected dtypes."""
    for dtype in [np.float32, np.float64]:
      drift_fn = lambda t, x: tf.sqrt(t) * tf.ones_like(x, dtype=t.dtype)
      vol_fn = lambda t, x: t * tf.ones([1, 1], dtype=t.dtype)

      paths = self.evaluate(
          euler_sampling.sample(
              dim=1,
              drift_fn=drift_fn, volatility_fn=vol_fn,
              times=[0.1, 0.2],
              num_samples=10,
              initial_state=[0.1],
              time_step=0.01,
              seed=123,
              dtype=dtype))

      self.assertEqual(paths.dtype, dtype) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:20,代码来源:euler_sampling_test.py

示例5: test_maybe_update_along_axis

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def test_maybe_update_along_axis(self, dtype):
    """Tests that the values are updated correctly."""
    tensor = tf.ones([5, 4, 3, 2], dtype=dtype)
    new_tensor = tf.zeros([5, 4, 1, 2], dtype=dtype)
    @tf.function
    def maybe_update_along_axis(do_update):
      return utils.maybe_update_along_axis(
          tensor=tensor, new_tensor=new_tensor, axis=1, ind=2,
          do_update=do_update)
    updated_tensor = maybe_update_along_axis(True)
    with self.subTest(name='Shape'):
      self.assertEqual(updated_tensor.shape, tensor.shape)
    with self.subTest(name='UpdatedVals'):
      self.assertAllEqual(updated_tensor[:, 2, :, :],
                          tf.zeros_like(updated_tensor[:, 2, :, :]))
    with self.subTest(name='NotUpdatedVals'):
      self.assertAllEqual(updated_tensor[:, 1, :, :],
                          tf.ones_like(updated_tensor[:, 2, :, :]))
    with self.subTest(name='DoNotUpdateVals'):
      not_updated_tensor = maybe_update_along_axis(False)
      self.assertAllEqual(not_updated_tensor, tensor) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:23,代码来源:utils_test.py

示例6: outer_multiply

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

示例7: test_sample_paths_dtypes

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def test_sample_paths_dtypes(self):
    """Sampled paths have the expected dtypes."""
    for dtype in [np.float32, np.float64]:
      drift_fn = lambda t, x: tf.sqrt(t) * tf.ones_like(x, dtype=t.dtype)
      vol_fn = lambda t, x: t * tf.ones([1, 1], dtype=t.dtype)
      process = GenericItoProcess(
          dim=1, drift_fn=drift_fn, volatility_fn=vol_fn, dtype=dtype)

      paths = self.evaluate(
          process.sample_paths(
              times=[0.1, 0.2],
              num_samples=10,
              initial_state=[0.1],
              time_step=0.01,
              seed=123))
      self.assertEqual(paths.dtype, dtype)

  # Several tests below are unit tests for GenericItoProcess.fd_solver_backward:
  # they mock out the pde solver and check only the conversion of SDE to PDE,
  # but not PDE solving. There are also integration tests further below. 
开发者ID:google,项目名称:tf-quant-finance,代码行数:22,代码来源:generic_ito_process_test.py

示例8: nonneg_softmax

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def nonneg_softmax(expr,
                   replace_nonpositives = -10):
  """A softmax operator that is appropriate for NQL outputs.

  NeuralQueryExpressions often evaluate to sparse vectors of small, nonnegative
  values. Softmax for those is dominated by zeros, so this is a fix.  This also
  fixes the problem that minibatches for NQL are one example per column, not one
  example per row.

  Args:
    expr: a Tensorflow expression for some predicted values.
    replace_nonpositives: will replace zeros with this value before computing
      softmax.

  Returns:
    Tensorflow expression for softmax.
  """
  if replace_nonpositives != 0.0:
    ones = tf.ones(tf.shape(input=expr), tf.float32)
    expr = tf.where(expr > 0.0, expr, ones * replace_nonpositives)
  return tf.nn.softmax(expr) 
开发者ID:google-research,项目名称:language,代码行数:23,代码来源:__init__.py

示例9: nonneg_crossentropy

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def nonneg_crossentropy(expr, target):
  """A cross entropy operator that is appropriate for NQL outputs.

  Query expressions often evaluate to sparse vectors.  This evaluates cross
  entropy safely.

  Args:
    expr: a Tensorflow expression for some predicted values.
    target: a Tensorflow expression for target values.

  Returns:
    Tensorflow expression for cross entropy.
  """
  expr_replacing_0_with_1 = \
     tf.where(expr > 0, expr, tf.ones(tf.shape(input=expr), tf.float32))
  cross_entropies = tf.reduce_sum(
      input_tensor=-target * tf.math.log(expr_replacing_0_with_1), axis=1)
  return tf.reduce_mean(input_tensor=cross_entropies, axis=0) 
开发者ID:google-research,项目名称:language,代码行数:20,代码来源:__init__.py

示例10: testBatchApply

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def testBatchApply(self):
    time_dim = 4
    batch_dim = 5
    inputs = {
        'a': tf.zeros(shape=(time_dim, batch_dim)),
        'b': {
            'b_1': tf.ones(shape=(time_dim, batch_dim, 9, 10)),
            'b_2': tf.ones(shape=(time_dim, batch_dim, 6)),
        }
    }

    def f(tensors):
      np.testing.assert_array_almost_equal(
          np.zeros(shape=(time_dim * batch_dim)), tensors['a'].numpy())
      np.testing.assert_array_almost_equal(
          np.ones(shape=(time_dim * batch_dim, 9, 10)),
          tensors['b']['b_1'].numpy())
      np.testing.assert_array_almost_equal(
          np.ones(shape=(time_dim * batch_dim, 6)), tensors['b']['b_2'].numpy())

      return tf.ones(shape=(time_dim * batch_dim, 2))

    result = utils.batch_apply(f, inputs)
    np.testing.assert_array_almost_equal(
        np.ones(shape=(time_dim, batch_dim, 2)), result.numpy()) 
开发者ID:google-research,项目名称:valan,代码行数:27,代码来源:utils_test.py

示例11: _neck

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def _neck(self, torso_output, state):
    # Verify state. It could have been reset if done was true.
    expected_state = np.copy(self._current_state.numpy())
    done = self._done[self._timestep]
    for i, d in enumerate(done):
      if d:
        expected_state[i] = np.zeros(self._init_state_size)
    np.testing.assert_array_almost_equal(expected_state, state.numpy())
    # Verify torso_output
    expected_torso_output = np.concatenate([
        np.ones(shape=(self._batch_size, 50)),
        np.zeros(shape=(self._batch_size, 50))
    ],
                                           axis=1)
    np.testing.assert_array_almost_equal(expected_torso_output,
                                         torso_output.numpy())
    self._timestep += 1
    self._current_state = state + 1
    return (tf.ones([self._batch_size, 6]) * self._timestep,
            self._current_state) 
开发者ID:google-research,项目名称:valan,代码行数:22,代码来源:base_agent_test.py

示例12: testConv

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def testConv(self):
    y = extensions.conv(
        np.ones([5, 320, 480, 3], dtype=np.float32),
        np.ones([3, 4, 3, 11], dtype=np.float32), [1, 1], "SAME",
        ("NHWC", "HWIO", "NHWC"))
    self.assertAllClose(y.shape, [5, 320, 480, 11])
    self.assertAllClose(
        y,
        tf.nn.conv2d(
            input=tf.ones([5, 320, 480, 3], dtype=tf.float32),
            filters=tf.ones([3, 4, 3, 11], dtype=tf.float32),
            strides=1,
            padding="SAME")) 
开发者ID:google,项目名称:trax,代码行数:15,代码来源:extensions_test.py

示例13: testAvgPool

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def testAvgPool(self):
    y = extensions.avg_pool(np.ones([5, 320, 480, 3]), [3, 5], [2, 3], "VALID")
    self.assertAllEqual(
        y,
        tf.nn.pool(
            input=tf.ones([5, 320, 480, 3]),
            window_shape=[3, 5],
            pooling_type="AVG",
            padding="VALID",
            strides=[2, 3],
        )) 
开发者ID:google,项目名称:trax,代码行数:13,代码来源:extensions_test.py

示例14: testMaxPool

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def testMaxPool(self):
    y = extensions.max_pool(np.ones([5, 320, 480, 3]), [3, 5], [2, 3], "VALID")
    self.assertAllEqual(
        y,
        tf.nn.pool(
            input=tf.ones([5, 320, 480, 3]),
            window_shape=[3, 5],
            pooling_type="MAX",
            padding="VALID",
            strides=[2, 3],
        )) 
开发者ID:google,项目名称:trax,代码行数:13,代码来源:extensions_test.py

示例15: eye

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import ones [as 别名]
def eye(N, M=None, k=0, dtype=float):  # pylint: disable=invalid-name,missing-docstring
  if dtype:
    dtype = utils.result_type(dtype)
  if not M:
    M = N
  # Making sure N, M and k are `int`
  N = int(N)
  M = int(M)
  k = int(k)
  if k >= M or -k >= N:
    # tf.linalg.diag will raise an error in this case
    return zeros([N, M], dtype=dtype)
  if k == 0:
    return arrays_lib.tensor_to_ndarray(tf.eye(N, M, dtype=dtype))
  # We need the precise length, otherwise tf.linalg.diag will raise an error
  diag_len = min(N, M)
  if k > 0:
    if N >= M:
      diag_len -= k
    elif N + k > M:
      diag_len = M - k
  elif k <= 0:
    if M >= N:
      diag_len += k
    elif M - k > N:
      diag_len = N + k
  diagonal_ = tf.ones([diag_len], dtype=dtype)
  return arrays_lib.tensor_to_ndarray(
      tf.linalg.diag(diagonal=diagonal_, num_rows=N, num_cols=M, k=k)) 
开发者ID:google,项目名称:trax,代码行数:31,代码来源:array_ops.py


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