Skip to content

Commit d447f06

Browse files
committed
update
2 parents ca367a8 + 91f13e4 commit d447f06

File tree

12 files changed

+390
-80
lines changed

12 files changed

+390
-80
lines changed

demo/mnist/api_train_v2.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,26 +20,29 @@ def main():
2020

2121
adam_optimizer = paddle.optimizer.Adam(learning_rate=0.01)
2222

23+
trainer = paddle.trainer.SGD(cost=cost,
24+
parameters=parameters,
25+
update_equation=adam_optimizer)
26+
2327
def event_handler(event):
2428
if isinstance(event, paddle.event.EndIteration):
25-
if event.batch_id % 100 == 0:
26-
print "Pass %d, Batch %d, Cost %f, %s" % (
27-
event.pass_id, event.batch_id, event.cost, event.metrics)
29+
if event.batch_id % 1000 == 0:
30+
result = trainer.test(reader=paddle.reader.batched(
31+
paddle.dataset.mnist.test(), batch_size=256))
32+
33+
print "Pass %d, Batch %d, Cost %f, %s, Testing metrics %s" % (
34+
event.pass_id, event.batch_id, event.cost, event.metrics,
35+
result.metrics)
36+
2837
else:
2938
pass
3039

31-
trainer = paddle.trainer.SGD(update_equation=adam_optimizer)
32-
3340
trainer.train(
3441
reader=paddle.reader.batched(
3542
paddle.reader.shuffle(
3643
paddle.dataset.mnist.train(), buf_size=8192),
3744
batch_size=32),
38-
cost=cost,
39-
parameters=parameters,
40-
event_handler=event_handler,
41-
reader_dict={images.name: 0,
42-
label.name: 1})
45+
event_handler=event_handler)
4346

4447

4548
if __name__ == '__main__':

doc/howto/usage/cluster/cluster_train_cn.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
在本文中,我们将阐释如何在集群上运行分布式 Paddle 训练作业。我们将以[推荐系统](https://github.com/baidu/Paddle/tree/develop/demo/recommendation)为例创建分布式的单进程训练。
88

9-
在本文中使用的[脚本](https://github.com/baidu/Paddle/tree/develop/paddle/scripts/cluster_train)通过 SSH 运行分布式作业。 它们还可以供那些运行更复杂的集群管理系统(如 MPI 和 [Kubernetes](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/howto/usage/cluster/k8s) )的用户参考。
9+
在本文中使用的[脚本](https://github.com/baidu/Paddle/tree/develop/paddle/scripts/cluster_train)通过 SSH 运行分布式作业。 它们还可以供那些运行更复杂的集群管理系统(如 MPI 和 [Kubernetes](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/howto/usage/k8s) )的用户参考。
1010

1111
## 前提条件
1212

doc/howto/usage/cluster/cluster_train_en.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
In this article, we explain how to run distributed Paddle training jobs on clusters. We will create the distributed version of the single-process training example, [recommendation](https://github.com/baidu/Paddle/tree/develop/demo/recommendation).
44

5-
[Scripts](https://github.com/baidu/Paddle/tree/develop/paddle/scripts/cluster_train) used in this article launch distributed jobs via SSH. They also work as a reference for users running more sophisticated cluster management systems like MPI and [Kubernetes](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/howto/usage/cluster/k8s).
5+
[Scripts](https://github.com/baidu/Paddle/tree/develop/paddle/scripts/cluster_train) used in this article launch distributed jobs via SSH. They also work as a reference for users running more sophisticated cluster management systems like MPI and [Kubernetes](https://github.com/PaddlePaddle/Paddle/tree/develop/doc/howto/usage/k8s).
66

77
## Prerequisite
88

python/paddle/v2/dataset/common.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,10 @@ def download(url, module_name, md5sum):
3232
shutil.copyfileobj(r.raw, f)
3333

3434
return filename
35+
36+
37+
def dict_add(a_dict, ele):
38+
if ele in a_dict:
39+
a_dict[ele] += 1
40+
else:
41+
a_dict[ele] = 1

python/paddle/v2/dataset/imdb.py

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
# /usr/bin/env python
2+
# -*- coding:utf-8 -*-
3+
4+
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
5+
#
6+
# Licensed under the Apache License, Version 2.0 (the "License");
7+
# you may not use this file except in compliance with the License.
8+
# You may obtain a copy of the License at
9+
#
10+
# http://www.apache.org/licenses/LICENSE-2.0
11+
#
12+
# Unless required by applicable law or agreed to in writing, software
13+
# distributed under the License is distributed on an "AS IS" BASIS,
14+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
# See the License for the specific language governing permissions and
16+
# limitations under the License.
17+
"""
18+
IMDB dataset: http://ai.stanford.edu/%7Eamaas/data/sentiment/aclImdb_v1.tar.gz
19+
"""
20+
import paddle.v2.dataset.common
21+
import tarfile
22+
import Queue
23+
import re
24+
import string
25+
import threading
26+
27+
__all__ = ['build_dict', 'train', 'test']
28+
29+
URL = 'http://ai.stanford.edu/%7Eamaas/data/sentiment/aclImdb_v1.tar.gz'
30+
MD5 = '7c2ac02c03563afcf9b574c7e56c153a'
31+
32+
33+
# Read files that match pattern. Tokenize and yield each file.
34+
def tokenize(pattern):
35+
with tarfile.open(paddle.v2.dataset.common.download(URL, 'imdb',
36+
MD5)) as tarf:
37+
# Note that we should use tarfile.next(), which does
38+
# sequential access of member files, other than
39+
# tarfile.extractfile, which does random access and might
40+
# destroy hard disks.
41+
tf = tarf.next()
42+
while tf != None:
43+
if bool(pattern.match(tf.name)):
44+
# newline and punctuations removal and ad-hoc tokenization.
45+
yield tarf.extractfile(tf).read().rstrip("\n\r").translate(
46+
None, string.punctuation).lower().split()
47+
tf = tarf.next()
48+
49+
50+
def build_dict(pattern, cutoff):
51+
word_freq = {}
52+
for doc in tokenize(pattern):
53+
for word in doc:
54+
paddle.v2.dataset.common.dict_add(word_freq, word)
55+
56+
# Not sure if we should prune less-frequent words here.
57+
word_freq = filter(lambda x: x[1] > cutoff, word_freq.items())
58+
59+
dictionary = sorted(word_freq, key=lambda x: (-x[1], x[0]))
60+
words, _ = list(zip(*dictionary))
61+
word_idx = dict(zip(words, xrange(len(words))))
62+
word_idx['<unk>'] = len(words)
63+
return word_idx
64+
65+
66+
def reader_creator(pos_pattern, neg_pattern, word_idx, buffer_size):
67+
UNK = word_idx['<unk>']
68+
69+
qs = [Queue.Queue(maxsize=buffer_size), Queue.Queue(maxsize=buffer_size)]
70+
71+
def load(pattern, queue):
72+
for doc in tokenize(pattern):
73+
queue.put(doc)
74+
queue.put(None)
75+
76+
def reader():
77+
# Creates two threads that loads positive and negative samples
78+
# into qs.
79+
t0 = threading.Thread(
80+
target=load, args=(
81+
pos_pattern,
82+
qs[0], ))
83+
t0.daemon = True
84+
t0.start()
85+
86+
t1 = threading.Thread(
87+
target=load, args=(
88+
neg_pattern,
89+
qs[1], ))
90+
t1.daemon = True
91+
t1.start()
92+
93+
# Read alternatively from qs[0] and qs[1].
94+
i = 0
95+
doc = qs[i].get()
96+
while doc != None:
97+
yield [word_idx.get(w, UNK) for w in doc], i % 2
98+
i += 1
99+
doc = qs[i % 2].get()
100+
101+
# If any queue is empty, reads from the other queue.
102+
i += 1
103+
doc = qs[i % 2].get()
104+
while doc != None:
105+
yield [word_idx.get(w, UNK) for w in doc], i % 2
106+
doc = qs[i % 2].get()
107+
108+
return reader()
109+
110+
111+
def train(word_idx):
112+
return reader_creator(
113+
re.compile("aclImdb/train/pos/.*\.txt$"),
114+
re.compile("aclImdb/train/neg/.*\.txt$"), word_idx, 1000)
115+
116+
117+
def test(word_idx):
118+
return reader_creator(
119+
re.compile("aclImdb/test/pos/.*\.txt$"),
120+
re.compile("aclImdb/test/neg/.*\.txt$"), word_idx, 1000)
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
imikolov's simple dataset: http://www.fit.vutbr.cz/~imikolov/rnnlm/
3+
"""
4+
import paddle.v2.dataset.common
5+
import tarfile
6+
7+
__all__ = ['train', 'test']
8+
9+
URL = 'http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz'
10+
MD5 = '30177ea32e27c525793142b6bf2c8e2d'
11+
12+
13+
def word_count(f, word_freq=None):
14+
add = paddle.v2.dataset.common.dict_add
15+
if word_freq == None:
16+
word_freq = {}
17+
18+
for l in f:
19+
for w in l.strip().split():
20+
add(word_freq, w)
21+
add(word_freq, '<s>')
22+
add(word_freq, '<e>')
23+
24+
return word_freq
25+
26+
27+
def build_dict(train_filename, test_filename):
28+
with tarfile.open(
29+
paddle.v2.dataset.common.download(
30+
paddle.v2.dataset.imikolov.URL, 'imikolov',
31+
paddle.v2.dataset.imikolov.MD5)) as tf:
32+
trainf = tf.extractfile(train_filename)
33+
testf = tf.extractfile(test_filename)
34+
word_freq = word_count(testf, word_count(trainf))
35+
36+
TYPO_FREQ = 50
37+
word_freq = filter(lambda x: x[1] > TYPO_FREQ, word_freq.items())
38+
39+
dictionary = sorted(word_freq, key=lambda x: (-x[1], x[0]))
40+
words, _ = list(zip(*dictionary))
41+
word_idx = dict(zip(words, xrange(len(words))))
42+
word_idx['<unk>'] = len(words)
43+
44+
return word_idx
45+
46+
47+
word_idx = {}
48+
49+
50+
def reader_creator(filename, n):
51+
global word_idx
52+
if len(word_idx) == 0:
53+
word_idx = build_dict('./simple-examples/data/ptb.train.txt',
54+
'./simple-examples/data/ptb.valid.txt')
55+
56+
def reader():
57+
with tarfile.open(
58+
paddle.v2.dataset.common.download(
59+
paddle.v2.dataset.imikolov.URL, 'imikolov',
60+
paddle.v2.dataset.imikolov.MD5)) as tf:
61+
f = tf.extractfile(filename)
62+
63+
UNK = word_idx['<unk>']
64+
for l in f:
65+
l = ['<s>'] + l.strip().split() + ['<e>']
66+
if len(l) >= n:
67+
l = [word_idx.get(w, UNK) for w in l]
68+
for i in range(n, len(l) + 1):
69+
yield tuple(l[i - n:i])
70+
71+
return reader
72+
73+
74+
def train(n):
75+
return reader_creator('./simple-examples/data/ptb.train.txt', n)
76+
77+
78+
def test(n):
79+
return reader_creator('./simple-examples/data/ptb.valid.txt', n)

python/paddle/v2/dataset/mnist.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99

1010
URL_PREFIX = 'http://yann.lecun.com/exdb/mnist/'
1111
TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz'
12-
TEST_IMAGE_MD5 = '25e3cc63507ef6e98d5dc541e8672bb6'
12+
TEST_IMAGE_MD5 = '9fb629c4189551a2d022fa330f9573f3'
1313
TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz'
14-
TEST_LABEL_MD5 = '4e9511fe019b2189026bd0421ba7b688'
14+
TEST_LABEL_MD5 = 'ec29112dd5afa0611ce80d1b7f02629c'
1515
TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz'
1616
TRAIN_IMAGE_MD5 = 'f68b3c2dcbeaaa9fbdd348bbdeb94873'
1717
TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz'
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import paddle.v2.dataset.imdb
2+
import unittest
3+
import re
4+
5+
TRAIN_POS_PATTERN = re.compile("aclImdb/train/pos/.*\.txt$")
6+
TRAIN_NEG_PATTERN = re.compile("aclImdb/train/neg/.*\.txt$")
7+
TRAIN_PATTERN = re.compile("aclImdb/train/.*\.txt$")
8+
9+
TEST_POS_PATTERN = re.compile("aclImdb/test/pos/.*\.txt$")
10+
TEST_NEG_PATTERN = re.compile("aclImdb/test/neg/.*\.txt$")
11+
TEST_PATTERN = re.compile("aclImdb/test/.*\.txt$")
12+
13+
14+
class TestIMDB(unittest.TestCase):
15+
word_idx = None
16+
17+
def test_build_dict(self):
18+
if self.word_idx == None:
19+
self.word_idx = paddle.v2.dataset.imdb.build_dict(TRAIN_PATTERN,
20+
150)
21+
22+
self.assertEqual(len(self.word_idx), 7036)
23+
24+
def check_dataset(self, dataset, expected_size):
25+
if self.word_idx == None:
26+
self.word_idx = paddle.v2.dataset.imdb.build_dict(TRAIN_PATTERN,
27+
150)
28+
29+
sum = 0
30+
for l in dataset(self.word_idx):
31+
self.assertEqual(l[1], sum % 2)
32+
sum += 1
33+
self.assertEqual(sum, expected_size)
34+
35+
def test_train(self):
36+
self.check_dataset(paddle.v2.dataset.imdb.train, 25000)
37+
38+
def test_test(self):
39+
self.check_dataset(paddle.v2.dataset.imdb.test, 25000)
40+
41+
42+
if __name__ == '__main__':
43+
unittest.main()
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import paddle.v2.dataset.imikolov
2+
import unittest
3+
4+
5+
class TestMikolov(unittest.TestCase):
6+
def check_reader(self, reader, n):
7+
for l in reader():
8+
self.assertEqual(len(l), n)
9+
10+
def test_train(self):
11+
n = 5
12+
self.check_reader(paddle.v2.dataset.imikolov.train(n), n)
13+
14+
def test_test(self):
15+
n = 5
16+
self.check_reader(paddle.v2.dataset.imikolov.test(n), n)
17+
18+
19+
if __name__ == '__main__':
20+
unittest.main()

python/paddle/v2/event.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@
1111
TODO(yuyang18): Complete it!
1212
"""
1313
import py_paddle.swig_paddle as api
14-
__all__ = ['EndIteration', 'BeginIteration', 'BeginPass', 'EndPass']
14+
15+
__all__ = [
16+
'EndIteration', 'BeginIteration', 'BeginPass', 'EndPass', 'TestResult'
17+
]
1518

1619

1720
class WithMetric(object):
@@ -30,6 +33,11 @@ def metrics(self):
3033
return retv
3134

3235

36+
class TestResult(WithMetric):
37+
def __init__(self, evaluator):
38+
super(TestResult, self).__init__(evaluator)
39+
40+
3341
class BeginPass(object):
3442
"""
3543
Event On One Pass Training Start.

0 commit comments

Comments
 (0)