1

正在研究二进制类的分类问题,我现在使用下面的代码完成了单个图像中模型的训练和测试

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)

问题是每次我重新运行代码时,我都会不断地得到标签和准确性的预测,我不确定是什么原因造成的

4

1 回答 1

0

在训练模型时,有许多来源会在结果中产生随机性。首先,权重是随机初始化的,因此您的模型从 N 空间中的不同点开始(N 是可训练参数的数量)。像 dropout 这样的第二层在选择哪些节点方面具有随机性。一些 GPU 进程,特别是多处理,也可能具有一定程度的随机性。我看过很多关于在 tensorflow 中获得可重复结果的帖子,但我还没有找到一个似乎真正有效的帖子。一般来说,如果您的模型工作正常并且您运行了足够多的时期,那么结果应该相当接近。现在,一旦模型经过训练并且您将其用于预测,只要您使用相同的训练模型,您就应该得到相同的预测结果。

于 2020-10-11T03:02:48.203 回答