Keras model.predict only returns one figure for binary classification taskHow to determine amount of augmented images in Keras?loss, val_loss, acc and val_acc do not update at all over epochsKeras: Why is my testing accuracy unstable?Object center detection using Convnet is always returning center of image rather than center of objectIssue: Model Classification cats and dogs (keras)About correctly using dropout in RNNs (Keras)Keras: Transfer Learning - Image scaling worsens performance of the model significantlyKeras - LSTM on embedding - dense layersEpoch's steps taking too long on GPUTuple index out of range, when visulaizing CNN filters

Why aren't nationalizations in Russia described as socialist?

Is an HNN extension of a virtually torsion-free group virtually torsion-free?

History of the kernel of a homomorphism?

Is 'contemporary' ambiguous and if so is there a better word?

Install LibreOffice-Writer Only not LibreOffice whole package

What to use instead of cling film to wrap pastry

Should I simplify my writing in a foreign country?

Notation: What does the tilde bellow of the Expectation mean?

Hostile Divisor Numbers

Out of scope work duties and resignation

Side effects of Initiation by a Guru?

Would a small hole in a Faraday cage drastically reduce its effectiveness at blocking interference?

Why is my arithmetic with a long long int behaving this way?

How to ask systemd to not start a system service on boot?

Would you use "llamarse" for an animal's name?

My first c++ game (snake console game)

Why is the magnitude of a photons 4 momentum vector 0 if it has momentum?

Why does sound not move through a wall?

Why would a military not separate its forces into different branches?

Latex & Markdown files

Are the Night's Watch still required?

Why wasn't the Z6 version of the Infocom Z-machine ported to the IIgs?

Start job from another SQL server instance

How to deal with employer who keeps me at work after working hours



Keras model.predict only returns one figure for binary classification task


How to determine amount of augmented images in Keras?loss, val_loss, acc and val_acc do not update at all over epochsKeras: Why is my testing accuracy unstable?Object center detection using Convnet is always returning center of image rather than center of objectIssue: Model Classification cats and dogs (keras)About correctly using dropout in RNNs (Keras)Keras: Transfer Learning - Image scaling worsens performance of the model significantlyKeras - LSTM on embedding - dense layersEpoch's steps taking too long on GPUTuple index out of range, when visulaizing CNN filters






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have trained a binary classification task with Keras according to this instruction "https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html".



However, model.predict returns only one figure such as [[0.6343]].
I think it should return two figures such as [[0.6343, 0.1245]] where each figure represents the probability of each class.



I'm using Keras of version 2.2.4 and Tensorflow of version 1.13.1.



Here is my code.



from keras.models import Sequential
from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import np_utils
from sklearn.datasets import fetch_mldata
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import tensorflowjs as tfjs


##############
# Train model
##############

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(1))
model.add(Activation('sigmoid'))

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


################################
# Read image data from directory
################################

batch_size = 16

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
fill_mode='wrap',
zoom_range=0.2,
horizontal_flip=True,
vertical_flip=True
)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1./255)

# this is a generator that will read pictures found in
# subfolers of 'data/train', and indefinitely generate
# batches of augmented image data
train_generator = train_datagen.flow_from_directory(
'dataset/train', # this is the target directory
target_size=(96, 128), # all images will be resized to 150x150
batch_size=batch_size,
class_mode='binary') # since we use binary_crossentropy loss, we need binary labels

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
'dataset/validation',
target_size=(96, 128),
batch_size=batch_size,
class_mode='binary')


##############
# Fit model
##############

model.fit_generator(
train_generator,
steps_per_epoch=2000 // batch_size,
epochs=30,
validation_data=validation_generator,
validation_steps=800 // batch_size)
model.save('model.h5') # always save your weights after training or during training
tfjs.converters.save_keras_model(model, './')


##############
# Predict class
##############

img = load_img('./dataset/validation/dog/image001.png')

if (img.size == (96, 128)):
img = img.rotate(90, expand=True)

x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
x = x / 255
x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

model.predict(x, batch_size=None, verbose=0, steps=None)


How should I fix the code to generate what I expect (two figures)?










share|improve this question






















  • For the binary cross-entropy loss, there is only one probability output, because the other probability is just 1 - p, so there is no need to output both probabilities.

    – Matias Valdenegro
    Mar 23 at 8:48











  • You are using sigmoid on the output layer with 1 node. This means that you're going to get a single output value (which can be the likelihood of presence of a class) and works well for binary classification as a logistic regression function. If you're looking for probability distribution, however, then you need to use 2 nodes on the output layer with the softmax activation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.

    – amityadav
    Mar 24 at 4:46

















0















I have trained a binary classification task with Keras according to this instruction "https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html".



However, model.predict returns only one figure such as [[0.6343]].
I think it should return two figures such as [[0.6343, 0.1245]] where each figure represents the probability of each class.



I'm using Keras of version 2.2.4 and Tensorflow of version 1.13.1.



Here is my code.



from keras.models import Sequential
from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import np_utils
from sklearn.datasets import fetch_mldata
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import tensorflowjs as tfjs


##############
# Train model
##############

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(1))
model.add(Activation('sigmoid'))

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


################################
# Read image data from directory
################################

batch_size = 16

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
fill_mode='wrap',
zoom_range=0.2,
horizontal_flip=True,
vertical_flip=True
)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1./255)

# this is a generator that will read pictures found in
# subfolers of 'data/train', and indefinitely generate
# batches of augmented image data
train_generator = train_datagen.flow_from_directory(
'dataset/train', # this is the target directory
target_size=(96, 128), # all images will be resized to 150x150
batch_size=batch_size,
class_mode='binary') # since we use binary_crossentropy loss, we need binary labels

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
'dataset/validation',
target_size=(96, 128),
batch_size=batch_size,
class_mode='binary')


##############
# Fit model
##############

model.fit_generator(
train_generator,
steps_per_epoch=2000 // batch_size,
epochs=30,
validation_data=validation_generator,
validation_steps=800 // batch_size)
model.save('model.h5') # always save your weights after training or during training
tfjs.converters.save_keras_model(model, './')


##############
# Predict class
##############

img = load_img('./dataset/validation/dog/image001.png')

if (img.size == (96, 128)):
img = img.rotate(90, expand=True)

x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
x = x / 255
x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

model.predict(x, batch_size=None, verbose=0, steps=None)


How should I fix the code to generate what I expect (two figures)?










share|improve this question






















  • For the binary cross-entropy loss, there is only one probability output, because the other probability is just 1 - p, so there is no need to output both probabilities.

    – Matias Valdenegro
    Mar 23 at 8:48











  • You are using sigmoid on the output layer with 1 node. This means that you're going to get a single output value (which can be the likelihood of presence of a class) and works well for binary classification as a logistic regression function. If you're looking for probability distribution, however, then you need to use 2 nodes on the output layer with the softmax activation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.

    – amityadav
    Mar 24 at 4:46













0












0








0








I have trained a binary classification task with Keras according to this instruction "https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html".



However, model.predict returns only one figure such as [[0.6343]].
I think it should return two figures such as [[0.6343, 0.1245]] where each figure represents the probability of each class.



I'm using Keras of version 2.2.4 and Tensorflow of version 1.13.1.



Here is my code.



from keras.models import Sequential
from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import np_utils
from sklearn.datasets import fetch_mldata
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import tensorflowjs as tfjs


##############
# Train model
##############

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(1))
model.add(Activation('sigmoid'))

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


################################
# Read image data from directory
################################

batch_size = 16

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
fill_mode='wrap',
zoom_range=0.2,
horizontal_flip=True,
vertical_flip=True
)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1./255)

# this is a generator that will read pictures found in
# subfolers of 'data/train', and indefinitely generate
# batches of augmented image data
train_generator = train_datagen.flow_from_directory(
'dataset/train', # this is the target directory
target_size=(96, 128), # all images will be resized to 150x150
batch_size=batch_size,
class_mode='binary') # since we use binary_crossentropy loss, we need binary labels

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
'dataset/validation',
target_size=(96, 128),
batch_size=batch_size,
class_mode='binary')


##############
# Fit model
##############

model.fit_generator(
train_generator,
steps_per_epoch=2000 // batch_size,
epochs=30,
validation_data=validation_generator,
validation_steps=800 // batch_size)
model.save('model.h5') # always save your weights after training or during training
tfjs.converters.save_keras_model(model, './')


##############
# Predict class
##############

img = load_img('./dataset/validation/dog/image001.png')

if (img.size == (96, 128)):
img = img.rotate(90, expand=True)

x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
x = x / 255
x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

model.predict(x, batch_size=None, verbose=0, steps=None)


How should I fix the code to generate what I expect (two figures)?










share|improve this question














I have trained a binary classification task with Keras according to this instruction "https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html".



However, model.predict returns only one figure such as [[0.6343]].
I think it should return two figures such as [[0.6343, 0.1245]] where each figure represents the probability of each class.



I'm using Keras of version 2.2.4 and Tensorflow of version 1.13.1.



Here is my code.



from keras.models import Sequential
from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import np_utils
from sklearn.datasets import fetch_mldata
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import tensorflowjs as tfjs


##############
# Train model
##############

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(1))
model.add(Activation('sigmoid'))

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


################################
# Read image data from directory
################################

batch_size = 16

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
fill_mode='wrap',
zoom_range=0.2,
horizontal_flip=True,
vertical_flip=True
)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1./255)

# this is a generator that will read pictures found in
# subfolers of 'data/train', and indefinitely generate
# batches of augmented image data
train_generator = train_datagen.flow_from_directory(
'dataset/train', # this is the target directory
target_size=(96, 128), # all images will be resized to 150x150
batch_size=batch_size,
class_mode='binary') # since we use binary_crossentropy loss, we need binary labels

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
'dataset/validation',
target_size=(96, 128),
batch_size=batch_size,
class_mode='binary')


##############
# Fit model
##############

model.fit_generator(
train_generator,
steps_per_epoch=2000 // batch_size,
epochs=30,
validation_data=validation_generator,
validation_steps=800 // batch_size)
model.save('model.h5') # always save your weights after training or during training
tfjs.converters.save_keras_model(model, './')


##############
# Predict class
##############

img = load_img('./dataset/validation/dog/image001.png')

if (img.size == (96, 128)):
img = img.rotate(90, expand=True)

x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
x = x / 255
x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

model.predict(x, batch_size=None, verbose=0, steps=None)


How should I fix the code to generate what I expect (two figures)?







python tensorflow keras deep-learning






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 0:52









Uzu YuyaUzu Yuya

11




11












  • For the binary cross-entropy loss, there is only one probability output, because the other probability is just 1 - p, so there is no need to output both probabilities.

    – Matias Valdenegro
    Mar 23 at 8:48











  • You are using sigmoid on the output layer with 1 node. This means that you're going to get a single output value (which can be the likelihood of presence of a class) and works well for binary classification as a logistic regression function. If you're looking for probability distribution, however, then you need to use 2 nodes on the output layer with the softmax activation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.

    – amityadav
    Mar 24 at 4:46

















  • For the binary cross-entropy loss, there is only one probability output, because the other probability is just 1 - p, so there is no need to output both probabilities.

    – Matias Valdenegro
    Mar 23 at 8:48











  • You are using sigmoid on the output layer with 1 node. This means that you're going to get a single output value (which can be the likelihood of presence of a class) and works well for binary classification as a logistic regression function. If you're looking for probability distribution, however, then you need to use 2 nodes on the output layer with the softmax activation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.

    – amityadav
    Mar 24 at 4:46
















For the binary cross-entropy loss, there is only one probability output, because the other probability is just 1 - p, so there is no need to output both probabilities.

– Matias Valdenegro
Mar 23 at 8:48





For the binary cross-entropy loss, there is only one probability output, because the other probability is just 1 - p, so there is no need to output both probabilities.

– Matias Valdenegro
Mar 23 at 8:48













You are using sigmoid on the output layer with 1 node. This means that you're going to get a single output value (which can be the likelihood of presence of a class) and works well for binary classification as a logistic regression function. If you're looking for probability distribution, however, then you need to use 2 nodes on the output layer with the softmax activation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.

– amityadav
Mar 24 at 4:46





You are using sigmoid on the output layer with 1 node. This means that you're going to get a single output value (which can be the likelihood of presence of a class) and works well for binary classification as a logistic regression function. If you're looking for probability distribution, however, then you need to use 2 nodes on the output layer with the softmax activation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.

– amityadav
Mar 24 at 4:46












1 Answer
1






active

oldest

votes


















0














Thanks to Matias and amityadav, I solved this problem.
I had to make following chages.



  1. Use 'categorical_crossentropy' loss

  2. Use 'softmax' for the final activation

  3. Give '2' to the final Dense function

  4. Use 'categorical' for class_mode of flow_from_directory

My final code looks like this



from keras.models import Sequential
from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import np_utils
from sklearn.datasets import fetch_mldata
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import tensorflowjs as tfjs


##############
# Train model
##############

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(2))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])


################################
# Read image data from directory
################################

batch_size = 16

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
fill_mode='wrap',
zoom_range=0.2,
horizontal_flip=True,
vertical_flip=True
)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1./255)

# this is a generator that will read pictures found in
# subfolers of 'data/train', and indefinitely generate
# batches of augmented image data
train_generator = train_datagen.flow_from_directory(
'dataset/train', # this is the target directory
target_size=(96, 128), # all images will be resized to 150x150
batch_size=batch_size,
class_mode='categorical') # since we use binary_crossentropy loss, we need binary labels

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
'dataset/validation',
target_size=(96, 128),
batch_size=batch_size,
class_mode='categorical')


##############
# Fit model
##############

model.fit_generator(
train_generator,
steps_per_epoch=2000 // batch_size,
epochs=30,
validation_data=validation_generator,
validation_steps=800 // batch_size)
model.save('model.h5') # always save your weights after training or during training
tfjs.converters.save_keras_model(model, './')


##############
# Predict class
##############

img = load_img('./dataset/validation/dog/image001.png')

if (img.size == (96, 128)):
img = img.rotate(90, expand=True)

x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
x = x / 255
x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

model.predict(x, batch_size=None, verbose=0, steps=None)





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55309566%2fkeras-model-predict-only-returns-one-figure-for-binary-classification-task%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Thanks to Matias and amityadav, I solved this problem.
    I had to make following chages.



    1. Use 'categorical_crossentropy' loss

    2. Use 'softmax' for the final activation

    3. Give '2' to the final Dense function

    4. Use 'categorical' for class_mode of flow_from_directory

    My final code looks like this



    from keras.models import Sequential
    from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
    from keras.utils import np_utils
    from sklearn.datasets import fetch_mldata
    from keras.datasets import mnist
    from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
    import pandas as pd
    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    import tensorflowjs as tfjs


    ##############
    # Train model
    ##############

    model = Sequential()
    model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(32, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(128, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
    model.add(Dense(128))
    model.add(Activation('relu'))
    model.add(Dropout(0.25))
    model.add(Dense(2))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy',
    optimizer='rmsprop',
    metrics=['accuracy'])


    ################################
    # Read image data from directory
    ################################

    batch_size = 16

    # this is the augmentation configuration we will use for training
    train_datagen = ImageDataGenerator(
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    rescale=1./255,
    shear_range=0.2,
    fill_mode='wrap',
    zoom_range=0.2,
    horizontal_flip=True,
    vertical_flip=True
    )

    # this is the augmentation configuration we will use for testing:
    # only rescaling
    test_datagen = ImageDataGenerator(rescale=1./255)

    # this is a generator that will read pictures found in
    # subfolers of 'data/train', and indefinitely generate
    # batches of augmented image data
    train_generator = train_datagen.flow_from_directory(
    'dataset/train', # this is the target directory
    target_size=(96, 128), # all images will be resized to 150x150
    batch_size=batch_size,
    class_mode='categorical') # since we use binary_crossentropy loss, we need binary labels

    # this is a similar generator, for validation data
    validation_generator = test_datagen.flow_from_directory(
    'dataset/validation',
    target_size=(96, 128),
    batch_size=batch_size,
    class_mode='categorical')


    ##############
    # Fit model
    ##############

    model.fit_generator(
    train_generator,
    steps_per_epoch=2000 // batch_size,
    epochs=30,
    validation_data=validation_generator,
    validation_steps=800 // batch_size)
    model.save('model.h5') # always save your weights after training or during training
    tfjs.converters.save_keras_model(model, './')


    ##############
    # Predict class
    ##############

    img = load_img('./dataset/validation/dog/image001.png')

    if (img.size == (96, 128)):
    img = img.rotate(90, expand=True)

    x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
    x = x / 255
    x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

    model.predict(x, batch_size=None, verbose=0, steps=None)





    share|improve this answer



























      0














      Thanks to Matias and amityadav, I solved this problem.
      I had to make following chages.



      1. Use 'categorical_crossentropy' loss

      2. Use 'softmax' for the final activation

      3. Give '2' to the final Dense function

      4. Use 'categorical' for class_mode of flow_from_directory

      My final code looks like this



      from keras.models import Sequential
      from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
      from keras.utils import np_utils
      from sklearn.datasets import fetch_mldata
      from keras.datasets import mnist
      from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
      import pandas as pd
      import numpy as np
      import matplotlib
      import matplotlib.pyplot as plt
      import tensorflowjs as tfjs


      ##############
      # Train model
      ##############

      model = Sequential()
      model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
      model.add(Activation('relu'))
      model.add(MaxPooling2D(pool_size=(2, 2)))

      model.add(Conv2D(32, (3, 3)))
      model.add(Activation('relu'))
      model.add(MaxPooling2D(pool_size=(2, 2)))

      model.add(Conv2D(64, (3, 3)))
      model.add(Activation('relu'))
      model.add(MaxPooling2D(pool_size=(2, 2)))

      model.add(Conv2D(64, (3, 3)))
      model.add(Activation('relu'))
      model.add(MaxPooling2D(pool_size=(2, 2)))

      model.add(Conv2D(128, (3, 3)))
      model.add(Activation('relu'))
      model.add(MaxPooling2D(pool_size=(2, 2)))

      model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
      model.add(Dense(128))
      model.add(Activation('relu'))
      model.add(Dropout(0.25))
      model.add(Dense(2))
      model.add(Activation('softmax'))

      model.compile(loss='categorical_crossentropy',
      optimizer='rmsprop',
      metrics=['accuracy'])


      ################################
      # Read image data from directory
      ################################

      batch_size = 16

      # this is the augmentation configuration we will use for training
      train_datagen = ImageDataGenerator(
      rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      rescale=1./255,
      shear_range=0.2,
      fill_mode='wrap',
      zoom_range=0.2,
      horizontal_flip=True,
      vertical_flip=True
      )

      # this is the augmentation configuration we will use for testing:
      # only rescaling
      test_datagen = ImageDataGenerator(rescale=1./255)

      # this is a generator that will read pictures found in
      # subfolers of 'data/train', and indefinitely generate
      # batches of augmented image data
      train_generator = train_datagen.flow_from_directory(
      'dataset/train', # this is the target directory
      target_size=(96, 128), # all images will be resized to 150x150
      batch_size=batch_size,
      class_mode='categorical') # since we use binary_crossentropy loss, we need binary labels

      # this is a similar generator, for validation data
      validation_generator = test_datagen.flow_from_directory(
      'dataset/validation',
      target_size=(96, 128),
      batch_size=batch_size,
      class_mode='categorical')


      ##############
      # Fit model
      ##############

      model.fit_generator(
      train_generator,
      steps_per_epoch=2000 // batch_size,
      epochs=30,
      validation_data=validation_generator,
      validation_steps=800 // batch_size)
      model.save('model.h5') # always save your weights after training or during training
      tfjs.converters.save_keras_model(model, './')


      ##############
      # Predict class
      ##############

      img = load_img('./dataset/validation/dog/image001.png')

      if (img.size == (96, 128)):
      img = img.rotate(90, expand=True)

      x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
      x = x / 255
      x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

      model.predict(x, batch_size=None, verbose=0, steps=None)





      share|improve this answer

























        0












        0








        0







        Thanks to Matias and amityadav, I solved this problem.
        I had to make following chages.



        1. Use 'categorical_crossentropy' loss

        2. Use 'softmax' for the final activation

        3. Give '2' to the final Dense function

        4. Use 'categorical' for class_mode of flow_from_directory

        My final code looks like this



        from keras.models import Sequential
        from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
        from keras.utils import np_utils
        from sklearn.datasets import fetch_mldata
        from keras.datasets import mnist
        from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
        import pandas as pd
        import numpy as np
        import matplotlib
        import matplotlib.pyplot as plt
        import tensorflowjs as tfjs


        ##############
        # Train model
        ##############

        model = Sequential()
        model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(32, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(64, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(64, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(128, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
        model.add(Dense(128))
        model.add(Activation('relu'))
        model.add(Dropout(0.25))
        model.add(Dense(2))
        model.add(Activation('softmax'))

        model.compile(loss='categorical_crossentropy',
        optimizer='rmsprop',
        metrics=['accuracy'])


        ################################
        # Read image data from directory
        ################################

        batch_size = 16

        # this is the augmentation configuration we will use for training
        train_datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        rescale=1./255,
        shear_range=0.2,
        fill_mode='wrap',
        zoom_range=0.2,
        horizontal_flip=True,
        vertical_flip=True
        )

        # this is the augmentation configuration we will use for testing:
        # only rescaling
        test_datagen = ImageDataGenerator(rescale=1./255)

        # this is a generator that will read pictures found in
        # subfolers of 'data/train', and indefinitely generate
        # batches of augmented image data
        train_generator = train_datagen.flow_from_directory(
        'dataset/train', # this is the target directory
        target_size=(96, 128), # all images will be resized to 150x150
        batch_size=batch_size,
        class_mode='categorical') # since we use binary_crossentropy loss, we need binary labels

        # this is a similar generator, for validation data
        validation_generator = test_datagen.flow_from_directory(
        'dataset/validation',
        target_size=(96, 128),
        batch_size=batch_size,
        class_mode='categorical')


        ##############
        # Fit model
        ##############

        model.fit_generator(
        train_generator,
        steps_per_epoch=2000 // batch_size,
        epochs=30,
        validation_data=validation_generator,
        validation_steps=800 // batch_size)
        model.save('model.h5') # always save your weights after training or during training
        tfjs.converters.save_keras_model(model, './')


        ##############
        # Predict class
        ##############

        img = load_img('./dataset/validation/dog/image001.png')

        if (img.size == (96, 128)):
        img = img.rotate(90, expand=True)

        x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
        x = x / 255
        x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

        model.predict(x, batch_size=None, verbose=0, steps=None)





        share|improve this answer













        Thanks to Matias and amityadav, I solved this problem.
        I had to make following chages.



        1. Use 'categorical_crossentropy' loss

        2. Use 'softmax' for the final activation

        3. Give '2' to the final Dense function

        4. Use 'categorical' for class_mode of flow_from_directory

        My final code looks like this



        from keras.models import Sequential
        from keras.layers import Activation, Dense, Dropout, Flatten, Conv2D, MaxPooling2D
        from keras.utils import np_utils
        from sklearn.datasets import fetch_mldata
        from keras.datasets import mnist
        from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
        import pandas as pd
        import numpy as np
        import matplotlib
        import matplotlib.pyplot as plt
        import tensorflowjs as tfjs


        ##############
        # Train model
        ##############

        model = Sequential()
        model.add(Conv2D(32, (3, 3), input_shape=(96, 128, 3), data_format="channels_last"))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(32, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(64, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(64, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Conv2D(128, (3, 3)))
        model.add(Activation('relu'))
        model.add(MaxPooling2D(pool_size=(2, 2)))

        model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
        model.add(Dense(128))
        model.add(Activation('relu'))
        model.add(Dropout(0.25))
        model.add(Dense(2))
        model.add(Activation('softmax'))

        model.compile(loss='categorical_crossentropy',
        optimizer='rmsprop',
        metrics=['accuracy'])


        ################################
        # Read image data from directory
        ################################

        batch_size = 16

        # this is the augmentation configuration we will use for training
        train_datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        rescale=1./255,
        shear_range=0.2,
        fill_mode='wrap',
        zoom_range=0.2,
        horizontal_flip=True,
        vertical_flip=True
        )

        # this is the augmentation configuration we will use for testing:
        # only rescaling
        test_datagen = ImageDataGenerator(rescale=1./255)

        # this is a generator that will read pictures found in
        # subfolers of 'data/train', and indefinitely generate
        # batches of augmented image data
        train_generator = train_datagen.flow_from_directory(
        'dataset/train', # this is the target directory
        target_size=(96, 128), # all images will be resized to 150x150
        batch_size=batch_size,
        class_mode='categorical') # since we use binary_crossentropy loss, we need binary labels

        # this is a similar generator, for validation data
        validation_generator = test_datagen.flow_from_directory(
        'dataset/validation',
        target_size=(96, 128),
        batch_size=batch_size,
        class_mode='categorical')


        ##############
        # Fit model
        ##############

        model.fit_generator(
        train_generator,
        steps_per_epoch=2000 // batch_size,
        epochs=30,
        validation_data=validation_generator,
        validation_steps=800 // batch_size)
        model.save('model.h5') # always save your weights after training or during training
        tfjs.converters.save_keras_model(model, './')


        ##############
        # Predict class
        ##############

        img = load_img('./dataset/validation/dog/image001.png')

        if (img.size == (96, 128)):
        img = img.rotate(90, expand=True)

        x = img_to_array(img) # this is a Numpy array with shape (3, 150, 150)
        x = x / 255
        x = x.reshape((1,) + x.shape) # this is a Numpy array with shape (1, 3, 150, 150)

        model.predict(x, batch_size=None, verbose=0, steps=None)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 30 at 6:26









        Uzu YuyaUzu Yuya

        11




        11





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55309566%2fkeras-model-predict-only-returns-one-figure-for-binary-classification-task%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해