【问题标题】:ValueError: Error when checking target: expected dense_3 to have shape (1,) but got array with shape (2,) kerasValueError:检查目标时出错:预期dense_3的形状为(1,)但得到的数组形状为(2,)keras
【发布时间】:2019-11-21 01:30:21
【问题描述】:

我在尝试从 pyimagesearch 学习 CNN 时发现了这个错误愚蠢和问题,也许同样的问题,但我已经做了我能做的事

ss# grab the image paths and randomly shuffle them
imagePaths = sorted(list(paths.list_images(args["dataset"])))
random.seed(42)
random.shuffle(imagePaths)


for imagePath in imagePaths:
# load the image, resize the image to be 32x32 pixels (ignoring
# aspect ratio), flatten the image into 32x32x3=3072 pixel image
# into a list, and store the image in the data list
image = cv2.imread(imagePath)
image = cv2.resize(image, (32, 32)).flatten()
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)

# scale the raw pixel intensities to the range [0, 1]
data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)

 # partition the data into training and testing splits using 75% of
 # the data for training and the remaining 25% for testing
  (trainX, testX, trainY, testY) = train_test_split(data,
   labels, test_size=0.25, random_state=42)



 lb =  LabelEncoder()
 trainY = lb.fit_transform(trainY)
 testY = to_categorical(testY, 2)


 # define the 3072-1024-512-3 architecture using Keras
 model = Sequential()
 model.add(Dense(1024, input_shape=(3072,), activation="sigmoid"))
 model.add(Dense(512, activation="sigmoid"))
 model.add(Dense(1, activation="softmax"))

【问题讨论】:

    标签: python tensorflow keras keras-layer


    【解决方案1】:

    在此行testY = to_categorical(testY, 2) 之后添加此行trainY = to_categorical(trainY, 2)。并将您的最后一层更改为model.add(Dense(2, activation="softmax")),因为它应该与您的目标一样匹配二维矩阵。另外,确保你的损失函数是categorical_crossentropy,如果不是的话。

    【讨论】:

    • 但我有一个问题,在 pyimagesearch web 中,作者告诉读者将其更改为二元交叉熵,因为只有 2 个类,它对我的​​训练模型有影响吗?
    • 很高兴我能帮上忙。据我了解,分类交叉熵更灵活,因为它也可以处理二元类。相反,二元交叉熵仅适用于两个类别。在两个班级,他们做同样的事情。
    • 我还有更多疑问,为什么我需要使用 labelencoder 对我的 trainY 进行编码?
    【解决方案2】:

    错误可能来自这一行:

    model.add(Dense(1, activation="softmax"))
    

    神经网络期望数组 y 只有一个值。这没有任何意义,因为 y 的维度有两个值。所以,你应该试试这个:

    model.add(Dense(2, activation="softmax"))
    

    如果 2 是您正在使用的类数。

    【讨论】:

    • 我试图将其更改为 model.add(Dense(2, activation="softmax")) 但收到此错误 ValueError: Error when checks target: expected dense_3 to have shape (2,) 但是得到形状为 (1,) 的数组
    猜你喜欢
    • 2021-06-30
    • 2019-01-16
    • 2019-05-10
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 2020-05-19
    相关资源
    最近更新 更多