영화 감상 텍스트 분석 - 전처리

Gongsam·2023년 10월 24일
0

딥러닝

목록 보기
3/4

필요한 라이브러리 확인

from konlpy.tag import Mecab
from gensim.models.keyedvectors import Word2VecKeyedVectors
from gensim.models import KeyedVectors, Word2Vec
  1. Mecab: 형태소 분석기. 형태소를 분해해줌
  2. Word2VecKeyedVectors
  3. KeyedVectors: 워드 벡터와 조회 토큰 혹은 정수로 키가 지정된 벡터 세트를 구현함. 조회 키와 벡터 사이 매핑 {str => 1D numpy array} RAM을 적게 쓴다.

    Since trained word vectors are independent from the way they were trained (Word2Vec, FastText etc), they can be represented by a standalone structure, as implemented in this module.
    출처 => 이해안됨

  4. Word2Vec

데이터 로더 구성: Word2Vec을 활용하지 않음

데이터 중복, 결측치 제거 => 한국어 토크나이저로 변환 => Counter을 사용하기 위해 잠시 변환
=> 텍스트 스트링을 사전 인덱스 스트링으로 변환

  • 한국어 토크나이저로 변환
  # train data를 한국어 토크나이저로 토큰화
    X_train = []
    for sentence in train_data['document']:
        temp_X = tokenizer.morphs(sentence) # 토큰화 
        temp_X = [word for word in temp_X if not word in stopwords] #불용어 제거
        X_train.append(temp_X)
  • morphs: 형태소를 알아내기 위한 함수

Counter 사용 위한 처리

    words = np.concatenate(X_train).tolist() #2차원 배열을 1차원 list로 변환
    counter = Counter(words)
    counter = counter.most_common(10000-4)
    vocab = ['<PAD>', '<BOS>', '<UNK>','<UNUSED>'] + [key for key, _ in counter]
    word_to_index = {word:index for index, word in enumerate(vocab)}
  • most_common: 최빈값 구하기, 9996번째 최빈값까지 구함
    • 4 빼는 이유: '<PAD>', '<BOS>', '<UNK>','<UNUSED>'와 같은 Dummy Token을 추가 해 10000개를 맞추기 위함
      • PAD:문장의 길이를 맞추기 위해서 넣음
      • BOS: 문장 시작을 나타냄, 모든 문장의 시작은 BOS
      • UNK: out of vocabulary, vocab에 저장되지 않은 토큰을 처리하기 위함
# 텍스트 스트링을 사전 인덱스 스트링으로 변환
  def wordlist_to_indexlist(wordlist):
  return [word_to_index[word] if word in word_to_index else word_to_index['<UNK>'] for word in wordlist]
  • 단어가 사전 안에 있으면 그 단어에 해당하는 키로 변경, 단어가 없다면 UNK에 해당하는 키로 변경

문장 길이의 분포 확인 후 적절한 길이로 전처리

# 분포에 따라 최대 길이를 40으로 지정
# padding = pre로 지정
X_train = tf.keras.preprocessing.sequence.pad_sequences(X_train,
                                                        value=word_to_index["<PAD>"],
                                                        padding='pre',
                                                        maxlen=max_len)

X_test = tf.keras.preprocessing.sequence.pad_sequences(X_test,
                                                       value=word_to_index["<PAD>"],
                                                       padding='pre',
                                                       maxlen=max_len)
  • 길이를 맞추기 위해 0을 앞쪽에 넣어준다.

Word2Vec 활용

word2vec_path = os.getenv('HOME') + '/aiffel/sentiment_classification/ko.bin'
word2vec = Word2Vec.load(word2vec_path)
  
vocab_size = 10000    
word_vector_dim = 200  
embedding_matrix = np.random.rand(vocab_size, word_vector_dim)

# embedding_matrix에 Word2Vec 워드 벡터를 단어 하나씩마다 차례차례 카피한다.
for i in range(4,vocab_size):
    if index_to_word[i] in word2vec:
        embedding_matrix[i] = word2vec[index_to_word[i]]

참고

한국어 자연어 처리 1편

profile
🐬 파이썬 / 인공지능 / 머신러닝

0개의 댓글