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;
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
add a comment |
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
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 usingsigmoidon 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 thesoftmaxactivation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.
– amityadav
Mar 24 at 4:46
add a comment |
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
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
python tensorflow keras deep-learning
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 usingsigmoidon 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 thesoftmaxactivation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.
– amityadav
Mar 24 at 4:46
add a comment |
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 usingsigmoidon 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 thesoftmaxactivation 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
add a comment |
1 Answer
1
active
oldest
votes
Thanks to Matias and amityadav, I solved this problem.
I had to make following chages.
- Use 'categorical_crossentropy' loss
- Use 'softmax' for the final activation
- Give '2' to the final Dense function
- 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)
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Thanks to Matias and amityadav, I solved this problem.
I had to make following chages.
- Use 'categorical_crossentropy' loss
- Use 'softmax' for the final activation
- Give '2' to the final Dense function
- 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)
add a comment |
Thanks to Matias and amityadav, I solved this problem.
I had to make following chages.
- Use 'categorical_crossentropy' loss
- Use 'softmax' for the final activation
- Give '2' to the final Dense function
- 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)
add a comment |
Thanks to Matias and amityadav, I solved this problem.
I had to make following chages.
- Use 'categorical_crossentropy' loss
- Use 'softmax' for the final activation
- Give '2' to the final Dense function
- 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)
Thanks to Matias and amityadav, I solved this problem.
I had to make following chages.
- Use 'categorical_crossentropy' loss
- Use 'softmax' for the final activation
- Give '2' to the final Dense function
- 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)
answered Mar 30 at 6:26
Uzu YuyaUzu Yuya
11
11
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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
sigmoidon 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 thesoftmaxactivation function. This will give you 2 outputs for each prediction with the probability scores for the two classes.– amityadav
Mar 24 at 4:46