【问题标题】:what is the difference between binary, sparse and categorical in class_modeclass_mode 中的二进制、稀疏和分类有什么区别
【发布时间】:2020-09-13 05:53:47
【问题描述】:

下面的代码便于理解,

#Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
    rescale = 1.0 / 255,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True
)

test_datagen = ImageDataGenerator(rescale= 1.0 / 255)

training_set = train_datagen.flow_from_directory(
    'dataset/training_set',
    target_size = (64,64),
    batch_size = 32,
    class_mode = 'binary'
)

test_set = test_datagen.flow_from_directory(
    'dataset/test_set',
    target_size = (64,64),
    batch_size = 32,
    class_mode = 'binary'
)

当我使用 sparse / categorical 时。它显示相同的输出,

在输出下方,

Found 214 images belonging to 5 classes.
Found 20 images belonging to 5 classes.

注意:此代码用于训练数据集,但不幸的是它不能训练

所以需要帮助

【问题讨论】:

    标签: python keras conv-neural-network


    【解决方案1】:

    它们与loss function相关。

    'binary' 班级模式为您提供每个班级的编号。例如,如果您的数据集有 3 个 A、B、C 类,则目标数据将为 A 类 0,B 类为 1,C 类为 2。

    categorical 为您提供 one hot encoding(1, 0, 0) 用于 A、(0, 1, 0) 用于 B 和 (0, 0, 1) 用于 C。

    你可以用这个寻找不同的。

    test_set = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size = (64,64),
        batch_size = 32,
        class_mode = 'binary'
    )
    x, y = test_set[0]
    print(y.shape)  # (32,)
    print(y)
    
    test_set = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size = (64,64),
        batch_size = 32,
        class_mode = 'categorical'
    )
    x, y = test_set[0]
    print(y.shape)  # (32, n) where n is equal to how many folder you have in 'dataset/test_set'
    print(y)
    
    

    sparse 不在flow_from_directory 中使用,通常在图像可以有多个类别时使用。例如,如果图像可以是 A 和 C,则目标将是 (1, 0, 1)

    binary 的原因实际上是这样调用的,因为在早期版本中它只给你 1 和 0。

    【讨论】:

      【解决方案2】:

      发件人:https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator “分类”、“二进制”、“稀疏”、“输入”或无之一。默认值:“分类”。确定返回的标签数组的类型:

      "categorical" will be 2D one-hot encoded labels,
      "binary" will be 1D binary labels,
      "sparse" will be 1D integer labels,
      "input" will be images identical to input images (mainly used to work with autoencoders).
      If None, no labels are returned (the generator will only yield batches of image data, which is useful to use with model.predict()). Please note that in case of class_mode None, the data still needs to reside in a subdirectory of directory for it to work correctly. 
      

      【讨论】:

        猜你喜欢
        • 2012-09-17
        • 2012-06-17
        • 2016-02-14
        • 2016-05-17
        • 1970-01-01
        • 2021-04-22
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多