-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathEncoderDecoder.py
47 lines (39 loc) · 1.53 KB
/
EncoderDecoder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
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
45
46
#'!/usr/bin/env python
#-*- coding:utf-8 -*-
#!/usr/bin/python3
from chainer import Chain, functions, links
from Encoder import Encoder
from Decoder import Decoder
import numpy as np
from util.Common_function import CommonFunction
class EncoderDecoder(Chain):
def __init__(self, vocab_size, embed_size, hidden_size):
super(EncoderDecoder, self).__init__(
enc=Encoder(vocab_size, embed_size, hidden_size),
dec=Decoder(vocab_size, embed_size, hidden_size),
)
self.vocab_size = vocab_size
self.embed_size = embed_size
self.hidden_size = hidden_size
self.common_function = CommonFunction()
def reset(self, batch_size):
self.zerograds()
self.c = self.common_function.my_zeros((batch_size, self.hidden_size), np.float32)
self.h = self.common_function.my_zeros((batch_size, self.hidden_size), np.float32)
def encode(self, x):
self.c, self.h = self.enc(x, self.c, self.h)
def decode(self, y):
y, self.c, self.h = self.dec(y, self.c, self.h)
return y
def save_spec(self, filename):
with open(filename, 'w') as fp:
print(self.vocab_size, file=fp)
print(self.embed_size, file=fp)
print(self.hidden_size, file=fp)
@staticmethod
def load_spec(filename):
with open(filename) as fp:
vocab_size = int(next(fp))
embed_size = int(next(fp))
hidden_size = int(next(fp))
return EncoderDecoder(vocab_size, embed_size, hidden_size)