ValueError:形状(无,5)和(无,1000)不兼容

2024-04-26 12:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

试图从预先训练的形式训练Resnet50模型,但一旦它达到训练它的代码,它就会抛出这个错误ValueError: Shapes (None, 5) and (None, 1000) are incompatible我不知道我在这里做错了什么

我有5个类数据集,所以我使用categorical_crossentropy作为损失

完整代码如下:

    # This is in for loop until labels.append
    #load the image, pre-process it, and store it in the data list
    image = cv2.imread(imagePath)
    image = cv2.resize(image, (224, 224))
    image = img_to_array(image)

    data.append(image)
    # extract the class label from the image path and update the
    # labels list
    label = imagePath.split(os.path.sep)[-2]
    labels.append(label)
  

  print("[INFO] ...reading the images completed", "+ Label class extracted.")

  # scale the raw pixel intensities to the range [0, 1]
  data = np.array(data, dtype="float") / 255.0
  labels = np.array(labels)
  print("[INFO] data matrix: {:.2f}MB".format(
      data.nbytes / (1024 * 1000.0)))
  # binarize the labels
  lb = LabelBinarizer()
  labels = lb.fit_transform(labels)
  # partition the data into training and testing splits using 80% of
  # the data for training and the remaining 20% for testing
  (trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.2, random_state=42)

  model = ResNet50()

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

  print("[INFO] Model compilation completed.")
  # train the network
  print("[INFO] training network...")
  H = model.fit(trainX, trainY, batch_size=BS,
                validation_data=(testX, testY),
                steps_per_epoch=len(trainX) // BS,
                epochs=EPOCHS, verbose=1)



Tags: andthe代码imageinfofordatalabels
2条回答

尝试为任务添加具有适当类别数的图层:

base = ResNet50(include_top=False, pooling='avg')

out = K.layers.Dense(5, activation='softmax')

model = K.Model(inputs=base.input, outputs=out(base.output))

您已经使用了预先训练的ResNet的完全连接层,您需要创建适合您的任务的适当分类层

from tensorflow.keras.layers import GlobalAveragePooling2D
from tensorflow.keras import Model

model = ResNet50(include_top=False)
f_flat = GlobalAveragePooling2D()(model.output)          
fc = Dense(units=2048,activation="relu")(f_flat)
logit = Dense(units=5, activation="softmax")(fc)

model = Model(model.inputs,logit)

相关问题 更多 >