Python tensorflow.compat.v2.int32() Examples
The following are 30
code examples of tensorflow.compat.v2.int32().
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: imagenet2012_corrupted.py From datasets with Apache License 2.0 | 6 votes |
def _decode_and_center_crop(image_bytes): """Crops to center of image with padding then scales image size.""" shape = tf.image.extract_jpeg_shape(image_bytes) image_height = shape[0] image_width = shape[1] padded_center_crop_size = tf.cast( ((_IMAGE_SIZE / (_IMAGE_SIZE + _CROP_PADDING)) * tf.cast(tf.minimum(image_height, image_width), tf.float32)), tf.int32) offset_height = ((image_height - padded_center_crop_size) + 1) // 2 offset_width = ((image_width - padded_center_crop_size) + 1) // 2 crop_window = tf.stack([ offset_height, offset_width, padded_center_crop_size, padded_center_crop_size ]) image = tf.image.decode_and_crop_jpeg(image_bytes, crop_window, channels=3) image = tf.image.resize([image], [_IMAGE_SIZE, _IMAGE_SIZE], method=tf.image.ResizeMethod.BICUBIC)[0] image = tf.cast(image, tf.int32) return image
Example #2
Source File: extensions.py From trax with Apache License 2.0 | 6 votes |
def _key2seed(a): """Converts an RNG key to an RNG seed. Args: a: an RNG key, an ndarray of shape [] and dtype `np.int64`. Returns: an RNG seed, a tensor of shape [2] and dtype `tf.int32`. """ def int64_to_int32s(a): """Converts an int64 tensor of shape [] to an int32 tensor of shape [2].""" a = tf.cast(a, tf.uint64) fst = tf.cast(a, tf.uint32) snd = tf.cast( tf.bitwise.right_shift(a, tf.constant(32, tf.uint64)), tf.uint32) a = [fst, snd] a = tf.nest.map_structure(lambda x: tf.cast(x, tf.int32), a) a = tf.stack(a) return a return int64_to_int32s(a.data)
Example #3
Source File: extensions.py From trax with Apache License 2.0 | 6 votes |
def _seed2key(a): """Converts an RNG seed to an RNG key. Args: a: an RNG seed, a tensor of shape [2] and dtype `tf.int32`. Returns: an RNG key, an ndarray of shape [] and dtype `np.int64`. """ def int32s_to_int64(a): """Converts an int32 tensor of shape [2] to an int64 tensor of shape [].""" a = tf.bitwise.bitwise_or( tf.cast(a[0], tf.uint64), tf.bitwise.left_shift( tf.cast(a[1], tf.uint64), tf.constant(32, tf.uint64))) a = tf.cast(a, tf.int64) return a return tf_np.asarray(int32s_to_int64(a))
Example #4
Source File: model_tf2.py From machine-learning-for-programming-samples with MIT License | 6 votes |
def compute_logits(self, token_ids: tf.Tensor, training: bool) -> tf.Tensor: """ Implements a language model, where each output is conditional on the current input and inputs processed so far. Args: token_ids: int32 tensor of shape [B, T], storing integer IDs of tokens. training: Flag indicating if we are currently training (used to toggle dropout) Returns: tf.float32 tensor of shape [B, T, V], storing the distribution over output symbols for each timestep for each batch element. """ # TODO 5# 1) Embed tokens # TODO 5# 2) Run RNN on embedded tokens # TODO 5# 3) Project RNN outputs onto the vocabulary to obtain logits. return rnn_output_logits
Example #5
Source File: squad.py From datasets with Apache License 2.0 | 6 votes |
def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ "id": tf.string, "title": tfds.features.Text(), "context": tfds.features.Text(), "question": tfds.features.Text(), "answers": tfds.features.Sequence({ "text": tfds.features.Text(), "answer_start": tf.int32, }), }), # No default supervised_keys (as we have to pass both question # and context as input). supervised_keys=None, homepage="https://rajpurkar.github.io/SQuAD-explorer/", citation=_CITATION, )
Example #6
Source File: commonvoice.py From datasets with Apache License 2.0 | 6 votes |
def _info(self): return tfds.core.DatasetInfo( description=("Mozilla Common Voice Dataset"), builder=self, features=tfds.features.FeaturesDict({ "client_id": tfds.features.Text(), "upvotes": tf.int32, "downvotes": tf.int32, "age": tfds.features.Text(), "gender": tfds.features.ClassLabel(names=_GENDER_CLASSES), "accent": tfds.features.ClassLabel(names=self.builder_config.accents), "sentence": tfds.features.Text(), "voice": tfds.features.Audio(), }), homepage="https://voice.mozilla.org/en/datasets", )
Example #7
Source File: periods.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def __init__(self, quantity, period_type): """Initializer. Args: quantity: A Tensor of type tf.int32, representing the quantities of period types (e.g. how many months). Can be both positive and negative. period_type: A PeriodType (a day, a month, etc). Currently only one PeriodType per instance of PeriodTensor is supported. Example: ```python two_weeks = PeriodTensor(2, PeriodType.WEEK) months = [3, 6, 9, 12] periods = PeriodTensor(months, PeriodType.MONTH) ``` """ self._quantity = tf.convert_to_tensor(quantity, dtype=tf.int32, name="pt_quantity") self._period_type = period_type
Example #8
Source File: math_ops.py From trax with Apache License 2.0 | 6 votes |
def true_divide(x1, x2): def _avoid_float64(x1, x2): if x1.dtype == x2.dtype and x1.dtype in (tf.int32, tf.int64): x1 = tf.cast(x1, dtype=tf.float32) x2 = tf.cast(x2, dtype=tf.float32) return x1, x2 def f(x1, x2): if x1.dtype == tf.bool: assert x2.dtype == tf.bool float_ = dtypes.default_float_type() x1 = tf.cast(x1, float_) x2 = tf.cast(x2, float_) if not dtypes.is_allow_float64(): # tf.math.truediv in Python3 produces float64 when both inputs are int32 # or int64. We want to avoid that when is_allow_float64() is False. x1, x2 = _avoid_float64(x1, x2) return tf.math.truediv(x1, x2) return _bin_op(f, x1, x2)
Example #9
Source File: groove.py From datasets with Apache License 2.0 | 6 votes |
def _info(self): features_dict = { "id": tf.string, "drummer": tfds.features.ClassLabel( names=["drummer%d" % i for i in range(1, 11)]), "type": tfds.features.ClassLabel(names=["beat", "fill"]), "bpm": tf.int32, "time_signature": tfds.features.ClassLabel(names=_TIME_SIGNATURES), "style": { "primary": tfds.features.ClassLabel(names=_PRIMARY_STYLES), "secondary": tf.string, }, "midi": tf.string } if self.builder_config.include_audio: features_dict["audio"] = tfds.features.Audio( dtype=tf.float32, sample_rate=self.builder_config.audio_rate) return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict(features_dict), homepage="https://g.co/magenta/groove-dataset", citation=_CITATION, )
Example #10
Source File: date_tensor.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def days_until(self, target_date_tensor): """Computes the number of days until the target dates. Args: target_date_tensor: A DateTensor object broadcastable to the shape of "self". Returns: An int32 tensor with numbers of days until the target dates. #### Example ```python dates = tff.datetime.dates_from_tuples([(2020, 1, 25), (2020, 3, 2)]) target = tff.datetime.dates_from_tuples([(2020, 3, 5)]) dates.days_until(target) # [40, 3] targets = tff.datetime.dates_from_tuples([(2020, 2, 5), (2020, 3, 5)]) dates.days_until(targets) # [11, 3] ``` """ return target_date_tensor.ordinal() - self._ordinals
Example #11
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 #12
Source File: bounded_holiday_calendar.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def business_days_in_period(self, date_tensor, period_tensor): """Calculates number of business days in a period. Includes the dates in `date_tensor`, but excludes final dates resulting from addition of `period_tensor`. Args: date_tensor: DateTensor of starting dates. period_tensor: PeriodTensor, should be broadcastable to `date_tensor`. Returns: An int32 Tensor with the number of business days in given periods that start at given dates. """ return self.business_days_between(date_tensor, date_tensor + period_tensor)
Example #13
Source File: feature.py From ranking with Apache License 2.0 | 6 votes |
def __init__(self, example_feature_columns, size_feature_name, name='generate_mask_layer', **kwargs): """Constructs a mask generator layer. Args: example_feature_columns: (dict) example feature names to columns. size_feature_name: (str) Name of feature for example list sizes. If not None, this feature name corresponds to a `tf.int32` Tensor of size [batch_size] corresponding to sizes of example lists. If `None`, all examples are treated as valid. name: (str) name of the layer. **kwargs: keyword arguments. """ super(GenerateMask, self).__init__(name=name, **kwargs) self._example_feature_columns = example_feature_columns self._size_feature_name = size_feature_name
Example #14
Source File: euler_sampling.py From tf-quant-finance with Apache License 2.0 | 6 votes |
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
Example #15
Source File: gap.py From datasets with Apache License 2.0 | 6 votes |
def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ 'ID': tfds.features.Text(), 'Text': tfds.features.Text(), 'Pronoun': tfds.features.Text(), 'Pronoun-offset': tf.int32, 'A': tfds.features.Text(), 'A-offset': tf.int32, 'A-coref': tf.bool, 'B': tfds.features.Text(), 'B-offset': tf.int32, 'B-coref': tf.bool, 'URL': tfds.features.Text() }), supervised_keys=None, homepage='https://github.com/google-research-datasets/gap-coreference', citation=_CITATION, )
Example #16
Source File: utils_test.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def test_sobol_numbers_generation(self, dtype): """Sobol random dtype results in the correct draws.""" num_draws = tf.constant(2, dtype=tf.int32) steps_num = tf.constant(3, dtype=tf.int32) num_samples = tf.constant(4, dtype=tf.int32) random_type = tff.math.random.RandomType.SOBOL skip = 10 samples = utils.generate_mc_normal_draws( num_normal_draws=num_draws, num_time_steps=steps_num, num_sample_paths=num_samples, random_type=random_type, dtype=dtype, skip=skip) expected_samples = [[[0.8871465, 0.48877636], [-0.8871465, -0.48877636], [0.48877636, 0.8871465], [-0.15731068, 0.15731068]], [[0.8871465, -1.5341204], [1.5341204, -0.15731068], [-0.15731068, 1.5341204], [-0.8871465, 0.48877636]], [[-0.15731068, 1.5341204], [0.15731068, -0.48877636], [-1.5341204, 0.8871465], [0.8871465, -1.5341204]]] self.assertAllClose(samples, expected_samples, rtol=1e-5, atol=1e-5)
Example #17
Source File: glue.py From datasets with Apache License 2.0 | 6 votes |
def _info(self): features = { text_feature: tfds.features.Text() for text_feature in six.iterkeys(self.builder_config.text_features) } if self.builder_config.label_classes: features["label"] = tfds.features.ClassLabel( names=self.builder_config.label_classes) else: features["label"] = tf.float32 features["idx"] = tf.int32 return tfds.core.DatasetInfo( builder=self, description=_GLUE_DESCRIPTION, features=tfds.features.FeaturesDict(features), homepage=self.builder_config.url, citation=self.builder_config.citation + "\n" + _GLUE_CITATION, )
Example #18
Source File: stateless_test.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def testOutputIsPermutation(self): """Checks that stateless_random_shuffle outputs a permutation.""" for dtype in (tf.int32, tf.int64, tf.float32, tf.float64): identity_permutation = tf.range(10, dtype=dtype) random_shuffle_seed_1 = tff_rnd.stateless_random_shuffle( identity_permutation, seed=tf.constant((1, 42), tf.int64)) random_shuffle_seed_2 = tff_rnd.stateless_random_shuffle( identity_permutation, seed=tf.constant((2, 42), tf.int64)) # Check that the shuffles are of the correct dtype for shuffle in (random_shuffle_seed_1, random_shuffle_seed_2): np.testing.assert_equal(shuffle.dtype, dtype.as_numpy_dtype) random_shuffle_seed_1 = self.evaluate(random_shuffle_seed_1) random_shuffle_seed_2 = self.evaluate(random_shuffle_seed_2) identity_permutation = self.evaluate(identity_permutation) # Check that the shuffles are different self.assertTrue( np.abs(random_shuffle_seed_1 - random_shuffle_seed_2).max()) # Check that the shuffles are indeed permutations for shuffle in (random_shuffle_seed_1, random_shuffle_seed_2): self.assertAllEqual(set(shuffle), set(identity_permutation))
Example #19
Source File: stateless_test.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def testOutputIsIndependentOfInputValues(self): """stateless_random_shuffle output is independent of input_tensor values.""" # Generate sorted array of random numbers to control that the result # is independent of `input_tesnor` values np.random.seed(25) random_input = np.random.normal(size=[10]) random_input.sort() for dtype in (tf.int32, tf.int64, tf.float32, tf.float64): # Permutation of a sequence [0, 1, .., 9] random_permutation = tff_rnd.stateless_random_shuffle( tf.range(10, dtype=dtype), seed=(100, 42)) random_permutation = self.evaluate(random_permutation) # Shuffle `random_input` with the same seed random_shuffle_control = tff_rnd.stateless_random_shuffle( random_input, seed=(100, 42)) random_shuffle_control = self.evaluate(random_shuffle_control) # Checks that the generated permutation does not depend on the underlying # values np.testing.assert_array_equal( np.argsort(random_permutation), np.argsort(random_shuffle_control))
Example #20
Source File: stateless_test.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def testOutputIsStatelessSession(self): """Checks that stateless_random_shuffle is stateless across Sessions.""" random_permutation_next_call = None for dtype in (tf.int32, tf.int64, tf.float32, tf.float64): random_permutation = tff_rnd.stateless_random_shuffle( tf.range(10, dtype=dtype), seed=tf.constant((100, 42), tf.int64)) with tf.compat.v1.Session() as sess: random_permutation_first_call = sess.run(random_permutation) if random_permutation_next_call is not None: # Checks that the values are the same across different dtypes np.testing.assert_array_equal(random_permutation_first_call, random_permutation_next_call) with tf.compat.v1.Session() as sess: random_permutation_next_call = sess.run(random_permutation) np.testing.assert_array_equal(random_permutation_first_call, random_permutation_next_call)
Example #21
Source File: stateless_test.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def testMultiDimensionalShape(self): """Check that stateless_random_shuffle works with multi-dim shapes.""" for dtype in (tf.int32, tf.int64, tf.float32, tf.float64): input_permutation = tf.constant([[[1], [2], [3]], [[4], [5], [6]]], dtype=dtype) random_shuffle = tff_rnd.stateless_random_shuffle( input_permutation, seed=(1, 42)) random_permutation_first_call = self.evaluate(random_shuffle) random_permutation_next_call = self.evaluate(random_shuffle) input_permutation = self.evaluate(input_permutation) # Check that the dtype is correct np.testing.assert_equal(random_permutation_first_call.dtype, dtype.as_numpy_dtype) # Check that the shuffles are the same np.testing.assert_array_equal(random_permutation_first_call, random_permutation_next_call) # Check that the output shape is correct np.testing.assert_equal(random_permutation_first_call.shape, input_permutation.shape)
Example #22
Source File: amazon_us_reviews.py From datasets with Apache License 2.0 | 6 votes |
def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ "data": collections.OrderedDict([ ("marketplace", tf.string), ("customer_id", tf.string), ("review_id", tf.string), ("product_id", tf.string), ("product_parent", tf.string), ("product_title", tf.string), ("product_category", tf.string), ("star_rating", tf.int32), ("helpful_votes", tf.int32), ("total_votes", tf.int32), ("vine", tfds.features.ClassLabel(names=["Y", "N"])), ("verified_purchase", tfds.features.ClassLabel(names=["Y", "N"])), ("review_headline", tf.string), ("review_body", tf.string), ("review_date", tf.string) ]) }), supervised_keys=None, homepage="https://s3.amazonaws.com/amazon-reviews-pds/readme.html", citation=_CITATION, )
Example #23
Source File: blimp.py From datasets with Apache License 2.0 | 6 votes |
def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ 'sentence_good': tfds.features.Text(), 'sentence_bad': tfds.features.Text(), 'field': tfds.features.Text(), 'linguistics_term': tfds.features.Text(), 'UID': tfds.features.Text(), 'simple_LM_method': tf.bool, 'one_prefix_method': tf.bool, 'two_prefix_method': tf.bool, 'lexically_identical': tf.bool, 'pair_id': tf.int32, }), supervised_keys=None, # Homepage of the dataset for documentation homepage=_PROJECT_URL, citation=_CITATION, )
Example #24
Source File: root_search_test.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def testFindsAllRootsUsingFloat16(self): left_bracket = [-2, 1] right_bracket = [2, -1] expected_num_iterations = [9, 4] expected_num_iterations, result = self.evaluate([ tf.constant(expected_num_iterations, dtype=tf.int32), root_search.brentq(polynomial5, tf.constant(left_bracket, dtype=tf.float16), tf.constant(right_bracket, dtype=tf.float16)) ]) _, value_at_roots, num_iterations, _ = result # Simply check that the objective function is close to the root for the # returned estimates. Do not check the estimates themselves. # Using float16 may yield root estimates which differ from those returned # by the SciPy implementation. self.assertAllClose(value_at_roots, [0., 0.], atol=1e-3) self.assertAllEqual(num_iterations, expected_num_iterations)
Example #25
Source File: date_utils.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def days_in_leap_and_nonleap_years_between(start_date, end_date): """Calculates number of days that fall on leap and non-leap years. Calculates a tuple '(days_in_leap_years, days_in_nonleap_years)'. 'start_date' is included and 'end_date' is excluded from the period. For example, for dates `2019-12-24` and `2024-2-10` the result is (406, 1103): 406 = 366 days in 2020 + 31 in Jan 2024 + 9 in Feb 2024, 1103 = 8 in 2019 + 365 in 2021 + 365 in 2022 + 365 in 2023. If `end_date` is earlier than `start_date`, the result will be negative or zero. Args: start_date: DateTensor. end_date: DateTensor compatible with `start_date`. Returns: Tuple of two Tensors of type 'int32'. """ days_between = end_date.ordinal() - start_date.ordinal() days_in_leap_years = days_in_leap_years_between(start_date, end_date) return days_in_leap_years, days_between - days_in_leap_years
Example #26
Source File: root_search_test.py From tf-quant-finance with Apache License 2.0 | 6 votes |
def testFindsRootForFlatFunction(self): # Flat in the [-0.5, 0.5] range. objective_fn = lambda x: 0 if x == 0 else x * exp(-1 / x**2) left_bracket = [-10] right_bracket = [1] expected_num_iterations = [13] expected_num_iterations, result = self.evaluate([ tf.constant(expected_num_iterations, dtype=tf.int32), root_search.brentq(objective_fn, tf.constant(left_bracket, dtype=tf.float64), tf.constant(right_bracket, dtype=tf.float64)) ]) _, value_at_roots, num_iterations, _ = result # Simply check that the objective function is close to the root for the # returned estimate. Do not check the estimate itself. # Unlike Brent's original algorithm (and the SciPy implementation), this # implementation stops the search as soon as a good enough root estimate is # found. As a result, the estimate may significantly differ from the one # returned by SciPy for functions which are extremely flat around the root. self.assertAllClose(value_at_roots, [0.]) self.assertAllEqual(num_iterations, expected_num_iterations)
Example #27
Source File: date_tensor.py From tf-quant-finance with Apache License 2.0 | 5 votes |
def day(self): """Returns an int32 tensor of days since the beginning the month. The result is one-based, i.e. yields 1 for first day of the month. #### Example ```python dates = tff.datetime.dates_from_tuples([(2019, 1, 25), (2020, 3, 2)]) dates.day() # [25, 2] ``` """ return self._days
Example #28
Source File: date_utils.py From tf-quant-finance with Apache License 2.0 | 5 votes |
def days_in_leap_years_between(start_date, end_date): """Calculates number of days between two dates that fall on leap years. 'start_date' is included and 'end_date' is excluded from the period. For example, for dates `2019-12-24` and `2024-2-10` the result is 406: 366 days in 2020, 31 in Jan 2024 and 9 in Feb 2024. If `end_date` is earlier than `start_date`, the result will be negative or zero. Args: start_date: DateTensor. end_date: DateTensor compatible with `start_date`. Returns: Tensor of type 'int32'. """ def days_in_leap_years_since_1jan0001(date): prev_year = date.year() - 1 leap_years_before = prev_year // 4 - prev_year // 100 + prev_year // 400 n_leap_days = leap_years_before * 366 days_in_cur_year = date.day_of_year() - 1 # exclude current day. n_leap_days += tf.where(is_leap_year(date.year()), days_in_cur_year, 0) return n_leap_days return (days_in_leap_years_since_1jan0001(end_date) - days_in_leap_years_since_1jan0001(start_date))
Example #29
Source File: bounded_holiday_calendar.py From tf-quant-finance with Apache License 2.0 | 5 votes |
def _compute_bus_day_ordinals_table(self): """Computes and caches rolled business day ordinals table.""" if self._table_cache.bus_day_ordinals is not None: return self._table_cache.bus_day_ordinals is_bus_day_table = self._compute_is_bus_day_table() with tf.init_scope(): bus_day_ordinals_table = ( tf.cast(tf.where(is_bus_day_table)[:, 0], tf.int32) + self._ordinal_offset - 1) self._table_cache.bus_day_ordinals = bus_day_ordinals_table return bus_day_ordinals_table
Example #30
Source File: date_utils.py From tf-quant-finance with Apache License 2.0 | 5 votes |
def ordinal_to_year_month_day(ordinals): """Calculates years, months and dates Tensor given ordinals Tensor. Args: ordinals: Tensor of int32 type. Each element is number of days since 1 Jan 0001. 1 Jan 0001 has `ordinal = 1`. Returns: Tuple (years, months, days), each element is an int32 Tensor of the same shape as `ordinals`. `months` and `days` are one-based. """ with tf.compat.v1.name_scope(None, "o2ymd", [ordinals]): ordinals = tf.convert_to_tensor(ordinals, dtype=tf.int32, name="ordinals") # The algorithm is adapted from # http://howardhinnant.github.io/date_algorithms.html # Take the fictional date of 1 March 0000 as reference and consider 1 March # as start of the year. This simplifies computations. ordinals -= _ORDINAL_OF_1_3_0000 era = ordinals // _DAYS_IN_ERA day_of_era = ordinals % _DAYS_IN_ERA year_of_era = (day_of_era - day_of_era // (_DAYS_IN_4_YEARS - 1) + day_of_era // _DAYS_IN_100_YEARS - day_of_era // (_DAYS_IN_ERA - 1)) // _DAYS_IN_YEAR year = year_of_era + era * _YEARS_IN_ERA day_of_year = day_of_era - (_DAYS_IN_YEAR * year_of_era + year_of_era // 4 - year_of_era // 100) months = _day_of_year_to_month(day_of_year) days = day_of_year - _days_in_year_before_month(months) + 1 # Go back from 1 March to 1 January as start of year. months = months + tf.compat.v2.where(months < 10, 3, -9) year += tf.compat.v2.where(months <= 2, 1, 0) return year, months, days