0

How to get label prediction of binary image classification from Tensorflow ?

Enviroment:

  • Google colab
  • Tensorflow 2.7.0
  • Python 3.7.12

Dataset Structure:

/training/<br/>
---/COVID19/<br/>
------/img1.jpg<br/>
------/img2.jpg<br/>
------/img3.jpg<br/>
---/NORMAL/<br/>
------/img4.jpg<br/>
------/img5.jpg<br/>
------/img6.jpg<br/>

Make Dataset Code:

batch_size = 32
img_height = 300    
img_width = 300
epochs = 10
input_shape = (img_width, img_height, 3)
AUTOTUNE = tf.data.AUTOTUNE


dataset_url = "https://storage.googleapis.com/fdataset/Dataset.tgz"
data_dir = tf.keras.utils.get_file('training', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

image_count = len(list(data_dir.glob('*/*.jpg')))
print(image_count)

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  seed=123,
  subset="training",
  validation_split=0.8,
  image_size=(img_width, img_height),
  batch_size=batch_size)

val_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  seed=123,
  subset="validation",
  validation_split=0.2,
  image_size=(img_width, img_height),
  batch_size=batch_size)

train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

The Model:

model = tf.keras.Sequential()
base_model = tf.keras.applications.DenseNet121(input_shape=input_shape,include_top=False)
base_model.trainable=True
model.add(base_model)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(16,activation='relu'))
model.add(tf.keras.layers.Dense(1, activation="sigmoid"))

loss function: binary_crossentropy
optimizer : RMSprop
metrics : accuracy

after I make a model and train it, I make a prediction with a validation dataset using this code

(model.predict(val_ds) > 0.5).astype("int32")

so I got the result like this

array([[0],
   [1],
   [1],
   [0],
   [0]], dtype=int32)

then how to convert it again to label like "COVID19" or "NORMAL" the example like this:

array([["COVID19"],
   ["NORMAL"],
   ["NORMAL"],
   ["COVID19"],
   ["COVID19"]], dtype=int32)

1 Answer 1

1

Map the desired values into the array

mapper = {1: "NORMAL", 0: "COVID19"}
np.vectorize(mapper.get)(output)
Sign up to request clarification or add additional context in comments.

4 Comments

How to make sure 1 is "NORMAL" and 0 is "COVID19"?
The dictionary says it. @FianJulio
Keras takes in the values in alphabetical order from the dataset directories. In your case COVID19 and then NORMAL. So the labels correspond to 0 and 1.
Thank you very much @Vishnudev, that's the answer I was looking for

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.