【问题标题】:How to get samples per class for TensorFlow Dataset如何为 TensorFlow 数据集获取每个类的样本
【发布时间】:2021-06-08 22:52:38
【问题描述】:

我正在使用来自 TensorFlow 数据集的数据集。 是否有一种简单的方法可以访问数据集中每个类的样本数量?我正在搜索 keras api,但没有找到任何可以使用的函数。

最终我想在 Y 轴上绘制一个带有样本数的条形图,在 X 轴上用 int 表示类 ID。目标是显示数据在类之间分布的均匀程度。

【问题讨论】:

    标签: tensorflow tensorflow2.0 tensorflow-datasets


    【解决方案1】:

    使用np.fromiter,您可以从可迭代对象创建一维数组。

    import tensorflow_datasets as tfds
    import numpy as np
    import seaborn as sns
    
    dataset = tfds.load('cifar10', split='train', as_supervised=True)
    
    labels, counts = np.unique(np.fromiter(dataset.map(lambda x, y: y), np.int32), 
                           return_counts=True)
    
    plt.ylabel('Counts')
    plt.xlabel('Labels')
    sns.barplot(x = labels, y = counts) 
    


    更新:您还可以计算如下标签:

    labels = []
    for x, y in dataset:
      # Not one hot encoded
      labels.append(y.numpy())
    
      # If one hot encoded, then apply argmax
      # labels.append(np.argmax(y, axis = -1))
    labels = np.concatenate(labels, axis = 0) # Assuming dataset was batched.
    

    然后您可以使用labels 数组绘制它们。

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 2022-01-18
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 2021-06-01
      • 2015-08-22
      相关资源
      最近更新 更多