如何解决ValueError:形状无,5和无,1000不兼容
尝试从预先训练的形式训练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,batch_size=BS,validation_data=(testX,testY),steps_per_epoch=len(trainX) // BS,epochs=EPOCHS,verbose=1)
解决方法
尝试为您的任务添加具有适当类别数的层:
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。