RNN_test_Model / test.py
OneclickAI's picture
Upload 4 files
9a24bb1 verified
import tensorflow as tf
from tensorflow import keras
import numpy as np
# --- 1. 모델과 단어 사전 로드 ---
# 저장된 Keras 모델 불러오기
model_path = "my_rnn_model_imdb.keras"
try:
loaded_model = keras.models.load_model(model_path)
print(f"'{model_path}' 모델을 성공적으로 불러왔습니다.")
except Exception as e:
print(f"모델 로딩 중 오류 발생: {e}")
exit()
# IMDB 데이터셋의 단어-인덱스 사전 로드
word_index = keras.datasets.imdb.get_word_index()
# Keras의 예약된 인덱스를 반영하여 3만큼 오프셋 추가
word_index = {k: (v + 3) for k, v in word_index.items()}
word_index["<pad>"] = 0
word_index["<start>"] = 1
word_index["<unk>"] = 2 # 알려지지 않은 단어(out-of-vocabulary)
word_index["<unused>"] = 3
# --- 2. 예측을 위한 전처리 함수 ---
MAX_LEN = 256
def preprocess_text(text):
"""
새로운 텍스트를 모델 입력 형식에 맞게 전처리합니다.
"""
# 텍스트를 토큰화하고 정수로 인코딩
tokens = [word_index.get(word, 2) for word in text.lower().split()]
# <start> 인덱스 추가
tokens = [word_index["<start>"]] + tokens
# 시퀀스 패딩
padded_sequence = keras.preprocessing.sequence.pad_sequences(
[tokens], maxlen=MAX_LEN, padding='pre'
)
return padded_sequence
# --- 3. 사용자 입력 기반 예측 실행 ---
print("\n영화 리뷰 감성 분석기 (종료하려면 'exit'를 입력하세요)")
print("-" * 50)
while True:
# 사용자로부터 리뷰 입력받기
review_text = input("리뷰를 입력하세요: ")
if review_text.lower() == 'exit':
print("프로그램을 종료합니다.")
break
if not review_text.strip():
print("입력된 내용이 없습니다. 다시 시도해주세요.")
continue
# 텍스트 전처리
processed_input = preprocess_text(review_text)
# 모델로 예측 수행
prediction = loaded_model.predict(processed_input)
# 결과 해석 (sigmoid 출력 > 0.5 이면 긍정)
score = prediction[0][0]
sentiment = "긍정 (Positive)" if score > 0.5 else "부정 (Negative)"
print(f"결과: {sentiment} (예측 점수: {score:.4f})")
print("-" * 50)