Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Input a single image to an H5 file and get percentages for each class as output

I'm using the COVID-19 Radiography Database to create a model that predicts if the user has COVID-19 or not.

This is the code that I have:

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

tf.random.set_seed(1234)

train_data_dir="X_train_data/"

#Used Sequential
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(8, (3, 3), activation='relu', input_shape=(64, 64, 3)))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2), strides=None, padding="valid"))
model.add(tf.keras.layers.Conv2D(16, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2), strides=None, padding="valid"))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(32))
model.add(tf.keras.layers.Dropout(.1, input_shape=(32,)))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

#Defining optimizer
from tensorflow.keras.optimizers import Adam

model.compile(optimizer=Adam(lr=0.0001), loss='binary_crossentropy', metrics=['accuracy'])

# Directing Images to train folder
from tensorflow.keras.preprocessing.image import ImageDataGenerator
img_height, img_width = 64,64
batch_size = 16
train_datagen = ImageDataGenerator(validation_split=0.3) # set validation split

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode='binary',
    subset='training') # set as training data

# Splitting images for validation set
validation_generator = train_datagen.flow_from_directory(
    train_data_dir, # same directory as training data
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode='binary',
    subset='validation') # set as validation data

# Training the model
trainer=model.fit(train_generator, validation_data=validation_generator, epochs=10, verbose=2)

model.save("cnn_covid_x-ray_v1.h5") #you can load this model from output part

I get a training accuracy of 97.82% and validation accuracy of 96.78%. How do I use my h5 file now to make predictions? For example, I want to input a single image, let's say a COVID-19 x-ray, and get the percentage of how likely it belongs to the COVID-19 class and how likely it belongs to the NORMAL class.

question from:https://stackoverflow.com/questions/65649401/input-a-single-image-to-an-h5-file-and-get-percentages-for-each-class-as-output

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

1 Reply

0 votes
by (71.8m points)

The first thing you have to do is to make sure the image that you wish to use undergoes the same preprocessing that was used on the training images. I noticed you did not rescale the images in ImageDataGenerator. If they were rescaled in something prior make sure you rescale your images in the same way. Next resize your images to 64 X 64. Feed the image to model.predict. It will produce a probability value as an output. If the value is less than or equal to .5 it is class 0 if greator than .5 it is class 1. To know which one is which use class_dict=train_generator.class_indices. Print the dictionary. It is of the form class name:index where class name is the name of the directory associated with the index. For example if you directories were named Covid and NonCovid your dictionary would look like {Covid:0, NonCovid:1}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...