Keras

LSTM을 이용해 로이터 뉴스 카테고리 분석하기

이부일 2018. 1. 10. 17:02

# 패키지 불러오기

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

from keras.datasets import reuters
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, LSTM, Embedding
from keras.preprocessing import sequence



# seed 값 설정
seed = 0
np.random.seed(seed)
tf.set_random_seed(seed)



# 학습 데이터와 테스트 데이터로 나누기
(x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=1000, test_split=0.2)



# 데이터 확인하기
category = np.max(y_train) + 1
print(category, "카테고리")
print(len(x_train), "학습용 뉴스 기사")
print(len(x_test), "테스트용 뉴스 기사")
print(len(x_test[0]))

자동 대체 텍스트를 사용할 수 없습니다.


# 데이터 전처리
x_train = sequence.pad_sequences(x_train, maxlen=100)
x_test = sequence.pad_sequences(x_test, maxlen=100)
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)



# 모델의 설정
model = Sequential()
model.add(Embedding(1000, 100))
model.add(LSTM(100, activation="tanh"))
model.add(Dense(46, activation="softmax"))



# 모델 학습과정 설정하기
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])



# 모델 학습하기
history = model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=20, batch_size=100, verbose=1)



# 모델 평가하기
print("\n Test Accuracy : %.4f" % (model.evaluate(x_test, y_test)[1]))

이미지: 텍스트


# 그래프 작성하기
y_train_loss = history.history["loss"]
y_val_loss = history.history["val_loss"]
x_len = np.arange(len(y_test_loss))
plt.plot(x_len, y_train_loss, marker=".", color="blue", label="Train_Loss")
plt.plot(x_len, y_val_loss, marker=".", color="red", label="Test_Loss")
plt.legend(loc="upper right")
plt.grid()
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()

자동 대체 텍스트를 사용할 수 없습니다.


[출처] 모두의 딥러닝, 조태호 지음, 길벗, p234~246