ValueError:检查目标时发生错误:预期category_output具有形状(2,),但数组的形状为(1,)

时间:2019-09-02 15:46:44

标签: python arrays tensorflow keras deep-learning

我制作了一个带有2个子分支的模型,一个子分支识别类别,一个子分支识别颜色。它工作得很好。 现在,我修改了代码并添加了另外2个子分支,并且出现以下错误。请注意,当我使用两个分支时,它工作正常,并且数组形状没有问题。

这是代码:

没有任何作用

# initialize the data, clothing category labels (i.e., shirts, jeans,
# dresses, etc.) along with the color labels (i.e., red, blue, etc.)
data = []
categoryLabels = []
colorLabels = []
attribute1Labels = []
attribute2Labels = []
# loop over the input images
for imagePath in imagePaths:
    try:
        # load the image, pre-process it, and store it in the data list
        image = cv2.imread(imagePath)
        image = cv2.resize(image, (IMAGE_DIMS[1], IMAGE_DIMS[0]))
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image = img_to_array(image)
        data.append(image)

        # extract the clothing color and category from the path and
        # update the respective lists
        (cat, attribute1 , attribute2 , color) = imagePath.split(os.path.sep)[-2].split("_")
        categoryLabels.append(cat)
        attribute1Labels.append(attribute1)
        attribute2Labels.append(attribute2)
        colorLabels.append(color)
    except Exception as e:
            pass
# scale the raw pixel intensities to the range [0, 1] and convert to
# a NumPy array
data = np.array(data, dtype="float") / 255.0
print("[INFO] data matrix: {} images ({:.2f}MB)".format(
    len(imagePaths), data.nbytes / (1024 * 1000.0)))

# convert the label lists to NumPy arrays prior to binarization
categoryLabels = np.array(categoryLabels)
colorLabels = np.array(colorLabels)
attribute1Labels = np.array(attribute1Labels)
attribute2Labels = np.array(attribute2Labels)

# binarize both sets of labels
print("[INFO] binarizing labels...")
categoryLB = LabelBinarizer()
colorLB = LabelBinarizer()
att1LB = LabelBinarizer()
att2LB = LabelBinarizer()
categoryLabels = categoryLB.fit_transform(categoryLabels)
colorLabels = colorLB.fit_transform(colorLabels)
attribute1Labels = att1LB.fit_transform(attribute1Labels)
attribute2Labels = att2LB.fit_transform(attribute2Labels)

# partition the data into training and testing splits using 80% of
# the data for training and the remaining 20% for testing
split = train_test_split(data, categoryLabels,attribute1Labels,attribute2Labels, colorLabels,
    test_size=0.2, random_state=42)
(trainX, testX, trainCategoryY, testCategoryY, trainAtt1, testAtt1 , trainAtt2,testAtt2,
    trainColorY, testColorY) = split

# initialize our FashionNet multi-output network
model = FashionNet.build(96, 96,
    numCategories=len(categoryLB.classes_), numAtts1 = len(att1LB.classes_) , numAtts2 = len(att2LB.classes_),
    numColors=len(colorLB.classes_),
    finalAct="softmax")

# define two dictionaries: one that specifies the loss method for
# each output of the network along with a second dictionary that
# specifies the weight per loss
losses = {
    "category_output": "categorical_crossentropy", "attribute1_output": "categorical_crossentropy","attribute2_output": "categorical_crossentropy",
    "color_output": "categorical_crossentropy",
}
lossWeights = {"category_output": 1.0, "color_output": 1.0 , "attribute1_output":1.0 , "attribute2_output":1.0}

# initialize the optimizer and compile the model
print("[INFO] compiling model...")
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model.compile(optimizer=opt, loss=losses, loss_weights=lossWeights,
    metrics=["accuracy"])
H = model.fit(trainX,
    {"category_output": trainCategoryY , "attribute1_output":trainAtt1 ,"attribute2_output":trainAtt2, "color_output": trainColorY},
    validation_data=(testX,
        {"category_output": testCategoryY, "attribute1_output":testAtt1,"attribute2_output":testAtt2, "color_output": testColorY}),
    epochs=EPOCHS,
    verbose=1)

# save the model to disk
print("[INFO] serializing network...")

这是错误:

ValueError                                Traceback (most recent call last)
<ipython-input-16-7d553dc48bc9> in <module>
      5         {"category_output": testCategoryY, "attribute1_output":testAtt1,"attribute2_output":testAtt2, "color_output": testColorY}),
      6         epochs=EPOCHS,
----> 7     verbose=1)
      8 
      9 # save the model to disk

c:\users\sokhen\appdata\local\programs\python\python37\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
    970                 val_x, val_y,
    971                 sample_weight=val_sample_weight,
--> 972                 batch_size=batch_size)
    973             if self._uses_dynamic_learning_phase():
    974                 val_ins = val_x + val_y + val_sample_weights + [0.]

c:\users\sokhen\appdata\local\programs\python\python37\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    787                 feed_output_shapes,
    788                 check_batch_axis=False,  # Don't enforce the batch size.
--> 789                 exception_prefix='target')
    790 
    791             # Generate sample-wise weight values given the `sample_weight` and

c:\users\sokhen\appdata\local\programs\python\python37\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    136                             ': expected ' + names[i] + ' to have shape ' +
    137                             str(shape) + ' but got array with shape ' +
--> 138                             str(data_shape))
    139     return data
    140 

ValueError: Error when checking target: expected category_output to have shape (2,) but got array with shape (1,)

0 个答案:

没有答案