앞서 기본 lstm 모델을 바탕으로 텍스트 리뷰 기반 딥러닝 모델을 만들어보았다.
해당 모델에서는 Attention 알고리즘 적용하여 에포크를 100번 돌았을 경우에 좋은 성능을 보임을 알 수 있었다.
추가로 같은 방식으로 sentiment 예측 모델도 생성할 수 있었다.
해당 과제를 수행하면서
textblob라는 라이브러리도 알게 되었다.
# 감성 분석을 위한 함수
def get_sentiment(text):
return TextBlob(text).sentiment.polarity
# textblob 적용된 sentiment_label
# 전처리 진행된 content_c 컬럼
negative_content = df[df['sentiment_label'] == 'negative']['content_c']
# 데이터 시각화
from wordcloud import WordCloud, STOPWORDS
stopwords = set(STOPWORDS)
stopwords.update(['use', 'account', 'now', 'netflix', 'movie', 'show', 'time', 'app', 'series', 'phone', 'movies', 'watch', 'shows', 'update', 'video', 'say', 'one', 'please', 'will', 'im']) # 리뷰에서 필요없는 단어는 여기 안에 추가하셔도 좋습니다.
negative_content = df[df['sentiment_label'] == 'negative']['content_c']
negative_reviews=" ".join(content for content in negative_content)
wordcloud = WordCloud(width=800, height=400, background_color='white', stopwords=stopwords).generate(negative_reviews)
plt.figure(figsize=(12,6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Negative Reviews Word Cloud')
plt.show()
그렇다면 이렇게 좋은 성능을 가진 모델을 만들었다면 모델을 저장하는 방법은 없을까??
1. 단어집 저장 (pickle.dump)
import pickle
# Vocab을 저장할 파일 경로
vocab_path = "vocab.pkl"
with open(vocab_path, "wb") as f:
# String to Index
pickle.dump(vocab.get_stoi(), f) # stoi 사전 저장
2. 모댈 저장 (torch.save)
save_path = "lstm_sentiment_model_vocab.pth"
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
'vocab_path': vocab_path # 저장한 vocab 경로 포함
}, save_path)
3. 저장된 모델 불러오기
from torchtext.vocab import Vocab
# 저장된 단어집 가져오기
with open("data/vocab.pkl", "rb") as f:
stoi = pickle.load(f)
vocab = Vocab(stoi)
tokenizer = get_tokenizer('basic_english')
def text_pipeline(text):
return [vocab[token] for token in tokenizer(text)]
def label_pipeline(label):
return int(label)
# 하이퍼파라미터 수정
VOCAB_SIZE = len(vocab)
EMBED_DIM = 64
HIDDEN_DIM = 128
OUTPUT_DIM = 3
NUM_EPOCHS = 100
LABEL_SMOOTHING = 0.05
model_in_path = LSTMModel.LSTMModel(VOCAB_SIZE, EMBED_DIM, HIDDEN_DIM, OUTPUT_DIM)
save_path = "lstm_sentiment_model_vocab.pth"
checkpoint = torch.load(save_path)
model_in_path.load_state_dict(checkpoint['model_state_dict'])
# 예측 함수(예시)
def predict_review(model, review):
model.eval()
with torch.no_grad():
tensor_review = torch.tensor(text_pipeline(review), dtype=torch.long).unsqueeze(0)
output = model(tensor_review)
prediction =output.argmax(dim=1).item()
return prediction
# 새로운 리뷰에 대한 예측
new_review = "This app is good but there are some critical bugs"
predicted_score = predict_review(model_in_path, new_review)
print(f'Predicted Score: {predicted_score}')
-> 주피터 노트북의 커널의 단점을 보완할 때 요긴하게 써먹을 수 있을 듯 하다
# 모듈을 동적으로 불러오는 함수
def load_module_from_path(path):
module_name = os.path.splitext(os.path.basename(path))[0]
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# 파일 경로 설정
preProcessing_path = "preProcessing/sentiment.py"
attention_path = "model_class/Attention.py"
lstm_path = "model_class/LSTMModel.py"
# 각 파일 모듈 불러오기
preProcessing = load_module_from_path(preProcessing_path)
Attention = load_module_from_path(attention_path)
LSTMModel = load_module_from_path(lstm_path)
회고