CNN的模型预测

时间:2020-05-13 06:51:19

标签: tensorflow keras deep-learning tensorflow2.0 tf.keras

我目前正在使用Tensor flow -2.0构建CNN模型,但未使用转移学习。我的问题是如何用新图像进行预测?我想从目录中加载它并需要预测(分类问题)。

我的代码如下-

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Conv2D,MaxPool2D,Dropout,Flatten
from tensorflow.keras.callbacks import EarlyStopping

model = Sequential()

model.add(Conv2D(filters = 16,kernel_size = (3,3), input_shape = image_shape, activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))

model.add(Conv2D(filters = 32,kernel_size = (3,3), activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))

model.add(Conv2D(filters = 64,kernel_size = (3,3), activation = 'relu'))
model.add(MaxPool2D(pool_size = (2,2)))

model.add(Flatten())

model.add(Dense(128,activation = 'relu'))
#model.add(Dropout(0.5))

model.add(Dense(1,activation = 'sigmoid'))

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

early_stop = EarlyStopping(monitor = 'val_loss',patience = 2)

batch_size = 16

train_image_gen = image_gen.flow_from_directory(train_path,
                                               target_size = image_shape[:2],
                                               color_mode = 'rgb',
                                               batch_size = batch_size,
                                               class_mode = 'binary')

test_image_gen = image_gen.flow_from_directory(test_path,
                                               target_size = image_shape[:2],
                                               color_mode = 'rgb',
                                               batch_size = batch_size,
                                               class_mode = 'binary',
                                              shuffle = False)

class myCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={}):
        if(logs.get('accuracy')>0.97):
            print("\nReached 97% accuracy so cancelling training!")
            self.model.stop_training = True

callbacks = myCallback()
results = model.fit_generator(train_image_gen,epochs = 85,
                             validation_data = test_image_gen,
                             callbacks = [callbacks])

# Let's now save our model to a file
model.save('cell_image_classifier.h5')

# Load the model
model = tf.keras.models.load_model('cell_image_classifier.h5')

model.evaluate_generator(test_image_gen)

#Prediction on image
pred = model.predict_generator(test_image_gen)

predictions = pred > .5

print(classification_report(test_image_gen.classes,predictions))
confusion_matrix(test_image_gen.classes,predictions)

现在在外部,我想加载图像并需要预测。

1 个答案:

答案 0 :(得分:1)

可以!

import numpy as np
from keras.preprocessing import image

# predicting images
fn = 'cat-2083492_640.jpg'  # name of the image
path='/content/' + fn     # path to the image
img=image.load_img(path, target_size=(150, 150)) # edit the target_size

x=image.img_to_array(img)
x=np.expand_dims(x, axis=0)
images = np.vstack([x])

classes = model.predict(images, batch_size=16) # edit the batch_size

print(classes)