【问题标题】:model prediction using CNN使用 CNN 进行模型预测
【发布时间】:2020-05-13 06:51:19
【问题描述】:

我目前正在使用 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)

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

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

    • Kuruppa - 抱歉,兄弟,我没有使用 google colab……还有其他解决方案吗?
    • 嘿@JohnDavis,如果它有效,你能接受它作为答案吗?还是没用?
    • 嘿@Gayal 仍然面临一些错误 - NameError Traceback(最近一次调用最后一次) in 6 #path='/content/' + fn # path到图像 7 #path='/content/' + fn # 到图像的路径 ----> 8 img=image.load_img(path, target_size=image_shape[:2]) 9 10 x=image.img_to_array(img ) NameError: name 'image_shape' 没有定义
    • 给 target_size 变量指定图像的大小,例如:target_size=(150, 150) 你必须给 batch_size 和 target_size 赋值
    猜你喜欢
    • 2018-03-02
    • 2018-12-13
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多