如何更改自定义Keras数据生成器的类标签

时间:2018-12-07 14:58:58

标签: python-3.x keras conv-neural-network

我为Keras应用程序准备了一个自定义的自定义图像数据生成器。它运作良好,但类标签有问题。这是代码的相关部分:

    def _get_batches_of_transformed_samples(self, index_array):
    # create array to hold the images
    batch_x = np.zeros((4*len(index_array),) + self.target_size+(3,), dtype='float32')
    # create array to hold the labels
    batch_y = np.zeros(4*len(index_array), dtype='float32')
    target_angles = [0, 90, 180, 270]

    for i, j in enumerate(index_array):           
        is_color = int(self.color_mode == 'rgb')
        image = cv2.imread(self.filenames[j], is_color)
        if is_color:
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)                               
        for rotation_angle in target_angles:
            rotated_im = rotate(image, rotation_angle, self.target_size[:2])
            if self.preprocess_func: rotated_im = self.preprocess_func(rotated_im)                  
            batch_x[i] = rotated_im
            batch_y[i] = rotation_angle

    batch_y = to_categorical(batch_y, 271)            
    return batch_x, batch_y

如代码所示,我必须在to_categorical方法中使用271。但是我只生成4个类。因此,如何在to_categorical方法中将0、1、2、3分配给0、90、180和270,并使用4而不是271?

1 个答案:

答案 0 :(得分:1)

使用两个列表:

target_angles = [0,90,180,270]
target_cat_angles = np.array(to_categorical([0,1,2,3]))

在循环中:

for rotation_angle, cat_angle in zip(target_angles, target_cat_angles):
    ...
    batch_y[i] = cat_angle
    ...