ValueError:检查目标时出错:预期density_3具有形状(1,),但数组形状为(2,)角

时间:2019-11-21 01:30:21

标签: python tensorflow keras keras-layer

当我尝试从pyimagesearch中学习CNN时,我发现了此错误,我试图将最后一个密点从3更改为1,但它无法解决我的问题,并且我已经将其更改为binnar_crossentroypy,但仍然无法正常工作,对不起我的代码愚蠢的问题,也许是同样的问题,但我已经做了我能做的事

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"))

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

错误可能来自此行:

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

神经网络期望数组 y 仅具有一个值。这没有任何意义,因为 y 的维度有两个值。因此,您应该尝试以下操作:

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

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