本文整理汇总了Python中tensorflow.compat.v2.name_scope方法的典型用法代码示例。如果您正苦于以下问题:Python v2.name_scope方法的具体用法?Python v2.name_scope怎么用?Python v2.name_scope使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.compat.v2
的用法示例。
在下文中一共展示了v2.name_scope方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def __init__(self,
shift,
validate_args=False,
name='shift'):
"""Instantiates the `Shift` bijector which computes `Y = g(X; shift) = X + shift`
where `shift` is a numeric `Tensor`.
Args:
shift: Floating-point `Tensor`.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.
"""
with tf.name_scope(name) as name:
dtype = dtype_util.common_dtype([shift], dtype_hint=tf.float32)
self._shift = tensor_util.convert_nonref_to_tensor(shift, dtype=dtype, name='shift')
super(Shift, self).__init__(
forward_min_event_ndims=0,
is_constant_jacobian=True,
dtype=dtype,
validate_args=validate_args,
name=name
)
示例2: __init__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def __init__(self,
mu,
sigma,
dtype=None,
name=None):
"""Initializes the Geometric Brownian Motion.
Args:
mu: Scalar real `Tensor`. Corresponds to the mean of the Ito process.
sigma: Scalar real `Tensor` of the same `dtype` as `mu`. Corresponds to
the volatility of the process.
dtype: The default dtype to use when converting values to `Tensor`s.
Default value: `None` which means that default dtypes inferred by
TensorFlow are used.
name: Python string. The name to give to the ops created by this class.
Default value: `None` which maps to the default name
'geometric_brownian_motion'.
"""
self._name = name or "geometric_brownian_motion"
with tf.name_scope(self._name):
self._mu = tf.convert_to_tensor(mu, dtype=dtype, name="mu")
self._dtype = self._mu.dtype
self._sigma = tf.convert_to_tensor(sigma, dtype=self._dtype, name="sigma")
self._dim = 1
示例3: weighted_by_sum
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def weighted_by_sum(
self, other):
"""Weight elements in some set by the sum of the scores in some other set.
Args:
other: A NeuralQueryExpression
Returns:
The NeuralQueryExpression that evaluates to the reweighted version of
the set obtained by evaluating 'self'.
"""
provenance = NQExprProvenance(
operation='weighted_by_sum',
inner=self.provenance,
other=other.provenance)
with tf.name_scope('weighted_by_sum'):
return self.context.as_nql(
self.tf * tf.reduce_sum(input_tensor=other.tf, axis=1, keepdims=True),
self._type_name, provenance)
示例4: price
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def price(self, valuation_date, market, model=None, pricing_context=None,
name=None):
"""Returns the present value of the instrument on the valuation date.
Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the interest rate swap.
model: Reserved for future use.
pricing_context: Additional context relevant for pricing.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to 'price'.
Returns:
A Rank 1 `Tensor` of real type containing the modeled price of each IRS
contract based on the input market data.
"""
name = name or (self._name + '_price')
with tf.name_scope(name):
valuation_date = dates.convert_to_date_tensor(valuation_date)
pay_cf = self._pay_leg.price(valuation_date, market, model,
pricing_context)
receive_cf = self._receive_leg.price(valuation_date, market, model,
pricing_context)
return receive_cf - pay_cf
示例5: __init__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def __init__(self,
swap,
expiry_date=None,
dtype=None,
name=None):
"""Initialize a batch of European swaptions.
Args:
swap: An instance of `InterestRateSwap` specifying the interest rate
swaps underlying the swaptions. The batch size of the swaptions being
created would be the same as the batch size of the `swap`.
expiry_date: An optional rank 1 `DateTensor` specifying the expiry dates
for each swaption. The shape of the input should be the same as the
batch size of the `swap` input.
Default value: None in which case the option expity date is the same as
the start date of each underlying swap.
dtype: `tf.Dtype`. If supplied the dtype for the real variables or ops
either supplied to the Swaption object or created by the Swaption
object.
Default value: None which maps to the default dtype inferred by
TensorFlow.
name: Python str. The name to give to the ops created by this class.
Default value: `None` which maps to 'swaption'.
"""
self._name = name or 'swaption'
with tf.name_scope(self._name):
self._dtype = dtype
self._expiry_date = dates.convert_to_date_tensor(expiry_date)
self._swap = swap
示例6: __init__
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def __init__(self,
start_date,
end_date,
coupon_spec,
dtype=None,
name=None):
"""Initialize a batch of CMS cashflow streams.
Args:
start_date: A rank 1 `DateTensor` specifying the starting dates of the
accrual of the first coupon of the cashflow stream. The shape of the
input correspond to the numbercof streams being created.
end_date: A rank 1 `DateTensor` specifying the end dates for accrual of
the last coupon in each cashflow stream. The shape of the input should
be the same as that of `start_date`.
coupon_spec: A list of `CMSCouponSpecs` specifying the details of the
coupon payment for the cashflow stream. The length of the list should
be the same as the number of streams being created. Each coupon within
the list must have the same daycount_convention and businessday_rule.
dtype: `tf.Dtype`. If supplied the dtype for the real variables or ops
either supplied to the FloatingCashflowStream object or created by the
object.
Default value: None which maps to the default dtype inferred by
TensorFlow.
name: Python str. The name to give to the ops created by this class.
Default value: `None` which maps to 'floating_cashflow_stream'.
"""
super(CMSCashflowStream, self).__init__()
self._name = name or 'cms_cashflow_stream'
with tf.name_scope(self._name):
self._start_date = dates.convert_to_date_tensor(start_date)
self._end_date = dates.convert_to_date_tensor(end_date)
self._batch_size = self._start_date.shape[0]
self._first_coupon_date = None
self._penultimate_coupon_date = None
self._dtype = dtype
self._setup(coupon_spec)
示例7: price
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def price(self, valuation_date, market, model=None, pricing_context=None,
name=None):
"""Returns the present value of the instrument on the valuation date.
Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the interest rate swap.
model: An optional input of type `InterestRateModelType` to specify the
model to use for `convexity correction` while pricing individual
swaplets of the cms swap. When `model` is
`InterestRateModelType.LOGNORMAL_SMILE_CONSISTENT_REPLICATION` or
`InterestRateModelType.NORMAL_SMILE_CONSISTENT_REPLICATION`, the
function uses static replication (from lognormal and normal swaption
implied volatility data respectively) as described in [1]. When `model`
is `InterestRateModelType.LOGNORMAL_RATE` or
`InterestRateModelType.NORMAL_RATE`, the function uses analytic
approximations for the convexity adjustment based on lognormal and
normal swaption rate dyanmics respectively [1].
Default value: `None` in which case convexity correction is not used.
pricing_context: Additional context relevant for pricing.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to 'price'.
Returns:
A Rank 1 `Tensor` of real type containing the modeled price of each IRS
contract based on the input market data.
#### References:
[1]: Patrick S. Hagan. Convexity conundrums: Pricing cms swaps, caps and
floors. WILMOTT magazine.
"""
name = name or (self._name + '_price')
with tf.name_scope(name):
return super(CMSSwap, self).price(valuation_date, market, model,
pricing_context, name)
示例8: price
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def price(self, valuation_date, market, model=None, pricing_context=None,
name=None):
"""Returns the present value of the stream on the valuation date.
Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the cashflow stream.
model: Reserved for future use.
pricing_context: Additional context relevant for pricing.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to 'price'.
Returns:
A Rank 1 `Tensor` of real type containing the modeled price of each stream
based on the input market data.
"""
del model, pricing_context
name = name or (self._name + '_price')
with tf.name_scope(name):
discount_curve = market.discount_curve
discount_factors = discount_curve.get_discount_factor(
self._payment_dates)
future_cashflows = tf.cast(self._payment_dates >= valuation_date,
dtype=self._dtype)
cashflow_pvs = self._notional * (
future_cashflows * self._daycount_fractions * self._coupon_rate *
discount_factors)
return tf.math.reduce_sum(
tf.reshape(cashflow_pvs, (self._batch_size, self._num_cashflows)),
axis=1)
示例9: price
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def price(self, valuation_date, market, model=None, name=None):
"""Returns the dirty price of the bonds on the valuation date.
Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the bonds.
model: Reserved for future use.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to 'price'.
Returns:
A Rank 1 `Tensor` of real dtype containing the dirty price of each bond
based on the input market data.
"""
name = name or (self._name + '_price')
with tf.name_scope(name):
discount_curve = market.discount_curve
coupon_cf = self._cashflows.price(valuation_date, market, model)
principal_cf = (
self._notional * discount_curve.get_discount_factor(
self._maturity_date)
)
return coupon_cf + principal_cf
示例10: price
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def price(self, valuation_date, market, model=None, name=None):
"""Returns the price of the contract on the valuation date.
Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: An object of type `InterestRateMarket` which contains the
necessary information for pricing the FRA instrument.
model: Reserved for future use.
name: Python string. The name to give this op.
Default value: `None` which maps to `price`.
Returns:
A Rank 1 `Tensor` of real type containing the modeled price of each
futures contract based on the input market data.
"""
del model, valuation_date
name = name or (self._name + '_price')
with tf.name_scope(name):
reference_curve = market.reference_curve
df1 = reference_curve.get_discount_factor(self._accrual_start_dates)
df2 = reference_curve.get_discount_factor(self._accrual_end_dates)
fwd_rates = (df1 / df2 - 1.) / self._accrual_daycount
total_accrual = tf.math.segment_sum(self._daycount_fractions,
self._contract_idx)
if self._averaging_type == rc.AverageType.ARITHMETIC_AVERAGE:
settlement_rate = tf.math.segment_sum(
fwd_rates * self._daycount_fractions,
self._contract_idx) / total_accrual
else:
settlement_rate = (tf.math.segment_prod(
1. + fwd_rates * self._daycount_fractions, self._contract_idx) -
1.) / total_accrual
return 100. * (1. - settlement_rate)
示例11: price
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def price(self, valuation_date, market, model=None, pricing_context=None,
name=None):
"""Returns the present value of the Cap/Floor on the valuation date.
Args:
valuation_date: A scalar `DateTensor` specifying the date on which
valuation is being desired.
market: A namedtuple of type `InterestRateMarket` which contains the
necessary information for pricing the Cap/Floor.
model: An optional input of type `InterestRateModelType` to specify which
model to use for pricing.
Default value: `None` in which case `LOGNORMAL_RATE` model is used.
pricing_context: An optional input to provide additional parameters (such
as model parameters) relevant for pricing.
name: Python str. The name to give to the ops created by this function.
Default value: `None` which maps to `"price"`.
Returns:
A Rank 1 `Tensor` of real type containing the modeled price of each cap
(or floor) based on the input market data.
Raises:
ValueError: If an unsupported model is supplied to the function.
"""
model = model or rc.InterestRateModelType.LOGNORMAL_RATE
name = name or (self._name + '_price')
with tf.name_scope(name):
valuation_date = dates.convert_to_date_tensor(valuation_date)
if model == rc.InterestRateModelType.LOGNORMAL_RATE:
caplet_prices = self._price_lognormal_rate(valuation_date, market,
pricing_context)
else:
raise ValueError(f'Unsupported model {model}.')
return tf.math.segment_sum(caplet_prices, self._contract_index)
示例12: _put_valuer
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [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)
示例13: actual_365_fixed
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def actual_365_fixed(*,
start_date,
end_date,
schedule_info=None,
dtype=None,
name=None):
"""Computes the year fraction between the specified dates.
The actual/365 convention specifies the year fraction between the start and
end date as the actual number of days between the two dates divided by 365.
Note that the schedule info is not needed for this convention and is ignored
if supplied.
For more details see:
https://en.wikipedia.org/wiki/Day_count_convention#Actual/365_Fixed
Args:
start_date: A `DateTensor` object of any shape.
end_date: A `DateTensor` object of compatible shape with `start_date`.
schedule_info: The schedule info. Ignored for this convention.
dtype: The dtype of the result. Either `tf.float32` or `tf.float64`. If not
supplied, `tf.float32` is returned.
name: Python `str` name prefixed to ops created by this function. If not
supplied, `actual_365_fixed` is used.
Returns:
A real `Tensor` of supplied `dtype` and shape of `start_date`. The year
fraction between the start and end date as computed by Actual/365 fixed
convention.
"""
del schedule_info
with tf.name_scope(name or 'actual_365_fixed'):
end_date = dt.convert_to_date_tensor(end_date)
start_date = dt.convert_to_date_tensor(start_date)
dtype = dtype or tf.constant(0.).dtype
actual_days = tf.cast(start_date.days_until(end_date), dtype=dtype)
return actual_days / 365
示例14: nested_ifs_and_context_managers
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def nested_ifs_and_context_managers(x):
with tf.name_scope(''):
if x > 0:
if x < 5:
with tf.name_scope(''):
return x
else:
return x * x
else:
return x * x * x
示例15: unreachable_return
# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import name_scope [as 别名]
def unreachable_return(x):
with tf.name_scope(''):
if x > 0:
if x < 5:
with tf.name_scope(''):
return x
else:
return x * x
else:
return x * x * x
return x * x * x * x