Exemple #1
0
    def layer_norm(self, inputs, epsilon=1e-8, scope='layer_norm'):
        shape = inputs.get_shape().as_lsit()[-1:]

        mean, var = tf.nn.moments(inputs, axes=-1, keep_dims=True)

        gamma = tf.Variable(tf.ones(shape))
        beta = tf.Variabel(tf.zeros(shape))

        normlized = (inputs - mean) / (var + epsilon)**0.5

        outputs = gamma * normlized + beta

        return outputs
Exemple #2
0
    def build(self):
        #Step1
        #placeholder를 define한다. placeholder는 사용할 데이터들이 들어갈 자리(entries to computational graph)이다.
        self.sequence_lengths = tf.placeholder(
            tf.int32, shape=[None], name="sequence_lengths"
        )  #sequence_length는 sequence labeling을 위한 sequence의 길이를 의미한다.
        self.labels = tf.placeholder(
            tf.int32, shape=[None, None], name="labels"
        )  #labels는 입력받은 sequence에 해당되는  label을 의미한다. sequence labeling의 결과가 들어간다.
        self.dropout = tf.placeholder(
            dtype=tf.float32, shape=[],
            name="dropout")  #dropout은 hidden units을 줄이기 위해 사용된다.
        #reduces complex co-adaptations of neurons, learns robust features in conjunction with many different subsets of other neurons, and avoids overfitting.
        self.lr = tf.placeholder(
            dtype=tf.float32, shape=[],
            name="lr")  #lr은 learning rate의 약자이다. train할 때 이용한다.
        self.word_ids = tf.placeholder(
            tf.int32, shape=[None, None], name="word_ids"
        )  #word id는 word embedding에서 사용 된다. 즉, sequence labeling을 하는데 필요한 요소이다.

        #Step2
        with tf.variable_scope("words"):

            if self.config.use_pretrained is False:  #미리 학습된 embedding이 없는 경우
                print("Randomly initializing word vectors"
                      )  #random하게 initialize한다.
                _word_embeddings = tf.get_variable(  #embedding 정보를 저장하는tensor에 random하게 get
                    name="_word_embeddings",
                    dtype=tf.float32,
                    shape=[self.config.nwords, self.config.dim_word])

            else:  #미리 학습된 embedding이 있는 경우, 이를 load한다.
                print("Using pre-trained word vectors : " +
                      sewlf.config.filename_embedding)
                _word_embeddings = tf.Variabel(  #embedding 정보를 저장하는 tensor에 미리 학습된 self.config.embeddings를 get
                    self.config.embeddings,
                    name="_word_embeddings",
                    dtype=tf.float32)

            word_embeddings = tf.nn.embedding_lookup(
                _word_embeddings,  #embedding은 tensorflow library를 사용하여 생성
                self.word_ids,
                name="word_embeddings")
        self.word_embeddings = word_embeddings  #생성된 embedding은 self.word_embeddings에 저장

        #Step3
        #모델을 생성한다. 모델은 Bi-drectional LSTM이다.
        cell_fw = tf.contrib.rnn.LSTMCell(
            self.config.hidden_size_lstm)  #foward LSTM cell을 생성
        cell_bw = tf.contrib.rnn.LSTMCell(
            self.config.hidden_size_lstm)  #backward LSTM cell을 생성
        (
            output_fw, output_bw
        ), _ = tf.nn.bidirectional_dynamic_rnn(  #tensorflow 내장 함수를 통해 LSTM cell에서 결과를 받아온다. 각 output에 저장.
            cell_fw,
            cell_bw,
            self.
            word_embeddings,  #tf.nn.bidirectional_dynamic_rnn에 넣어줄 인자는 두 LSTM cell과 word_embeddings, sequence_lengths이다.
            sequence_length=self.sequence_lengths,
            dtype=tf.float32)

        output = tf.concat([output_fw, output_bw], axis=-1)  #각 output을 연결
        output = tf.nn.dropout(
            output, self.dropout)  #dropout을 통해 hidden 수를 줄인다. (optional)

        nsteps = tf.shape(
            output
        )[1]  #output 값의 1-D integer tensor representing the shape의 두번째 값을 nsteps에 저장해 놓는다.

        #Step4
        #출력 레이어를 정의한다. 최종 예측 값은 output*W + b이다.
        output = tf.reshape(
            output,
            [-1, 2 * self.config.hidden_size_lstm
             ])  #output 값을 reshape해준다. 두 LSTM cell 값 취하므로 2*hidden_size_lstm
        W = tf.get_variable(
            "W",
            dtype=tf.
            float32,  #weight 값을 얻어온다. shape는 2*hidden_size_lstm by self.config.ntags 이다.(pred-예측값 계산을 위한 shape)
            shape=[2 * self.config.hidden_size_lstm, self.config.ntags])
        b = tf.get_variable(
            "b",
            dtype=tf.
            float32,  #bias 값을 얻어 온다. shape는 slef.config.ntags. 참고로 self.config.ntags는 tag의 개수(len(self.vocab_tags))
            shape=[self.config.ntags],
            initializer=tf.zeros_initializer())
        pred = tf.matmul(
            output,
            W) + b  #위에 정의된 output, weight, bias를 계산하여 최종 예측 값 pred를 계산한다.

        self.logits = tf.reshape(pred,
                                 [-1, nsteps, self.config.ntags
                                  ])  #그리고 pred값을 reshape하여 self.logits에 저장한다.

        #Step5
        #Loss를 계산한다. 예측값과 정답값을 cross entropy를 이용하여 loss를 구한다.
        losses = tf.nn.sparse_softmax_cross_entropy_with_logits(  #tensorflow library의 내장 함수를 이용한다.
            logits=self.logits,
            labels=self.labels)  #앞서 저장한 pred값(logits)를 파라미터로 갖는다.
        self.loss = tf.reduce_mean(
            losses)  #구한 loss의 reduce mean값을 self.loss에 저장한다.
        self.labels_pred = tf.cast(tf.argmax(self.logits, axis=-1),
                                   tf.int32)  #위를 바탕으로 label의 prediction을 구한다.

        #Step6
        #사용할 Optimizer를 정하고 Session을 초기화 및 run한다.
        optimizer = tf.train.AdamOptimizer(
            self.lr
        )  #Adam Optimizer를 사용한다. Adam은 Stochastic Gradient Descent의 변형 버전 중 하나이다. (미리 세팅된 learning rate 사용)
        self.train_op = optimizer.minimize(self.loss)  #loss를 최소화하는 방향으로 학습 진행
        self.sess = tf.Session()  #Session을 초기화하고
        self.sess.run(tf.global_variables_initializer())  #그 Session을 run한다.
        self.saver = tf.train.Saver(
        )  #to save and restore variables to and from checkpoints
Exemple #3
0
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variabel(initial)
Exemple #4
0
def bias_variable(shape):
    return tf.Variabel(tf.constant(0.1, shape=shape))
Exemple #5
0
def bias_variable(val, shape):
    return tf.Variabel(tf.constant(val, shape=shape))
Exemple #6
0
          [1, 7, 7, 7]]
y_data = [[0, 0, 1],
          [0, 0, 1],
          [0, 0, 1],
          [0, 1, 0],
          [0, 1, 0],
          [0, 1, 0],
          [1, 0, 0],
          [1, 0, 0]]

nb_classes = 3
X = tf.placeholder('float', [None, 4])
Y = tf.placeholder('float', [None, nb_classes])

W = tf.Variable(tf.random_normal([4, nb_classes]), name='weight')
b = tf.Variabel(tf.random_normal([nb_classes]), name='bias')

hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1)) # result is not 1 dimension, [[1], [2], ...]
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for step in range(2001):
        sess.run(optimizer, feed_dict={X: x_data, Y: y_data})
        if step % 200 == 0:
            print(step, sess.run(cost, feed_dict=={X: x_data, Y: y_data}))
    
    print('--------------')