查询 Tensorflow 数据集的结构——行、列、形状

Querying the structure of a Tensorflow Dataset -- rows, columns, shape

我正在设置数据(训练、测试和验证)以加载到简单的 TensorFlow 模型 (Tensorflow v2.0)。我想浏览我正在构建的具体 TensorFlow 数据集中的行数和列数。

如果数据集设置了 _tensors 属性,我可以使用 中的技术。

但是,看起来有些数据集没有张量。例如,

a = np.array([e for e in range(10)])
df = pd.DataFrame({'a':a,'b':a,'c':a})

target = df.pop('c')

dataset = tf.data.Dataset.from_tensor_slices((df.values, target.values))

print([x.get_shape().as_list() for x in dataset._tensors])  
# Works.  Gives:
#[[10, 2], [10]]

train_dataset = dataset.shuffle(len(df)).batch(1)

print([x.get_shape().as_list() for x in train_dataset._tensors]) 
# ** Fails.  Gives:
# AttributeError: 'BatchDataset' object has no attribute '_tensors'

我看到这些是不同类型的数据集(TensorSliceDataset 与 BatchDataset):

dataset
Out[109]: <TensorSliceDataset shapes: ((2,), ()), types: (tf.int32, tf.int32)>

train_dataset
Out[110]: <BatchDataset shapes: ((None, 2), (None,)), types: (tf.int32, tf.int32)>

看起来像下面给出了张量中的行数:

print(len([e for e in dataset]))
#Gives:
#10

print(len([e for e in train_dataset]))
#Gives:
#10

以下遍历 enter code here枚举的对象:

r=0
for t in dataset:
    for e in t:
        r+=1
        tf.print('Row #{0}={1}'.format(r,e))

输出:

Row #1=[0 0]
Row #2=0
Row #3=[1 1]
Row #4=1
Row #5=[2 2]
...
Row #17=[8 8]
Row #18=8
Row #19=[9 9]
Row #20=9

有没有更好的方法?

根据 amish 的回复,我认为获取数据集“形状”的更简单方法是:

print(len(dataset), dataset)
# Gives:
# 10 <TensorSliceDataset shapes: ((2,), ()), types: (tf.int32, tf.int32)>

print(len(train_dataset), train_dataset)
# Gives 
# 10 <BatchDataset shapes: ((None, 2), (None,)), types: (tf.int32, tf.int32)>