Skip to content

Commit 3eef539

Browse files
committed
add word2vec test for the new API
1 parent 7cfd4e4 commit 3eef539

File tree

1 file changed

+146
-0
lines changed

1 file changed

+146
-0
lines changed
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import paddle
16+
import paddle.fluid as fluid
17+
import numpy as np
18+
import math
19+
import sys
20+
from functools import partial
21+
22+
PASS_NUM = 100
23+
EMBED_SIZE = 32
24+
HIDDEN_SIZE = 256
25+
N = 5
26+
BATCH_SIZE = 32
27+
28+
29+
def create_random_lodtensor(lod, place, low, high):
30+
# The range of data elements is [low, high]
31+
data = np.random.random_integers(low, high, [lod[-1], 1]).astype("int64")
32+
res = fluid.LoDTensor()
33+
res.set(data, place)
34+
res.set_lod([lod])
35+
return res
36+
37+
38+
word_dict = paddle.dataset.imikolov.build_dict()
39+
dict_size = len(word_dict)
40+
41+
42+
def inference_network(is_sparse):
43+
first_word = fluid.layers.data(name='firstw', shape=[1], dtype='int64')
44+
second_word = fluid.layers.data(name='secondw', shape=[1], dtype='int64')
45+
third_word = fluid.layers.data(name='thirdw', shape=[1], dtype='int64')
46+
forth_word = fluid.layers.data(name='forthw', shape=[1], dtype='int64')
47+
48+
embed_first = fluid.layers.embedding(
49+
input=first_word,
50+
size=[dict_size, EMBED_SIZE],
51+
dtype='float32',
52+
is_sparse=is_sparse,
53+
param_attr='shared_w')
54+
embed_second = fluid.layers.embedding(
55+
input=second_word,
56+
size=[dict_size, EMBED_SIZE],
57+
dtype='float32',
58+
is_sparse=is_sparse,
59+
param_attr='shared_w')
60+
embed_third = fluid.layers.embedding(
61+
input=third_word,
62+
size=[dict_size, EMBED_SIZE],
63+
dtype='float32',
64+
is_sparse=is_sparse,
65+
param_attr='shared_w')
66+
embed_forth = fluid.layers.embedding(
67+
input=forth_word,
68+
size=[dict_size, EMBED_SIZE],
69+
dtype='float32',
70+
is_sparse=is_sparse,
71+
param_attr='shared_w')
72+
73+
concat_embed = fluid.layers.concat(
74+
input=[embed_first, embed_second, embed_third, embed_forth], axis=1)
75+
hidden1 = fluid.layers.fc(input=concat_embed,
76+
size=HIDDEN_SIZE,
77+
act='sigmoid')
78+
predict_word = fluid.layers.fc(input=hidden1, size=dict_size, act='softmax')
79+
return predict_word
80+
81+
82+
def train_network():
83+
next_word = fluid.layers.data(name='nextw', shape=[1], dtype='int64')
84+
predict_word = inference_network()
85+
cost = fluid.layers.cross_entropy(input=predict_word, label=next_word)
86+
avg_cost = fluid.layers.mean(cost)
87+
return avg_cost
88+
89+
90+
def train(use_cuda, is_sparse, save_path):
91+
train_reader = paddle.batch(
92+
paddle.dataset.imikolov.train(word_dict, N), BATCH_SIZE)
93+
94+
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
95+
96+
def event_handler(event):
97+
if isinstance(event, fluid.EndPass):
98+
avg_cost = trainer.test(reader=paddle.dataset.imikolov.test(
99+
word_dict, N))
100+
101+
if avg_cost < 5.0:
102+
trainer.params.save(save_path)
103+
return
104+
if math.isnan(avg_cost):
105+
sys.exit("got NaN loss, training failed.")
106+
107+
trainer = fluid.Trainer(
108+
partial(inference_network, is_sparse),
109+
optimizer=fluid.optimizer.SGD(learning_rate=0.001),
110+
place=place,
111+
event_handler=event_handler)
112+
trainer.train(train_reader, 100)
113+
114+
115+
def infer(use_cuda, save_path):
116+
params = fluid.Params(save_path)
117+
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
118+
inferencer = fluid.Inferencer(inference_network, params, place=place)
119+
120+
lod = [0, 1]
121+
first_word = create_random_lodtensor(lod, place, low=0, high=dict_size - 1)
122+
second_word = create_random_lodtensor(lod, place, low=0, high=dict_size - 1)
123+
third_word = create_random_lodtensor(lod, place, low=0, high=dict_size - 1)
124+
fourth_word = create_random_lodtensor(lod, place, low=0, high=dict_size - 1)
125+
result = inferencer.infer({
126+
'firstw': first_word,
127+
'secondw': second_word,
128+
'thirdw': third_word,
129+
'forthw': fourth_word
130+
})
131+
print(result)
132+
133+
134+
def main(use_cuda, is_sparse):
135+
if use_cuda and not fluid.core.is_compiled_with_cuda():
136+
return
137+
138+
save_path = "word2vec.inference.model"
139+
train(use_cuda, is_sparse, save_path)
140+
infer(use_cuda, save_path)
141+
142+
143+
if __name__ == '__main__':
144+
for use_cuda in (False, True):
145+
for is_sparse in (False, True):
146+
main(use_cuda=use_cuda, is_sparse=is_sparse)

0 commit comments

Comments
 (0)