Upload 3 files
Browse files- config.json +6 -0
- test.py +94 -0
- train.py +96 -0
config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
|
3 |
+
model : {},
|
4 |
+
layers : {},
|
5 |
+
|
6 |
+
}
|
test.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# test.py (오류 수정 최종 코드)
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import tensorflow as tf
|
5 |
+
from tensorflow import keras
|
6 |
+
# from_pretrained_keras 대신 hf_hub_download를 사용합니다.
|
7 |
+
from huggingface_hub import hf_hub_download
|
8 |
+
|
9 |
+
print("TensorFlow 버전:", tf.__version__)
|
10 |
+
|
11 |
+
# 1. Hugging Face Hub에서 모델 파일 다운로드 후 로드
|
12 |
+
REPO_ID = "OneclickAI/LSTM_GUE_test_Model"
|
13 |
+
print(f"\n'{REPO_ID}' 저장소에서 모델 파일의 위치를 확인합니다...")
|
14 |
+
|
15 |
+
try:
|
16 |
+
# 1단계: hf_hub_download로 파일의 로컬 캐시 경로를 가져옵니다.
|
17 |
+
# 파일이 이미 다운로드 되었다면, 다운로드를 생략하고 경로만 즉시 반환합니다.
|
18 |
+
print("LSTM 모델 경로 확인 중...")
|
19 |
+
lstm_model_path = hf_hub_download(repo_id=REPO_ID, filename="lstm_model.keras")
|
20 |
+
print(f"LSTM 모델 파일 위치: {lstm_model_path}")
|
21 |
+
|
22 |
+
print("GRU 모델 경로 확인 중...")
|
23 |
+
gru_model_path = hf_hub_download(repo_id=REPO_ID, filename="gru_model.keras")
|
24 |
+
print(f"GRU 모델 파일 위치: {gru_model_path}")
|
25 |
+
|
26 |
+
# 2단계: 다운로드된 파일 경로를 Keras의 표준 load_model 함수로 직접 로드합니다.
|
27 |
+
print("\nKeras로 모델을 로드합니다...")
|
28 |
+
lstm_model = keras.models.load_model(lstm_model_path)
|
29 |
+
gru_model = keras.models.load_model(gru_model_path)
|
30 |
+
|
31 |
+
print("모델을 성공적으로 로드했습니다.")
|
32 |
+
|
33 |
+
except Exception as e:
|
34 |
+
print(f"모델 로딩 중 오류 발생: {e}")
|
35 |
+
print("인터넷 연결 및 저장소 ID, 파일명을 확인해주세요.")
|
36 |
+
exit()
|
37 |
+
|
38 |
+
# IMDB 데이터셋의 단어 인덱스 로드 ('단어': 정수)
|
39 |
+
word_index = keras.datasets.imdb.get_word_index()
|
40 |
+
|
41 |
+
# 2. 예측할 리뷰 문장 정의
|
42 |
+
review1 = "This movie was fantastic and wonderful. I really enjoyed it."
|
43 |
+
review2 = "It was a complete waste of time. The plot was terrible and the acting was bad."
|
44 |
+
|
45 |
+
# 3. 문장 전처리 함수
|
46 |
+
def preprocess_text(text, word_index, maxlen=256):
|
47 |
+
"""
|
48 |
+
텍스트를 모델이 이해할 수 있는 정수 시퀀스로 변환하고 패딩합니다.
|
49 |
+
"""
|
50 |
+
# 문장을 소문자로 변환하고 단어 단위로 분할
|
51 |
+
tokens = text.lower().split()
|
52 |
+
|
53 |
+
# 각 단어를 정수 인덱스로 변환 (word_index에 없으면 2번 인덱스'<unk>' 사용)
|
54 |
+
token_indices = [word_index.get(word, 2) for word in tokens]
|
55 |
+
|
56 |
+
# 시퀀스 패딩
|
57 |
+
padded_sequence = keras.preprocessing.sequence.pad_sequences([token_indices], maxlen=maxlen)
|
58 |
+
|
59 |
+
return padded_sequence
|
60 |
+
|
61 |
+
# 4. 모델 예측 및 결과 출력 함수
|
62 |
+
def predict_review(review_text, model, model_name):
|
63 |
+
"""
|
64 |
+
전처리된 텍스트를 사용하여 감성 분석을 수행하고 결과를 출력합니다.
|
65 |
+
"""
|
66 |
+
# 문장 전처리
|
67 |
+
processed_review = preprocess_text(review_text, word_index)
|
68 |
+
|
69 |
+
# 예측 수행
|
70 |
+
prediction = model.predict(processed_review, verbose=0) # 예측 시 로그 출력을 끔
|
71 |
+
positive_probability = prediction[0][0] * 100
|
72 |
+
|
73 |
+
print(f"--- {model_name} 모델 예측 결과 ---")
|
74 |
+
print(f"리뷰: '{review_text}'")
|
75 |
+
print(f"긍정 확률: {positive_probability:.2f}%")
|
76 |
+
if positive_probability > 50:
|
77 |
+
print("결과: 긍정적인 리뷰입니다.")
|
78 |
+
else:
|
79 |
+
print("결과: 부정적인 리뷰입니다.")
|
80 |
+
print("-" * 30)
|
81 |
+
|
82 |
+
# 5. 각 리뷰에 대해 두 모델로 예측 수행
|
83 |
+
print("\n" + "="*40)
|
84 |
+
print("첫 번째 리뷰 예측 시작")
|
85 |
+
print("="*40)
|
86 |
+
predict_review(review1, lstm_model, "LSTM")
|
87 |
+
predict_review(review1, gru_model, "GRU")
|
88 |
+
|
89 |
+
|
90 |
+
print("\n" + "="*40)
|
91 |
+
print("두 번째 리뷰 예측 시작")
|
92 |
+
print("="*40)
|
93 |
+
predict_review(review2, lstm_model, "LSTM")
|
94 |
+
predict_review(review2, gru_model, "GRU")
|
train.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import tensorflow as tf
|
3 |
+
from tensorflow import keras
|
4 |
+
from keras import layers
|
5 |
+
|
6 |
+
print("TensorFlow 버전:", tf.__version__)
|
7 |
+
|
8 |
+
# 1. 데이터 로드 및 전처리
|
9 |
+
print("\n1. 데이터 로드 및 전처리를 시작합니다...")
|
10 |
+
# num_words=10000: 가장 빈도가 높은 1만 개의 단어만 사용
|
11 |
+
(x_train, y_train), (x_test, y_test) = keras.datasets.imdb.load_data(num_words=10000)
|
12 |
+
|
13 |
+
print(f"학습 데이터 개수: {len(x_train)}")
|
14 |
+
print(f"테스트 데이터 개수: {len(x_test)}")
|
15 |
+
|
16 |
+
# 문장의 길이를 동일하게 맞추기 위해 패딩(padding) 처리 (maxlen=256)
|
17 |
+
x_train = keras.preprocessing.sequence.pad_sequences(x_train, maxlen=256)
|
18 |
+
x_test = keras.preprocessing.sequence.pad_sequences(x_test, maxlen=256)
|
19 |
+
print("데이터 전처리가 완료되었습니다.")
|
20 |
+
|
21 |
+
# 2. LSTM 모델 생성, 학습 및 저장
|
22 |
+
print("\n2. LSTM 모델 학습을 시작합니다...")
|
23 |
+
|
24 |
+
# LSTM 모델 아키텍처 정의
|
25 |
+
lstm_model = keras.Sequential([
|
26 |
+
layers.Embedding(input_dim=10000, output_dim=128),
|
27 |
+
layers.LSTM(64),
|
28 |
+
layers.Dense(1, activation="sigmoid")
|
29 |
+
])
|
30 |
+
|
31 |
+
# 모델 컴파일
|
32 |
+
lstm_model.compile(
|
33 |
+
loss="binary_crossentropy",
|
34 |
+
optimizer="adam",
|
35 |
+
metrics=["accuracy"]
|
36 |
+
)
|
37 |
+
|
38 |
+
print("\n--- LSTM 모델 구조 ---")
|
39 |
+
lstm_model.summary()
|
40 |
+
|
41 |
+
# 모델 학습
|
42 |
+
batch_size = 128
|
43 |
+
epochs = 1 # 예제이므로 epoch를 줄여서 실행 시간을 단축합니다.
|
44 |
+
history_lstm = lstm_model.fit(
|
45 |
+
x_train, y_train,
|
46 |
+
batch_size=batch_size,
|
47 |
+
epochs=epochs,
|
48 |
+
validation_data=(x_test, y_test)
|
49 |
+
)
|
50 |
+
|
51 |
+
# 모델 평가
|
52 |
+
score_lstm = lstm_model.evaluate(x_test, y_test, verbose=0)
|
53 |
+
print(f"\nLSTM 모델 테스트 결과 -> Loss: {score_lstm[0]:.4f}, Accuracy: {score_lstm[1]:.4f}\n")
|
54 |
+
|
55 |
+
# 학습된 LSTM 모델 저장
|
56 |
+
lstm_model.save("lstm_model.keras")
|
57 |
+
print("LSTM 모델이 'lstm_model.keras' 파일로 저장되었습니다.")
|
58 |
+
|
59 |
+
|
60 |
+
# 3. GRU 모델 생성, 학습 및 저장
|
61 |
+
print("\n3. GRU 모델 학습을 시작합니다...")
|
62 |
+
|
63 |
+
# GRU 모델 아키텍처 정의
|
64 |
+
gru_model = keras.Sequential([
|
65 |
+
layers.Embedding(input_dim=10000, output_dim=128),
|
66 |
+
layers.GRU(64),
|
67 |
+
layers.Dense(1, activation="sigmoid")
|
68 |
+
])
|
69 |
+
|
70 |
+
# 모델 컴파일
|
71 |
+
gru_model.compile(
|
72 |
+
loss="binary_crossentropy",
|
73 |
+
optimizer="adam",
|
74 |
+
metrics=["accuracy"]
|
75 |
+
)
|
76 |
+
|
77 |
+
print("\n--- GRU 모델 구조 ---")
|
78 |
+
gru_model.summary()
|
79 |
+
|
80 |
+
|
81 |
+
# 모델 학습
|
82 |
+
history_gru = gru_model.fit(
|
83 |
+
x_train, y_train,
|
84 |
+
batch_size=batch_size,
|
85 |
+
epochs=epochs,
|
86 |
+
validation_data=(x_test, y_test)
|
87 |
+
)
|
88 |
+
|
89 |
+
# 모델 평가
|
90 |
+
score_gru = gru_model.evaluate(x_test, y_test, verbose=0)
|
91 |
+
print(f"\nGRU 모델 테스트 결과 -> Loss: {score_gru[0]:.4f}, Accuracy: {score_gru[1]:.4f}")
|
92 |
+
|
93 |
+
|
94 |
+
# 학습된 GRU 모델 저장
|
95 |
+
gru_model.save("gru_model.keras")
|
96 |
+
print("GRU 모델이 'gru_model.keras' 파일로 저장되었습니다.")
|