케라스 모델 구현하기
이것은 케라스 모델을 만들어 저장하는 코드이다.
추가적으로 모델의 accuracy와 loss를 그래프로 출력해준다.
책에는 안나와있는데, 중요한 것은 이 모델을 활용하려면
Tokenizer로 분석한 tokenizer을 파일로 저장해주고,
모델을 사용할 때 불러와줘야 한다는 것이다.
그렇지 않으면 모델로 사용할 때 예측을 하고픈 문장으로
토크나이징이 되기 때문에 학습의 결과가 아무 의미가 없다.
이렇게 두개의 파일로 나눠준 이유는 예측 할때마다 학습을 해서는 의미가 없기 때문.
texts = []
labels = []
f1 = open("/home/shkim/Desktop/cuss_dat/train/cussdata.txt", 'r')
f2 = open("/home/shkim/Desktop/cuss_dat/train/cusslabel.txt", 'r')
while True:
textline = f1.readline()
labelline = f2.readline()
if not textline: break
texts.append(textline[:-1])
labels.append(int(labelline[:-1]))
f1.close()
f2.close()
from khaiii import KhaiiiApi
api = KhaiiiApi()
morpheme = []
for text in texts:
union = ""
for word in api.analyze(text):
for x in word.morphs:
if x.tag not in ['SF', 'SP', 'SS', 'SE', 'SO', 'SL', 'SH', 'SW', 'SN', 'ZN', 'ZV', 'ZZ']:
union += x.lex
union += " "
morpheme.append(union)
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
import numpy as np
maxlen = 20
max_words = 10000
tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(morpheme)
sequences = tokenizer.texts_to_sequences(morpheme)
word_index = tokenizer.word_index
print('%s개의 고유한 토큰을 찾았습니다.' % len(word_index))
# word_index 저장
import json
json = json.dumps(word_index)
f3 = open("wordIndex.json", "w")
f3.write(json)
f3.close()
data = pad_sequences(sequences, maxlen=maxlen)
labels = np.asarray(labels)
print('데이터 텐서의 크기:', data.shape)
print('레이블 텐서의 크기:', labels.shape)
indices = np.arange(data.shape[0])
np.random.shuffle(indices)
x_train = data[indices]
y_train = labels[indices]
from keras.models import Sequential
from keras.layers import Flatten, Dense, Embedding
model = Sequential()
model.add(Embedding(10000, 8, input_length=maxlen))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc'])
model.summary()
history = model.fit(x_train, y_train,
epochs=10,
batch_size=32,
validation_split=0.2)
from keras.models import load_model
model.save('model.h5')
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
아래의 코드는 이 모델을 활용하기 위한 코드이다.
from khaiii import KhaiiiApi
api = KhaiiiApi()
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
maxlen = 20
max_words = 10000
tokenizer = Tokenizer(num_words=max_words)
import json
with open('wordIndex.json') as json_file:
word_index = json.load(json_file)
tokenizer.word_index = word_index
from keras.models import load_model
model = load_model('191125_model.h5')
examples = ['여기에', '예시를', '적으면', '됩니다']
ex_morpheme = []
for text in examples:
union = ""
for word in api.analyze(text):
for x in word.morphs:
if x.tag not in ['SF', 'SP', 'SS', 'SE', 'SO', 'SL', 'SH', 'SW', 'SN', 'ZN', 'ZV', 'ZZ']:
union += x.lex
union += " "
ex_morpheme.append(union)
sequences = tokenizer.texts_to_sequences(ex_morpheme)
x_test = pad_sequences(sequences, maxlen=maxlen)
value_predicted = model.predict(x_test)
print(value_predicted)