-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmodel.py
49 lines (35 loc) · 1.34 KB
/
model.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
47
48
49
import tensorflow as tf
from keras import layers
import keras
class EmbeddingLayer(layers.Layer):
def __init__(self, units, input_dim):
super(EmbeddingLayer, self).__init__()
self.input_dim = input_dim
w_init = tf.random_normal_initializer()
self.w = tf.Variable(initial_value=w_init(shape=(input_dim, units),
dtype= 'float32'),
trainable=True,
name="emb")
def call(self, inputs):
embedding = tf.matmul(inputs, self.w)
return embedding
class ScoringLayer(layers.Layer):
def __init__(self, units, input_dim):
super(ScoringLayer, self).__init__()
w_init = tf.random_normal_initializer()
self.w = tf.Variable(initial_value=w_init(shape=(input_dim, units),
dtype='float32'),
trainable=True)
def call(self, inputs):
output = tf.matmul(inputs, self.w)
softmax = tf.nn.softmax(output, axis=-1)
return softmax
class Word2Vec(keras.Model):
def __init__(self, units, input_dim):
super(Word2Vec, self).__init__()
self.embedding = EmbeddingLayer(units, input_dim)
self.scoring = ScoringLayer(input_dim,units)
def call(self, inputs):
embedding = self.embedding(inputs)
output = self.scoring(embedding)
return outputs