首页 > 解决方案 > 加载模型时的预测速度比在过程中拟合时的速度慢

问题描述

我有一个奇怪的问题,当我加载模型的权重时,DNN.predict 方法比使用 fit 方法训练时要慢得多。我还注意到,当我对一批图像进行预测时,预测的速度越来越快。

这是我的代码

class Reseau(object):

def init(self, img_size, lr=-1, activation=" "):
tf.logging.set_verbosity(tf.logging.ERROR)
self.lr = lr
self.activation = activation
self.img_size = img_size
self.alreadySaved = 0

def setting(self, X, Y, test_x, test_y, nbEpoch):
tflearn.init_graph(num_cores=32, gpu_memory_fraction=1)
with tf.device("/device:GPU:0"):
convnet = input_data(shape=[None, self.img_size, self.img_size, 3], name='input')

        convnet = conv_2d(convnet, 32, 5, activation=self.activation)
        convnet = max_pool_2d(convnet, 5)

        convnet = conv_2d(convnet, 64, 5, activation=self.activation)
        convnet = max_pool_2d(convnet, 5)

        convnet = conv_2d(convnet, 128, 5, activation=self.activation)
        convnet = max_pool_2d(convnet, 5)

        convnet = conv_2d(convnet, 64, 5, activation=self.activation)
        convnet = max_pool_2d(convnet, 5)

        convnet = conv_2d(convnet, 32, 5, activation=self.activation)
        convnet = max_pool_2d(convnet, 5)

        convnet = flatten(convnet)

        convnet = fully_connected(convnet, 1024, activation=self.activation, name='last')
        convnet = fully_connected(convnet, 1024, activation=self.activation, name='last')
        convnet = fully_connected(convnet, 1024, activation=self.activation, name='last')
        convnet = fully_connected(convnet, 1024, activation=self.activation, name='last')
        convnet = dropout(convnet, 0.8)

        convnet = fully_connected(convnet, 2, activation='softmax')
        convnet = regression(convnet, optimizer='adam', learning_rate=self.lr, loss='categorical_crossentropy', name='targets')

        self.model = tflearn.DNN(convnet, tensorboard_dir='log')

        if self.alreadySaved == 0:
            self.model.fit({'input': X}, {'targets': Y}, n_epoch=nbEpoch, validation_set=({'input': test_x}, {'targets': test_y}), snapshot_step=500, show_metric=True, run_id="model")
            self.model.save("./model")
        else:
            self.model.load("./model", weights_only=True)
    return self.model

def predire(self, img, label):
image = array(img).reshape(1, self.img_size,self.img_size,3)
model_out = self.model.predict(image)
rep = 0

    if np.argmax(model_out) == np.argmax(label): rep = 1
    else: rep = 0

    return rep

这是我主要的一部分

reseau.setting(X, Y, test_x, test_y, NB_EPOCH)

X = np.array([i[0] for i in test]).reshape(-1,IMG_SIZE,IMG_SIZE,3)
Y = [i[1] for i in test]
cpt = 0

vrai = 0
start_time = time.time()

for i in range(20):
    cpt = 0

    vrai = 0
    start_time = time.time()
    for img in tqdm(X):
        prediction = reseau.predire(img, Y[cpt])
        cpt += 1
        if prediction == 1:
            vrai += 1

如您所见,我对同一批次的图像进行了 20 次预测。第一次总是比其他的慢(没有拟合,我预测第一次是 82 张图像,然后是每秒 340 张,拟合后,第一次是 255 张图像,然后是每秒 340 张)。

我真的不知道要解决这个问题。

标签: pythontensorflowtflearn

解决方案


推荐阅读