Python tensorflow.compat.v2.convert_to_tensor() Examples
The following are 30
code examples of tensorflow.compat.v2.convert_to_tensor().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
tensorflow.compat.v2
, or try the search function
.
Example #1
Source File: logic_test.py From trax with Apache License 2.0 | 6 votes |
def setUp(self): super(LogicTest, self).setUp() self.array_transforms = [ lambda x: x, # Identity, tf.convert_to_tensor, np.array, lambda x: np.array(x, dtype=np.int32), lambda x: np.array(x, dtype=np.int64), lambda x: np.array(x, dtype=np.float32), lambda x: np.array(x, dtype=np.float64), array_ops.array, lambda x: array_ops.array(x, dtype=tf.int32), lambda x: array_ops.array(x, dtype=tf.int64), lambda x: array_ops.array(x, dtype=tf.float32), lambda x: array_ops.array(x, dtype=tf.float64), ]
Example #2
Source File: rate_curve.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def ratecurve_from_discounting_function(discount_fn, dtype=None): """Returns `RateCurve` object using the supplied function for discounting. Args: discount_fn: A python callable which takes a `DateTensor` as an input and returns the corresponding discount factor as an output. dtype: `tf.Dtype`. Optional input specifying the dtype of the real tensors and ops. Returns: An object of class `RateCurveFromDiscountingFunction` which uses the supplied function for discounting. """ dtype = dtype or tf.constant(0.0).dtype pseudo_maturity_dates = dates.convert_to_date_tensor([(2020, 1, 1)]) pseudo_rates = tf.convert_to_tensor([0.0], dtype=dtype) pseudo_valuation_date = dates.convert_to_date_tensor((2020, 1, 1)) return RateCurveFromDiscountingFunction( pseudo_maturity_dates, pseudo_rates, pseudo_valuation_date, discount_fn, dtype)
Example #3
Source File: cap_floor.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def _get_forward_rate(self, valuation_date, market): """Returns the relevant forward rates from the market data.""" forward_rates = market.reference_curve.get_forward_rate( self._accrual_start_dates, self._accrual_end_dates, self._daycount_fractions) forward_rates = tf.where(self._daycount_fractions > 0.0, forward_rates, tf.zeros_like(forward_rates)) libor_rate = rc.get_rate_index( market, self._start_date, rc.RateIndexType.LIBOR, dtype=self._dtype) libor_rate = tf.repeat( tf.convert_to_tensor(libor_rate, dtype=self._dtype), self._num_caplets) forward_rates = tf.where( self._accrual_end_dates < valuation_date, tf.constant(0., dtype=self._dtype), tf.where(self._accrual_start_dates < valuation_date, libor_rate, forward_rates)) return forward_rates
Example #4
Source File: extensions_test.py From trax with Apache License 2.0 | 6 votes |
def testEvalOnShapesNoUnnecessaryTracing(self): def num_traces(f): return len( f._tf_function._list_all_concrete_functions_for_serialization()) def check_trace_only_once(arg1, arg2): @extensions.eval_on_shapes def f(a): return a + 1 self.assertAllEqual(0, num_traces(f)) f(arg1) self.assertAllEqual(1, num_traces(f)) f(arg2) self.assertAllEqual(1, num_traces(f)) check_trace_only_once(1, 2) check_trace_only_once(1.1, 2.1) check_trace_only_once(tf_np.asarray(1), tf_np.asarray(2)) check_trace_only_once( tf.convert_to_tensor(value=1), tf.convert_to_tensor(value=2))
Example #5
Source File: extensions_test.py From trax with Apache License 2.0 | 6 votes |
def testJitNoUnnecessaryTracing(self): def num_traces(f): return len(f.tf_function._list_all_concrete_functions_for_serialization()) def check_trace_only_once(arg1, arg2): @extensions.jit def f(a): return a + 1 self.assertAllEqual(0, num_traces(f)) f(arg1) self.assertAllEqual(1, num_traces(f)) f(arg2) self.assertAllEqual(1, num_traces(f)) check_trace_only_once(1, 2) check_trace_only_once(1.1, 2.1) check_trace_only_once(tf_np.asarray(1), tf_np.asarray(2)) check_trace_only_once( tf.convert_to_tensor(value=1), tf.convert_to_tensor(value=2))
Example #6
Source File: swaption.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def _price_lognormal_rate(self, market, pricing_context, forward_swap_rate, strike, expiry_time): """Price the swaption using lognormal model for rate.""" # Ideally we would like the model to tell what piece of market data is # needed. For example, a Black lognormal model will tell us to pick # lognormal vols and Black normal model should tell us to pick normal # vols. if pricing_context is None: swaption_vol_cube = rc.get_implied_volatility_data(market) term = self._swap.swap_term black_vols = swaption_vol_cube.interpolate(self._expiry_date, strike, term) else: black_vols = tf.convert_to_tensor(pricing_context, dtype=self._dtype) return black_scholes.option_price(volatilities=black_vols, strikes=strike, expiries=expiry_time, forwards=forward_swap_rate, is_call_options=self._swap.is_payer, dtype=self._dtype )
Example #7
Source File: test_helpers.py From graphics with Apache License 2.0 | 6 votes |
def generate_random_test_dual_quaternions(): """Generates random test dual quaternions.""" angles = generate_random_test_euler_angles() random_quaternion_real = quaternion.from_euler(angles) min_translation = -3.0 max_translation = 3.0 translations = np.random.uniform(min_translation, max_translation, angles.shape) translations_quaternion_shape = np.asarray(translations.shape) translations_quaternion_shape[-1] = 1 translations = np.concatenate( (translations / 2.0, np.zeros(translations_quaternion_shape)), axis=-1) random_quaternion_translation = tf.convert_to_tensor(value=translations) random_quaternion_dual = quaternion.multiply(random_quaternion_translation, random_quaternion_real) random_dual_quaternion = tf.concat( (random_quaternion_real, random_quaternion_dual), axis=-1) return random_dual_quaternion
Example #8
Source File: dual_quaternion_test.py From graphics with Apache License 2.0 | 6 votes |
def test_conjugate_preset(self): """Tests if the conjugate function is providing correct results.""" x_init = test_helpers.generate_preset_test_dual_quaternions() x = tf.convert_to_tensor(value=x_init) y = tf.convert_to_tensor(value=x_init) x = dual_quaternion.conjugate(x) x_real, x_dual = tf.split(x, (4, 4), axis=-1) y_real, y_dual = tf.split(y, (4, 4), axis=-1) xyz_y_real, w_y_real = tf.split(y_real, (3, 1), axis=-1) xyz_y_dual, w_y_dual = tf.split(y_dual, (3, 1), axis=-1) y_real = tf.concat((-xyz_y_real, w_y_real), axis=-1) y_dual = tf.concat((-xyz_y_dual, w_y_dual), axis=-1) self.assertAllEqual(x_real, y_real) self.assertAllEqual(x_dual, y_dual)
Example #9
Source File: forward_rate_agreement_test.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def test_fra_many(self): dtype = np.float64 notional = 1. settlement_date = dates.convert_to_date_tensor( [(2021, 2, 8), (2021, 5, 8), (2021, 8, 8)]) fixing_date = dates.convert_to_date_tensor( [(2021, 2, 8), (2021, 5, 8), (2021, 8, 8)]) valuation_date = dates.convert_to_date_tensor([(2020, 2, 8)]) fixed_rate = tf.convert_to_tensor([0.02, 0.021, 0.022], dtype=dtype) rate_term = dates.months([3, 3, 3]) fra = tff.experimental.instruments.ForwardRateAgreement( settlement_date, fixing_date, fixed_rate, notional=notional, rate_term=rate_term, dtype=dtype) curve_dates = valuation_date + dates.months([1, 2, 3, 12, 24, 60]) reference_curve = tff.experimental.instruments.RateCurve( curve_dates, np.array([0.02, 0.025, 0.0275, 0.03, 0.035, 0.0325], dtype=dtype), valuation_date=valuation_date, dtype=dtype) market = tff.experimental.instruments.InterestRateMarket( reference_curve=reference_curve, discount_curve=reference_curve) price = self.evaluate(fra.price(valuation_date, market)) np.testing.assert_allclose(price, [0.00377957, 0.0042278427, 0.004548173], atol=1e-6)
Example #10
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
def zeros_like(a, dtype=None): """Returns an array of zeros with the shape and type of the input 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`. dtype: Optional, defaults to dtype of the input array. The type of the resulting ndarray. Could be a python type, a NumPy type or a TensorFlow `DType`. Returns: An ndarray. """ if isinstance(a, arrays_lib.ndarray): a = a.data if dtype is None: # We need to let utils.result_type decide the dtype, not tf.zeros_like dtype = utils.result_type(a) else: # TF and numpy has different interpretations of Python types such as # `float`, so we let `utils.result_type` decide. dtype = utils.result_type(dtype) dtype = tf.as_dtype(dtype) # Work around b/149877262 return arrays_lib.tensor_to_ndarray(tf.zeros_like(a, dtype))
Example #11
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
def ones_like(a, dtype=None): """Returns an array of ones with the shape and type of the input 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`. dtype: Optional, defaults to dtype of the input array. The type of the resulting ndarray. Could be a python type, a NumPy type or a TensorFlow `DType`. Returns: An ndarray. """ if isinstance(a, arrays_lib.ndarray): a = a.data if dtype is None: dtype = utils.result_type(a) else: dtype = utils.result_type(dtype) return arrays_lib.tensor_to_ndarray(tf.ones_like(a, dtype))
Example #12
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
def any(a, axis=None, keepdims=None): # pylint: disable=redefined-builtin """Whether any element in the entire array or in an axis evaluates to true. Casts the array to bool type if it is not already and uses `tf.reduce_any` to compute the result. 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: Optional. Could be an int or a tuple of integers. If not specified, the reduction is performed over all array indices. keepdims: If true, retains reduced dimensions with length 1. Returns: An ndarray. Note that unlike NumPy this does not return a scalar bool if `axis` is None. """ a = asarray(a, dtype=bool) return utils.tensor_to_ndarray( tf.reduce_any(input_tensor=a.data, axis=axis, keepdims=keepdims))
Example #13
Source File: test_helpers.py From graphics with Apache License 2.0 | 6 votes |
def generate_preset_test_dual_quaternions(): """Generates pre-set test quaternions.""" angles = generate_preset_test_euler_angles() preset_quaternion_real = quaternion.from_euler(angles) translations = generate_preset_test_translations() translations = np.concatenate( (translations / 2.0, np.zeros((np.ma.size(translations, 0), 1))), axis=1) preset_quaternion_translation = tf.convert_to_tensor(value=translations) preset_quaternion_dual = quaternion.multiply(preset_quaternion_translation, preset_quaternion_real) preset_dual_quaternion = tf.concat( (preset_quaternion_real, preset_quaternion_dual), axis=-1) return preset_dual_quaternion
Example #14
Source File: arrays_test.py From trax with Apache License 2.0 | 6 votes |
def _testBinOp(self, a, b, out, f, types=None): a = t2a(tf.convert_to_tensor(value=a, dtype=np.int32)) b = t2a(tf.convert_to_tensor(value=b, dtype=np.int32)) if not isinstance(out, arrays.ndarray): out = t2a(tf.convert_to_tensor(value=out, dtype=np.int32)) if types is None: types = [[np.int32, np.int32, np.int32], [np.int64, np.int32, np.int64], [np.int32, np.int64, np.int64], [np.float32, np.int32, np.float64], [np.int32, np.float32, np.float64], [np.float32, np.float32, np.float32], [np.float64, np.float32, np.float64], [np.float32, np.float64, np.float64]] for a_type, b_type, out_type in types: o = f(a.astype(a_type), b.astype(b_type)) self.assertIs(o.dtype.type, out_type) self.assertAllEqual(out.astype(out_type), o)
Example #15
Source File: multivariate_normal.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def _process_mean_scale(mean, scale_matrix, covariance_matrix, dtype): """Extracts correct mean, scale, batch_shape, dimension, and dtype.""" if scale_matrix is not None: scale_matrix = tf.convert_to_tensor(scale_matrix, dtype=dtype, name='scale_matrix') else: if covariance_matrix is not None: covariance_matrix = tf.convert_to_tensor(covariance_matrix, dtype=dtype, name='covariance_matrix') scale_matrix = tf.linalg.cholesky(covariance_matrix) if mean is None: mean = 0.0 # batch_shape includes the dimension of the samples batch_shape = scale_matrix.shape.as_list()[:-1] dim = scale_matrix.shape.as_list()[-1] dtype = scale_matrix.dtype else: batch_shape = mean.shape.as_list() dim = mean.shape.as_list()[-1] dtype = mean.dtype return mean, scale_matrix, batch_shape, dim, dtype
Example #16
Source File: math_ops.py From trax with Apache License 2.0 | 6 votes |
def _scalar(tf_fn, x, promote_to_float=False): """Computes the tf_fn(x) for each element in `x`. Args: tf_fn: function that takes a single Tensor argument. x: array_like. Could be an ndarray, a Tensor or any object that can be converted to a Tensor using `tf.convert_to_tensor`. promote_to_float: whether to cast the argument to a float dtype (`dtypes.default_float_type`) if it is not already. Returns: An ndarray with the same shape as `x`. The default output dtype is determined by `dtypes.default_float_type`, unless x is an ndarray with a floating point type, in which case the output type is same as x.dtype. """ x = array_ops.asarray(x) if promote_to_float and not np.issubdtype(x.dtype, np.inexact): x = x.astype(dtypes.default_float_type()) return utils.tensor_to_ndarray(tf_fn(x.data))
Example #17
Source File: root_search.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def _should_stop(state, stopping_policy_fn): """Indicates whether the overall Brent search should continue. Args: state: A Python `_BrentSearchState` namedtuple. stopping_policy_fn: Python `callable` controlling the algorithm termination. Returns: A boolean value indicating whether the overall search should continue. """ return tf.convert_to_tensor( stopping_policy_fn(state.finished), name="should_stop", dtype=tf.bool) # This is a direct translation of the Brent root-finding method. # Each operation is guarded by a call to `tf.where` to avoid performing # unnecessary calculations.
Example #18
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
def transpose(a, axes=None): """Permutes dimensions of 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`. axes: array_like. A list of ints with length rank(a) or None specifying the order of permutation. The i'th dimension of the output array corresponds to axes[i]'th dimension of the `a`. If None, the axes are reversed. Returns: An ndarray. """ a = asarray(a) if axes is not None: axes = asarray(axes) return utils.tensor_to_ndarray(tf.transpose(a=a.data, perm=axes))
Example #19
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
def real(val): """Returns real parts of all elements in `a`. Uses `tf.real`. Args: val: array_like. Could be an ndarray, a Tensor or any object that can be converted to a Tensor using `tf.convert_to_tensor`. Returns: An ndarray with the same shape as `a`. """ val = asarray(val) # TODO(srbs): np.real returns a scalar if val is a scalar, whereas we always # return an ndarray. return utils.tensor_to_ndarray(tf.math.real(val.data))
Example #20
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
def imag(a): """Returns imaginary parts of all elements in `a`. Uses `tf.imag`. 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`. Returns: An ndarray with the same shape as `a`. """ a = asarray(a) # TODO(srbs): np.imag returns a scalar if a is a scalar, whereas we always # return an ndarray. return utils.tensor_to_ndarray(tf.math.imag(a.data))
Example #21
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
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)
Example #22
Source File: array_ops_test.py From trax with Apache License 2.0 | 5 votes |
def setUp(self): super(ArrayManipulationTest, self).setUp() self.array_transforms = [ lambda x: x, tf.convert_to_tensor, np.array, array_ops.array, ]
Example #23
Source File: implied_vol_approximation.py From tf-quant-finance with Apache License 2.0 | 5 votes |
def _validate_args_control_deps(prices, forwards, strikes, expiries, discount_factors, is_call_options): """Returns assertions for no-arbitrage conditions on the prices.""" epsilon = tf.convert_to_tensor(1e-8, dtype=prices.dtype) forwards_positive = tf.compat.v1.debugging.assert_positive(forwards) strikes_positive = tf.compat.v1.debugging.assert_positive(strikes) expiries_positive = tf.compat.v1.debugging.assert_non_negative(expiries) put_lower_bounds = tf.nn.relu(strikes - forwards) call_lower_bounds = tf.nn.relu(forwards - strikes) if is_call_options is not None: is_call_options = tf.convert_to_tensor(is_call_options, dtype=tf.bool, name='is_call_options') lower_bounds = tf.where( is_call_options, x=call_lower_bounds, y=put_lower_bounds) upper_bounds = tf.where(is_call_options, x=forwards, y=strikes) else: lower_bounds = call_lower_bounds upper_bounds = forwards undiscounted_prices = prices / discount_factors bounds_satisfied = [ tf.compat.v1.debugging.assert_less_equal(lower_bounds, undiscounted_prices), tf.compat.v1.debugging.assert_greater_equal(upper_bounds, undiscounted_prices) ] not_too_close_to_bounds = [ tf.compat.v1.debugging.assert_greater( tf.math.abs(undiscounted_prices - lower_bounds), epsilon), tf.compat.v1.debugging.assert_greater( tf.math.abs(undiscounted_prices - upper_bounds), epsilon) ] return [expiries_positive, forwards_positive, strikes_positive ] + bounds_satisfied + not_too_close_to_bounds
Example #24
Source File: lsm_test.py From tf-quant-finance with Apache License 2.0 | 5 votes |
def test_american_basket_option_put(self): """Tests the LSM price of American Basket put option.""" # This is the same example as in Section 1 of # Longstaff, F.A. and Schwartz, E.S., 2001. Valuing American options by # simulation: a simple least-squares approach. The review of financial # studies, 14(1), pp.113-147. # This is the minimum number of basis functions for the tests to pass. basis_fn = lsm.make_polynomial_basis(10) exercise_times = [1, 2, 3] dtype = np.float64 payoff_fn = payoff.make_basket_put_payoff([1.1, 1.2, 1.3], dtype=dtype) # Create a 2-d process which is simply follows the `samples` paths: samples = tf.convert_to_tensor(self.samples, dtype=dtype) samples_2d = tf.concat([samples, samples], -1) # Price American basket option american_basket_put_price = lsm.least_square_mc( samples_2d, exercise_times, payoff_fn, basis_fn, discount_factors=self.discount_factors, dtype=dtype) # Since the marginal processes of `samples_2d` are 100% correlated, the # price should be the same as of the American option computed for # `samples` american_put_price = lsm.least_square_mc( self.samples, exercise_times, payoff_fn, basis_fn, discount_factors=self.discount_factors, dtype=dtype) self.assertAllClose(american_basket_put_price, american_put_price, rtol=1e-4, atol=1e-4) self.assertAllEqual(american_basket_put_price.shape, [3])
Example #25
Source File: trax2keras.py From trax with Apache License 2.0 | 5 votes |
def to_tensors(args): return math_lib.nested_map(tf.convert_to_tensor, args)
Example #26
Source File: feature_test.py From ranking with Apache License 2.0 | 5 votes |
def _features(): return { 'query_length': tf.convert_to_tensor(value=[[1], [2]]), 'utility': tf.convert_to_tensor(value=[[[1.0], [0.0]], [[0.0], [1.0]]]), 'unigrams': tf.SparseTensor( indices=[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0]], values=['ranking', 'regression', 'classification', 'ordinal'], dense_shape=[2, 2, 1]), 'example_feature_size': tf.convert_to_tensor(value=[1, 2]) }
Example #27
Source File: parabolic_equation_stepper.py From tf-quant-finance with Apache License 2.0 | 5 votes |
def _prepare_boundary_conditions(boundary_tensor, value_grid): """Prepares values received from boundary_condition callables.""" if boundary_tensor is None: return None boundary_tensor = tf.convert_to_tensor(boundary_tensor, value_grid.dtype) # Broadcast to batch dimensions. broadcast_shape = tf.shape(value_grid)[:-1] return tf.broadcast_to(boundary_tensor, broadcast_shape)
Example #28
Source File: dnn_test.py From ranking with Apache License 2.0 | 5 votes |
def _features(): return { "query_length": tf.convert_to_tensor(value=[[1], [2]]), "utility": tf.convert_to_tensor(value=[[[1.0], [0.0]], [[0.0], [1.0]]]), "unigrams": tf.SparseTensor( indices=[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0]], values=["ranking", "regression", "classification", "ordinal"], dense_shape=[2, 2, 1]) }
Example #29
Source File: gam_test.py From ranking with Apache License 2.0 | 5 votes |
def _features(): return { "query_length": tf.convert_to_tensor(value=[[1], [2]]), "utility": tf.convert_to_tensor(value=[[[1.0], [0.0]], [[0.0], [1.0]]]), "unigrams": tf.SparseTensor( indices=[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0]], values=["ranking", "regression", "classification", "ordinal"], dense_shape=[2, 2, 1]) }
Example #30
Source File: resnet50_tf2.py From tpu_models with Apache License 2.0 | 5 votes |
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)