Search code examples
pythontensorflowkeraskeras-layer

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


i found this error when i try to learn CNN from pyimagesearch i have tried to change the last dense from 3 into 1 but it dont resolve my prblem and i already change it into binnar_crossentroypy but its still dont work heres my code sorry for dumb and question and maybe the same question but i already do what i can do

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

Solution

  • Add this line trainY = to_categorical(trainY, 2) after this line testY = to_categorical(testY, 2). And change your last layer to model.add(Dense(2, activation="softmax")), because it's supposed to match a 2D matrix like your target. Also, make sure your loss function is categorical_crossentropy, if it isn't already.