Search code examples
tensorflowkeras

How can I see the array of x, y of batch dataset?


I made a batch dataset with tensorflow with below code.

dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)

Dataset shape is below.

<_BatchDataset element_spec=(TensorSpec(shape=(20, 256, 256, 3), dtype=tf.float32, name=None), TensorSpec(shape=(20, 256, 256, 1), dtype=tf.float32, name=None))>

I wanted to print first array of x with below code but it didn't work, where x and y is input and target data.

dataset[0][0] 

Solution

  • You can use one of these ways to get the first parts of a dataset:

    x = tf.random.uniform((100,2))
    y = tf.random.uniform((100, 1))
    ds = tf.data.Dataset.from_tensor_slices((x, y))  # dataset creation
    ds = ds.batch(3, drop_remainder=True)
    
    """ THIS """
    for x,y in ds:
      print(x,y)
      break
    """ OR THIS """
    print(next(iter(ds)))
    

    I think the for-loop does more or less the second solution under the hood. It creates an iterable object with iter, and next gives the next element in the order.