evaluate.py 2.3 KB
Newer Older
W
wanglong03 已提交
1 2 3 4 5 6 7 8 9
#!/bin/env python

#function:
#   demo to show how to use converted model using caffe2fluid
#

import sys
import os
import numpy as np
10
import paddle.fluid as fluid
W
whs 已提交
11
import paddle
W
wanglong03 已提交
12

W
wanglong03 已提交
13

W
wanglong03 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
def test_model(exe, test_program, fetch_list, test_reader, feeder):
    acc_set = []

    for data in test_reader():
        acc_np, pred = exe.run(program=test_program,
                               feed=feeder.feed(data),
                               fetch_list=fetch_list)
        acc_set.append(float(acc_np))

    acc_val = np.array(acc_set).mean()
    return float(acc_val)


def evaluate(net_file, model_file):
    """ main
    """
    #1, build model
    net_path = os.path.dirname(net_file)
    if net_path not in sys.path:
        sys.path.insert(0, net_path)

    from lenet import LeNet as MyNet

    #1, define network topology
    images = fluid.layers.data(name='image', shape=[1, 28, 28], dtype='float32')
    label = fluid.layers.data(name='label', shape=[1], dtype='int64')

    net = MyNet({'data': images})
    prediction = net.layers['prob']
    acc = fluid.layers.accuracy(input=prediction, label=label)

45
    place = fluid.CPUPlace()
W
wanglong03 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    exe = fluid.Executor(place)
    exe.run(fluid.default_startup_program())

    #2, load weights
    if model_file.find('.npy') > 0:
        net.load(data_path=model_file, exe=exe, place=place)
    else:
        net.load(data_path=model_file, exe=exe)

    #3, test this model
    test_program = fluid.default_main_program().clone()
    test_reader = paddle.batch(paddle.dataset.mnist.test(), batch_size=128)

    feeder = fluid.DataFeeder(feed_list=[images, label], place=place)
    fetch_list = [acc, prediction]

    print('go to test model using test set')
    acc_val = test_model(exe, test_program, \
            fetch_list, test_reader, feeder)

    print('test accuracy is [%.4f], expected value[0.919]' % (acc_val))


if __name__ == "__main__":
    net_file = 'models/lenet/lenet.py'
    weight_file = 'models/lenet/lenet.npy'

    argc = len(sys.argv)
    if argc == 3:
        net_file = sys.argv[1]
W
wanglong03 已提交
76
        weight_file = sys.argv[2]
W
wanglong03 已提交
77 78 79
    elif argc > 1:
        print('usage:')
        print('\tpython %s [net_file] [weight_file]' % (sys.argv[0]))
W
wanglong03 已提交
80
        print('\teg:python %s %s %s %s' % (sys.argv[0], net_file, weight_file))
W
wanglong03 已提交
81 82 83
        sys.exit(1)

    evaluate(net_file, weight_file)