如何解决Keras预测同一输入图像的不同输出
在研究二元类的分类问题时,我已经使用下面的代码完成了在单个图像中的训练和测试模型
import warnings
import time
from urllib.request import urlopen
import os
import urllib.request
start_time = time.time()
with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=FutureWarning)
import numpy as np
from keras.preprocessing.image import img_to_array,load_img
from keras.models import Sequential
from keras.layers import Dropout,Flatten,Dense,GlobalAveragePooling2D
from keras.applications.vgg16 import VGG16
import tensorflow as tf
import logging
logging.getLogger('tensorflow').disabled = True
img_size = 224
class PersonPrediction:
def __init__(self):
self.class_dictionary = np.load(
'class_indices_vgg.npy',allow_pickle=True).item()
self.top_model_weights_path = 'v2/weights/bottleneck_fc_model_2020-10-10-05.h5'
self.num_classes = len(self.class_dictionary)
self.model = self.create_model(self.num_classes)
self.graph = tf.compat.v1.get_default_graph()
def create_model(self,num_of_cls):
model = Sequential()
vgg_model = VGG16(include_top=False,weights='imagenet',input_shape=(img_size,img_size,3))
for layer in vgg_model.layers[:-4]:
layer.trainable = False
model.add(vgg_model)
model.add(GlobalAveragePooling2D())
model.add(Dense(512,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1,activation='sigmoid'))
return model
def predict(self,path=None,file_name=None):
if path:
image_path = path
path = self.url_to_image(image_path)
else:
path = os.path.join('imgs',file_name)
print("[INFO] loading and preprocessing image...")
image = load_img(path,target_size=(224,224))
image = img_to_array(image)
# important! otherwise the predictions will be '0'
image = image / 255
image = np.expand_dims(image,axis=0)
label_idx = self.model.predict_classes(image)[0][0]
probability = self.model.predict(image)[0]
inv_map = {v: k for k,v in self.class_dictionary.items()}
label = inv_map[label_idx]
return label,probability[0]
path = 'temp.jpg'
tax_model = PersonPrediction()
label,proba = tax_model.predict(
file_name='frame303.jpg')
print(label,proba)
问题是每次重新运行代码时,我都会不断获得有关标签和准确性的预测,不确定是什么原因造成的
解决方法
在训练模型时,有许多来源会在结果中产生随机性。首先,权重是随机初始化的,因此您的模型是从N空间中的另一个点开始的(N是可训练参数的数量)。像dropout这样的第二层在选择哪个节点将成为节点方面具有随机性。一些GPU进程(尤其是具有多处理功能的GPU进程)也可能具有一定程度的随机性。我已经看到许多关于在tensorflow中获得可重复结果的帖子,但是我还没有找到似乎确实有效的帖子。通常,如果模型正常工作并且运行了足够的纪元,则结果应该相当接近。现在,一旦对模型进行训练并将其用于预测,只要您使用相同的训练模型,您就应该获得相同的预测结果。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。