Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get label prediction of binary image classification from Tensorflow

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/
—/COVID19/
——/img1.jpg
——/img2.jpg
——/img3.jpg
—/NORMAL/
——/img4.jpg
——/img5.jpg
——/img6.jpg

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

Map the desired values into the array

mapper = {1: "NORMAL", 0: "COVID19"}
np.vectorize(mapper.get)(output)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading