본문 바로가기
딥러닝 with Python

[딥러닝 with Python] 시계열 데이터 분석을 위한 tsai 라이브러리 활용하기: tsai.data.core

by CodeCrafter 2025. 7. 20.
반응형

 

오늘은 시계열 데이터 분석을 위한 파이썬 라이브러리 중 하나인 tsai의 핵심 모듈 중 하나인

 

data.core

 

에 대해 알아보겠습니다. 

 

코드 실습을 통해서 알아보겠으며, Google의 Colab 환경에서 tsai를 활용해 시계열 데이터를 효율적으로 다루는 방법을 알아보겠습니다.

 

1. tsai 라이브러리의 data.core 실습하기

1) 먼저 colab 환경에서 tsai 라이브러리를 설치하고, 예제 데이터를 불러오는 것부터 시작하겠습니다. 

tsai는 UCR 시계열 데이터셋과 같은 다양한 외부 데이터를 쉽게 다운로드하고 사용할 수 있는 기능을 제공하는데요.

 

tsai 라이브러리는 다운로드 받을 때 시간이 좀 걸리므로, 한번 드라이브내에 받아놓으면 좋을 것 같습니다. 

 

먼저 드라이브를 연동해줍니다.

from google.colab import drive
drive.mount('/content/drive')

 

 

그리고나서, 드라이브에 tsai라는 폴더를 만들고 해당 폴더로 direction을 이동 시킨뒤 tsai git hub에서 폴더들을 clone 해옵니다.

import os
import sys

target_dir = '/content/drive/MyDrive/tsai'

if not os.path.exists(target_dir):
    os.makedirs(target_dir)

%cd {target_dir}

if not os.path.exists(os.path.join(target_dir, '.git')):
    !git clone https://github.com/timeseriesAI/tsai.git .

tsai_library_root = target_dir
if tsai_library_root not in sys.path:
    sys.path.append(tsai_library_root)

 

그리고 다운로드 된 모듈들을 import하기 위해서, 해당 경로에서 모듈들을 찾을 수 있도록 sys.path에 추가해줍니다.


# Python이 해당 경로에서 모듈을 찾을 수 있도록 sys.path에 추가합니다.
import sys
tsai_path = '/content/drive/MyDrive/tsai'
if tsai_path not in sys.path:
    sys.path.append(tsai_path)

 

이제 필요한 오늘 실습에 필요한 라이브러리들을 임포트 해줍니다.

# 필요한 라이브러리 임포트
from tsai.data.external import get_UCR_data
from tsai.data.core import *
import numpy as np
import torch
import matplotlib.pyplot as plt
from tsai.data.preprocessing import cat2int
from fastcore.all import *

 

 

이제 예제 데이터셋 중 하나인 OliveOil을 사용해 데이터를 불러오겠습니다. get_UCR_data 함수는 훈련(train) 및 검증(validation) 데이터와 레이블을 쉽게 가져올 수 있도록 해줍니다.

 

# 'OliveOil' 데이터셋 불러오기
dsid = 'OliveOil'
X_train, y_train, X_valid, y_valid = get_UCR_data(dsid, on_disk=True, force_download=True)

# 데이터 형태 확인
print(f"X_train shape: {X_train.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"X_valid shape: {X_valid.shape}")
print(f"y_valid shape: {y_valid.shape}")

# 레이블을 정수형으로 변환 (필요시)
y_tensor = cat2int(y_train) # cat2int 함수는 tsai.data.core에 포함
print(f"y_tensor (converted) sample: {y_tensor[:5]}")

 

데이터가 잘 불러와줬으며, categorical한 레이블을 정수형으로 변환도 cat2int로 쉽게 변환가능합니다.

 

 

2) NumpyTesnor와 TSTensor: tsai의 독특한 텐서 타입

tsai는 Pytorch 텐서를 기반으로 하지만, 시계열 데이터에 특화된 NumpyTensor와 TSTensor라는 커스텀 텐서 클래스를 제공해줍니다. 

이들은 Numpy 배열이나 PyTorch 텐서를 입력으로 받아 tsai 내부에서 더 효율적으로 처리될 수 있도록 도와주는데요. 

특히, TSTnersor는 show 메소드를 통해 시계열 데이터를 쉽게 시각화할 수 있는 기능까지 포함하고 있습니다.

# Numpy 배열을 TSTensor로 변환
a = np.random.randn(2, 3, 4).astype(np.float32)
ts_a = TSTensor(a)
print(f"Original numpy array type: {type(a)}")
print(f"TSTensor type: {type(ts_a)}")
print(f"TSTensor data type: {type(ts_a.data)}") # 내부적으로 PyTorch Tensor

# PyTorch 텐서를 TSTensor로 변환
t = torch.rand(2, 3, 4).float()
ts_t = TSTensor(t)
print(f"Original torch tensor type: {type(t)}")
print(f"TSTensor type from torch: {type(ts_t)}")

# TSTensor의 show 메서드 활용 (실제 데이터 시각화)
# X_train 데이터의 첫 번째 시계열을 TSTensor로 변환 후 시각화
TSTensor(X_train[0]).show(title='Sample Time Series from X_train');

 

 

 

3) 데이터 변환(Transforms): ToNumpyTensor, ToTSTensor, TSClassifictaion

tsai는 데이터를 전처리하고 변환하는 다양한 트랜스폼(Transform)을 제공합니다. 이는 fastai 라이브러리의 트랜스폼 시스템을 기반으로 하는데요 

 

* ToNumpyTensor / ToTSTensor: 데이터를 각각의 텐서 형태로 변환합니다.

* ToInt / ToFloat: 데이터 타입을 정수 또는 부동소수점으로 변환합니다.

* TSClassification: 분류 문제에서 범주형 레이블을 정수형 인코딩으로 변환하고, 필요에 따라 다시 원본 레이블로 디코딩 할 수 있게 해줍니다.

 

# TSClassification 예시
tfm = TSClassification()
# 훈련 데이터의 레이블로 setup을 수행하여, 어떤 범주들이 있는지 학습합니다.
tfm.setup(y_train)

# 레이블을 인코딩합니다.
y_encoded = tfm(y_train)
print(f"Original y_train sample: {y_train[:5]}")
print(f"Encoded y_train sample: {y_encoded[:5]}")

# 인코딩된 레이블을 다시 디코딩합니다.
y_decoded = tfm.decodes(y_encoded)
print(f"Decoded y_train sample: {y_decoded[:5]}")

# 원본과 디코딩된 레이블이 동일한지 확인
assert np.array_equal(y_train, y_decoded)

 

 

 

4) TSDataset 및 TSDatasets: 데이터셋 관리

tsai는 TSDataset과 TSDAtasets 클래스를 통해 시계열 데이터셋을 효율적으로 관리합니다. TSDataset은 단일 시계열 데이터와 그에 해당하는 레이블을 캡슐화하며, TSDatasets는 훈련, 검증 등 여러 데이터셋을 한 번에 관리하고 트랜스폼을 적용할 수 있도록 해줍니다.

# TSDatasets 생성
# X_train, y_train, X_valid, y_valid는 get_UCR_data에서 이미 split되어 있으므로, splits 인자를 활용합니다.
# get_UCR_data에서 반환되는 X_train, X_valid는 각각 splits[0], splits[1]에 해당합니다.
# 여기서는 편의를 위해 전체 데이터 X, y를 다시 불러와 splits 인자를 직접 사용합니다.
X, y, splits = get_UCR_data(dsid, on_disk=True, split_data=False)

# 분류를 위한 트랜스폼 적용
dsets = TSDatasets(X, y, splits=splits, tfms=[None, TSClassification()])

print(f"Total samples: {len(dsets)}")
print(f"Train samples: {len(dsets.train)}")
print(f"Valid samples: {len(dsets.valid)}")

# 데이터셋의 첫 번째 샘플 확인 (X, y 튜플 형태)
sample_x, sample_y = dsets.train[0]
print(f"First train sample X shape: {sample_x.shape}")
print(f"First train sample Y: {sample_y}")
print(f"Type of X: {type(sample_x)}, Type of Y: {type(sample_y)}")

 

 

 

5) TSDataLoader 및 TSDataLoaders: 배치 처리의 효율성

TSDataLoader는 Pytorch DataLoader를 확장하여 tsai의 TSTensor와 트랜스폼 시스템과 잘 연동되도록 설계가 되었습니다. TSDataLoaders는 훈련 및 검증 데이터 로더를 묶어 편리하게 사용할 수 있게 해주며, 훈련 루프에서 데이터를 배치 단위로 가져오는데 필수적입니다.

 

# TSDatasets를 사용하여 TSDataLoaders 생성
dls = TSDataLoaders.from_dsets(dsets.train, dsets.valid, bs=64)

# 훈련 데이터로더에서 첫 번째 배치 가져오기
xb, yb = dls.train.one_batch()

print(f"Shape of X in first train batch: {xb.shape}") # (batch_size, n_variables, seq_len)
print(f"Shape of y in first train batch: {yb.shape}") # (batch_size,)

# 데이터로더 정보 확인
print(f"Number of variables (features): {dls.vars}")
print(f"Sequence length: {dls.len}")
print(f"Is classification task: {dls.cat}")
print(f"Number of classes (if classification): {dls.c}")

# 배치 디코딩 (인코딩된 레이블을 원래 형태로)
decoded_batch = dls.decode((xb, yb))
print(f"Decoded first X in batch shape: {decoded_batch[0][0].shape}")
print(f"Decoded first Y in batch: {decoded_batch[1][0]}")

# 데이터 분포 시각화 (분류 문제의 경우)
dls.show_dist();
dls.train.show_dist();

반응형

댓글