Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

python - Expecting a Binary value but predicts a float number

I created a neural network which takes images of people as X_training values and their respective genders (binary value) as the Y_train values, where my goal is to predict the relevant gender once a user enters a image. Here is the code where i set the image and the gender values as training data:

from sklearn.model_selection import train_test_split

images_f=np.array(images)
images_f_2=images_f/255

labels_f=np.array(genders)

labels_f:

array([1, 0, 1, ..., 0, 0, 0])

I basically use convolutional layers and since im predicting a binary value(male or female, 0 or 1), i used sigmoid as my final dense layer activation method.

Here is the model code:

# Create a model and add layers
model = Sequential()

model.add(Conv2D(32, (3, 3), padding='same', input_shape=(48, 48, 3),strides=(1, 1),kernel_regularizer=l2(0.001), activation="relu"))
model.add(Conv2D(32, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), padding='same', activation="relu"))
model.add(Conv2D(64, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(128, (3, 3), padding='same', activation="relu"))
model.add(Conv2D(128, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(1, activation="sigmoid"))

model.summary()

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

This is where i fit the values code:

# Train the model
model.fit(
    X_train,
    [Y_train],
    batch_size=64,
    epochs=30,
    validation_data=(X_test, Y_test),
    shuffle=True
)

Now once i trained the model, i tried to call the model and set one of my own images and predict.

from keras.preprocessing import image

img = image.load_img("queen.jpg", target_size=(48, 48,3))

# Convert the image to a numpy array
img = image.img_to_array(img)
# Add a forth dimension to the image (since Keras expects a bunch of images, not a single image)
img/=255
img = np.expand_dims(img, axis=0)


result = model.predict(img)

And the result value i get it :

array([[0.06528784]], dtype=float32)

For each and every image i get a float value but im expecting a binary value. Why?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I tried it like this:

print((model.predict_classes(img)))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...