ranknet.py 1.7 KB
Newer Older
W
wangmeng28 已提交
1 2 3 4
"""
ranknet is the classic pairwise learning to rank algorithm
http://icml.cc/2015/wp-content/uploads/2015/06/icml_ranking.pdf
"""
C
caoying03 已提交
5 6 7
import paddle.v2 as paddle


D
dong zhihong 已提交
8
def half_ranknet(name_prefix, input_dim):
9
    """
C
caoying03 已提交
10 11 12 13 14
    parameter in same name will be shared in paddle framework,
    these parameters in ranknet can be used in shared state,
    e.g. left network and right network shared parameters in detail
    https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/api.md
    """
15
    # data layer
C
caoying03 已提交
16
    data = paddle.layer.data(name_prefix + "_data",
17
                             paddle.data_type.dense_vector(input_dim))
D
dong zhihong 已提交
18

19
    # hidden layer
20 21 22 23 24 25
    hd1 = paddle.layer.fc(input=data,
                          name=name_prefix + "_hidden",
                          size=10,
                          act=paddle.activation.Tanh(),
                          param_attr=paddle.attr.Param(
                              initial_std=0.01, name="hidden_w1"))
C
caoying03 已提交
26 27

    # fully connected layer and output layer
28 29 30 31 32 33
    output = paddle.layer.fc(input=hd1,
                             name=name_prefix + "_score",
                             size=1,
                             act=paddle.activation.Linear(),
                             param_attr=paddle.attr.Param(
                                 initial_std=0.01, name="output"))
34
    return output
D
dong zhihong 已提交
35 36 37


def ranknet(input_dim):
38
    # label layer
D
dzhwinter 已提交
39
    label = paddle.layer.data("label", paddle.data_type.dense_vector(1))
40 41 42 43 44 45 46 47 48

    # reuse the parameter in half_ranknet
    output_left = half_ranknet("left", input_dim)
    output_right = half_ranknet("right", input_dim)

    # rankcost layer
    cost = paddle.layer.rank_cost(
        name="cost", left=output_left, right=output_right, label=label)
    return cost