【问题标题】:Keras multi label image classification. Do I pass my data correctly? Did I preprocess correctly?Keras 多标签图像分类。我是否正确传递了我的数据?我是否正确预处理?
【发布时间】:2020-06-03 22:40:03
【问题描述】:

我陷入了我的 keras 多标签问题。我得到了使用自定义数据生成器来创建小批量并避免内存问题的提示。

我使用带有 ID、文件名及其相应标签(总共 21 个)的 csv 文件,如下所示:

Filename  label1  label2  label3  label4  ...   ID
abc1.jpg    1       0       0       1     ...  id-1
def2.jpg    1       0       0       1     ...  id-2
ghi3.jpg    1       0       0       1     ...  id-3
...

我将 id 和标签放入字典中,输出如下:

partition: {'train': ['id-1','id-2','id-3',...], 'validation': ['id-7','id-14','id-21',...]}
labels:    {'id-0': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-1': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            'id-2': [1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
             ...}

我还有一个文件夹,每张图片都保存为一个 npy 文件,下面的自定义数据生成器将获取该文件:

import numpy as np
import keras
from keras.layers import *
from keras.models import Sequential

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, list_IDs, labels, batch_size=32, dim=(224,224), n_channels=3,
                 n_classes=21, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_IDs
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.list_IDs) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = np.load('Folder with npy files/' + ID + '.npy')

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)
import numpy as np

from keras.models import Sequential

# Parameters
params = {'dim': (224, 224),
          'batch_size': 32,
          'n_classes': 21,
          'n_channels': 3,
          'shuffle': True}

# Datasets
partition = partition
labels = labels

# Generators
training_generator = DataGenerator(partition['train'], labels, **params)
validation_generator = DataGenerator(partition['validation'], labels, **params)

# Design model
model = Sequential()

model.add(Conv2D(32, (3,3), input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

...

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(21))
model.add(Activation('softmax'))

model.summary()

到目前为止,我的笔记本没有给我任何错误,但是当我执行以下操作时:

model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

# Train model on dataset
model.fit_generator(generator=training_generator,
                    validation_data=validation_generator,
                    epochs=5,
                    use_multiprocessing=True,
                    workers=2)

我收到这样的错误消息:

线程 Thread-7 中的异常: 回溯(最近一次通话最后): _bootstrap_inner 中的文件“c:\users\sebas\appdata\local\programs\python\python36\lib\threading.py”,第 916 行 自我运行() ...

文件“c:\users\sebas\appdata\local\programs\python\python36\lib\multiprocessing\reduction.py”,第 60 行,转储中 ForkingPickler(文件,协议).dump(obj) BrokenPipeError:[Errno 32] 损坏的管道

感觉我传递或使用的数据不知何故不正确!? 如果有人有想法或提示如何以更好的方式传递数据或解决此问题,我将不胜感激。即使是不同的方法也会很棒。提前感谢您的帮助。

【问题讨论】:

    标签: machine-learning keras deep-learning image-recognition multilabel-classification


    【解决方案1】:

    use_multiprocessing=True 在 Windows (github issue) 上不受支持。删除它和workers 参数。

    【讨论】:

    • 谢谢,这至少消除了损坏的管道错误。现在我得到一个不同的错误:ValueError: setting an array element with a sequence.,我猜我传递我的数据不正确!?
    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    相关资源
    最近更新 更多