| |
| |
| |
| |
| |
| import tensorflow as tf |
| import numpy as np |
| tf.set_random_seed(777) |
| from keras.utils import np_utils |
| import matplotlib.pyplot as plt |
| |
| |
| tf.reset_default_graph() |
| |
| tf.set_random_seed(1) |
| |
| |
| |
| raw_data = 'First Citizen' |
| n_samples = len(raw_data) |
| print("전체 문자 수 : ", n_samples) |
| unique_chars = list(set(raw_data)); |
| print("고유한 문자 수 : ", len(unique_chars)) |
| |
| char_to_int = { ch:i for i,ch in enumerate(unique_chars) } |
| |
| int_to_char = { i:ch for i,ch in enumerate(unique_chars) } |
| |
| n_unique_chars = len(unique_chars) |
| |
| input_dim = n_unique_chars |
| |
| num_classes = n_unique_chars |
| |
| seq_len = n_samples-1 |
| |
| |
| |
| |
| |
| |
| |
| batch_size = 1 |
| hidden_size = 16 |
| learning_rate = 0.1 |
| nepochs = 20 |
| |
| x = raw_data[:-1] |
| print("x : ", x) |
| |
| y = raw_data[1:] |
| print("y : ", y) |
| |
| x_one_hot = np_utils.to_categorical(x_int, |
| n_unique_chars).reshape(batch_size,seq_len, input_dim) |
| print("x_one_hot : ", x_one_hot) |
| |
| |
| X = tf.placeholder(tf.float32, [None, seq_len, input_dim]) |
| |
| Y = tf.placeholder(tf.int32, [None, seq_len]) |
| |
| cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_size) |
| |
| initial_state = cell.zero_state(batch_size, tf.float32) |
| |
| |
| outputs,_states = tf.nn.dynamic_rnn(cell, X, initial_state=initial_state, |
| dtype = tf. float32) |
| |
| |
| |
| outputs = tf.contrib.layers.fully_connected(inputs = outputs, num_outputs = num_classes, |
| activation_fn = None) |
| |
| outputs = tf.reshape(outputs, [batch_size, seq_len, num_classes]) |
| |
| |
| |
| |
| weight = tf.ones([batch_size, seq_len]) |
| |
| sequence_loss = tf.contrib.seq2seq.sequence_loss(logits = outputs, |
| targets = Y, weights = weight) |
| |
| loss = tf.reduce_mean(sequence_loss) |
| |
| |
| optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) |
| |
| |
| prediction = tf.argmax(outputs, axis=2) |
| |
| |
| |
| losses = [] |
| with tf.Session() as sess: |
| sess.run(tf.global_variables_initializer()) |
| for epoch in range(nepochs): |
| l, _ = sess.run([loss, optimizer], feed_dict = {X: x_one_hot, Y: y_int}) |
| result = sess.run(prediction, feed_dict = {X: x_one_hot}) |
| print('epoch = {}, loss = {}' .format(epoch, l)) |
| losses.append(l) |
| |
| result_str = [int_to_char[k] for k in result[0]] |
| print("predicted : {}" .format(''.join(result_str))) |