[NLP] 텍스트 전처리 - (7) 패딩(Padding)

김규리·2022년 6월 21일
0

NLP

목록 보기
7/33
post-thumbnail

패딩(Padding)

병렬 연산을 위해서 여러 문장의 길이를 임의로 동일하게 맞춰주는 작업
데이터에 특정 값을 채워서 데이터의 크기(shape)를 조정하는 것
*숫자 0을 사용하고 있다면 제로 패딩(zero padding)이라고 함

1. Numpy로 패딩하기

import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer

# 텍스트 데이터 단어 집합
preprocessed_sentences = [['barber', 'person'], ['barber', 'good', 'person'], ['barber', 'huge', 'person'], ['knew', 'secret'], ['secret', 'kept', 'huge', 'secret'], ['huge', 'secret'], ['barber', 'kept', 'word'], ['barber', 'kept', 'word'], ['barber', 'kept', 'secret'], ['keeping', 'keeping', 'huge', 'secret', 'driving', 'barber', 'crazy'], ['barber', 'went', 'huge', 'mountain']]

# 정수 인코딩
tokenizer = Tokenizer()
tokenizer.fit_on_texts(preprocessed_sentences)
encoded = tokenizer.texts_to_sequences(preprocessed_sentences)

# 가장 길이가 긴 문장의 길이 구하기
max_len = max(len(item) for item in encoded)

# 모든 문장의 길이를 max_len으로 맞추기
for sentence in encoded:
    while len(sentence) < max_len:
        sentence.append(0)

padded_np = np.array(encoded)
padded_np
array([[ 1,  5,  0,  0,  0,  0,  0],
       [ 1,  8,  5,  0,  0,  0,  0],
       [ 1,  3,  5,  0,  0,  0,  0],
       [ 9,  2,  0,  0,  0,  0,  0],
       [ 2,  4,  3,  2,  0,  0,  0],
       [ 3,  2,  0,  0,  0,  0,  0],
       [ 1,  4,  6,  0,  0,  0,  0],
       [ 1,  4,  6,  0,  0,  0,  0],
       [ 1,  4,  2,  0,  0,  0,  0],
       [ 7,  7,  3,  2, 10,  1, 11],
       [ 1, 12,  3, 13,  0,  0,  0]])

2. 케라스 전처리 도구로 패딩하기

  • pad_sequences(): 문서의 앞에 0으로 채움
from tensorflow.keras.preprocessing.sequence import pad_sequences

padded = pad_sequences(encoded)

# 문서의 뒤에 0을 채우고 싶다면, padding='post'
padded = pad_sequences(encoded, padding='post')

# 길이에 제한을 두고 싶다면, maxlen의 인자 활용
# 기존에 5보다 길었던 데이터 -> 앞의 단어 삭제
# 뒤의 단어가 삭제되도록 하고 싶다면, truncating 인자 활용
padded = pad_sequences(encoded, padding='post', maxlen=5)
padded = pad_sequences(encoded, padding='post', truncating='post', maxlen=5)

# 0이 아닌 다른 숫자로 패딩하고 싶다면, value 인자 활용
padded = pad_sequences(encoded, padding='post', value=last_value)
profile
connecting the dots

0개의 댓글