반응형
코세라의 deeplearning.AI tensorflow developer 전문가 자격증 과정내에 Natural Language Processing in TensorFlow
과정의 4주차 sequence models and literature챕터의 코드 예제입니다.
laurence to poetry
한 문학의 문장들을 학습시킨 모델을 이용해서, 첫 몇 단어를 seed로 모델에 주면, 이후 단어들을 예측해서 문장들을 자동으로 써나가는 코드이다.
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
import numpy as np
!wget --no-check-certificate \
https://storage.googleapis.com/laurencemoroney-blog.appspot.com/irish-lyrics-eof.txt \
-O /tmp/irish-lyrics-eof.txt
tokenizer = Tokenizer()
data = open('/tmp/irish-lyrics-eof.txt').read()
corpus = data.lower().split("\n")
tokenizer.fit_on_texts(corpus)
total_words = len(tokenizer.word_index) + 1
print(tokenizer.word_index)
print(total_words)
input_sequences = []
for line in corpus:
token_list = tokenizer.texts_to_sequences([line])[0]
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
input_sequences.append(n_gram_sequence)
# pad sequences
max_sequence_len = max([len(x) for x in input_sequences])
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))
# create predictors and label
xs, labels = input_sequences[:,:-1],input_sequences[:,-1]
ys = tf.keras.utils.to_categorical(labels, num_classes=total_words)
print(tokenizer.word_index['in'])
print(tokenizer.word_index['the'])
print(tokenizer.word_index['town'])
print(tokenizer.word_index['of'])
print(tokenizer.word_index['athy'])
print(tokenizer.word_index['one'])
print(tokenizer.word_index['jeremy'])
print(tokenizer.word_index['lanigan'])
print(xs[6])
print(ys[6])
print(xs[5])
print(ys[5])
print(tokenizer.word_index)
model = Sequential()
model.add(Embedding(total_words, 100, input_length=max_sequence_len-1))
model.add(Bidirectional(LSTM(150)))
model.add(Dense(total_words, activation='softmax'))
adam = Adam(lr=0.01)
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
#earlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=0, mode='auto')
history = model.fit(xs, ys, epochs=100, verbose=1)
#print model.summary()
print(model)
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.show()
plot_graphs(history, 'accuracy')
seed_text = "I've got a bad feeling about this"
next_words = 100
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
print(seed_text)
|
cs |
generating text using a character-based RNN 예시 참고 :
www.tensorflow.org/tutorials/text/text_generation
반응형
'AI & 머신러닝 coding skill' 카테고리의 다른 글
[SEQUENCES, TIME SERIES AND PREDICTION] RNN, LSTM for time series (0) | 2020.11.11 |
---|---|
[SEQUENCES, TIME SERIES AND PREDICTION] Deep neural network for time series 예측 (0) | 2020.11.11 |
[SEQUENCES, TIME SERIES AND PREDICTION] Preparing features and labels (0) | 2020.11.11 |
[SEQUENCES, TIME SERIES AND PREDICTION] Sequences and Prediction (0) | 2020.11.11 |
[NATURAL LANGUAGE PROCESSING IN TENSORFLOW] Sequence models (0) | 2020.11.11 |
[NATURAL LANGUAGE PROCESSING IN TENSORFLOW] subwords text encoder (0) | 2020.11.11 |
training data in tensorflow site (0) | 2020.11.11 |
[NATURAL LANGUAGE PROCESSING IN TENSORFLOW] Word embeddings (0) | 2020.11.11 |