votes up 2

_SLICE_TYPE_ERROR, got (!r)

Package:
Exception Class:
TypeError

Raise code

  # * any object with a dtype is supported
  # * any object with a dtype has a sizeable shape attribute.
  dtype = getattr(idx, "dtype", None)
  if (dtype is None or dtypes.as_dtype(dtype) not in _SUPPORTED_SLICE_DTYPES or
      idx.shape and len(idx.shape) == 1):
    # TODO(slebedev): IndexError seems more appropriate here, but it
    # will break `_slice_helper` contract.
    raise TypeError(_SLICE_TYPE_ERROR + ", got {!r}".format(idx))


def _is_undefined_dimension(d):
  return isinstance(d, tensor_shape.Dimension) and d.value is None


@tf_export("__operators__.getitem", v1=[])

Comment explaining raise

TODO(slebedev): IndexError seems more appropriate here, but it will break `_slice_helper` contract.

Ways to fix

votes up 0 votes down

Steps to reproduce:

Step 1: Create a test directory

$ mkdir test-tf

Step 2: Navigate to that directory

$ cd test-tf

Step 3: Run the command

$ pipenv shell

Step 4: Install the dependencies

$ pipenv install tensorflow

Step 5: Run the below code to reproduce the exception:

from tensorflow.python.ops.array_ops import _slice_helper
import tensorflow as tf

t1 = tf.constant([0, 1, 2, 3, 4, 5, 6, 7])

_slice_helper(t1, [slice(1.0, 6, 2)]) # 1.0 which is a float value is provided as begin arg of slice function which is an invalid indices value

The above code raised the exception:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-5430e7872f41> in <module>()
      4 t1 = tf.constant([0, 1, 2, 3, 4, 5, 6, 7])
      5 
----> 6 _slice_helper(t1, [slice(1.0, 6,2)])

/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/array_ops.py in _check_index(idx)
    885     # TODO(slebedev): IndexError seems more appropriate here, but it
    886     # will break `_slice_helper` contract.
--> 887     raise TypeError(_SLICE_TYPE_ERROR + ", got {!r}".format(idx))
    888 
    889 

TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got 1.0


Fixed version of code:

from tensorflow.python.ops.array_ops import _slice_helper
import tensorflow as tf

t1 = tf.constant([0, 1, 2, 3, 4, 5, 6, 7])

_slice_helper(t1, [slice(1, 6,  2)]) # changed the float value to int index to fix it

Explanation:

To reproduce the exception we provided an invalid index value 1.0 which is a floating-point value. Supported datatypes for slicing are dtypes.int32, dtypes.int32_ref, dtypes.int64, and dtypes.int64_ref. To fix it, we changed the floating value to integer i.e. 1.

Jun 19, 2021 umangtaneja98 answer
umangtaneja98 741

Add a possible fix

Please authorize to post fix