PyTorch로 시퀀스 처리하기

PyTorch로 배우는 Intermediate Deep Learning

Michal Oleszak

Machine Learning Engineer

순차 데이터

  • 시간 또는 공간 순서로 정렬됨
  • 데이터 포인트의 순서에 상호 의존성이 존재
  • 순차 데이터의 예:
    • 시계열
    • 텍스트
    • 음파

컴퓨터 화면에 표시된 시계열 그래프.

펼쳐진 책.

스피커와 오디오 처리 소프트웨어가 열린 컴퓨터 화면.

PyTorch로 배우는 Intermediate Deep Learning

전력 소비량 예측

  • 목표: 과거 패턴을 기반으로 미래 전력 소비량 예측

  • 전력 소비량 데이터셋:

                 timestamp  consumption
0      2011-01-01 00:15:00    -0.704319
1      2011-01-01 00:30:00    -0.704319
...                    ...          ...
140254 2014-12-31 23:45:00    -0.095751
140255 2015-01-01 00:00:00    -0.095751
1 Trindade,Artur. (2015). ElectricityLoadDiagrams20112014. UCI Machine Learning Repository. https://doi.org/10.24432/C58C86.
PyTorch로 배우는 Intermediate Deep Learning

훈련-테스트 분할

  • 시계열에는 무작위 분할 사용 금지!
  • 미래 정보 누수: 모델이 미래 정보를 갖게 됨
  • 해결책: 시간 순서로 분할

2011~2013년 훈련 세트(파란색)와 2014년 테스트 세트(주황색)가 시각적으로 구분된 그래프.

PyTorch로 배우는 Intermediate Deep Learning

시퀀스 생성하기

  • 시퀀스 길이 = 훈련 예제 하나의 데이터 포인트 수
    • 24 × 4 = 96 -> 최근 24시간 고려
  • 다음 단일 데이터 포인트 예측

동일한 길이의 입력 시퀀스(파란색)와 타깃 값(초록색)이 시각적으로 구분된 그림.

PyTorch로 배우는 Intermediate Deep Learning

Python에서 시퀀스 생성하기

import numpy as np

def create_sequences(df, seq_length):

xs, ys = [], []
for i in range(len(df) - seq_length):
x = df.iloc[i:(i+seq_length), 1] y = df.iloc[i+seq_length, 1]
xs.append(x) ys.append(y)
return np.array(xs), np.array(ys)
  • 데이터와 시퀀스 길이를 입력으로 받음
  • 입력 및 타깃 리스트 초기화
  • 데이터 포인트 순회
  • 입력 및 타깃 정의
  • 초기화된 리스트에 추가
  • 입력과 타깃을 NumPy 배열로 반환
PyTorch로 배우는 Intermediate Deep Learning

TensorDataset

훈련 예제 생성

X_train, y_train = create_sequences(train_data, seq_length)
print(X_train.shape, y_train.shape)
(34944, 96) (34944,)

Torch Dataset으로 변환

from torch.utils.data import TensorDataset

dataset_train = TensorDataset(
    torch.from_numpy(X_train).float(),
    torch.from_numpy(y_train).float(),
)
PyTorch로 배우는 Intermediate Deep Learning

다른 순차 데이터에의 적용

동일한 기법을 다른 시퀀스에도 적용할 수 있습니다:

  • 대규모 언어 모델
  • 음성 인식
PyTorch로 배우는 Intermediate Deep Learning

연습해 봅시다!

PyTorch로 배우는 Intermediate Deep Learning

Preparing Video For Download...