0 / 0
영어 버전 문서로 돌아가기

시계열 함수

마지막 업데이트 날짜: 2024년 11월 21일
시계열 함수

시계열 함수는 각 시점에 측정되는 데이터 값의 시퀀스에 동작하는 집계 함수입니다.

다음 섹션은 여러 가지 시계열 패키지에서 사용 가능한 시계열 함수의 일부를 설명합니다.

변환

변환은 시계열에 적용되어 다른 시계열을 생성하는 함수입니다. 시계열 라이브러리는 사용자 정의된 변환뿐만 아니라 제공된 변환(from tspy.functions import transformers을(를) 사용하여)을 포함해 다양한 유형의 변환을 지원합니다.

다음 샘플은 몇 가지 제공되는 변환을 보여줍니다.

#Interpolation
>>> ts = tspy.time_series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
>>> periodicity = 2
>>> interp = interpolators.nearest(0.0)
>>> interp_ts = ts.resample(periodicity, interp)
>>> interp_ts.print()
TimeStamp: 0     Value: 1.0
TimeStamp: 2     Value: 3.0
TimeStamp: 4     Value: 5.0

#Fillna
>>> shift_ts = ts.shift(2)
    print("shifted ts to add nulls")
    print(shift_ts)
    print("\nfilled ts to make nulls 0s")
    null_filled_ts = shift_ts.fillna(interpolators.fill(0.0))
    print(null_filled_ts)

shifted ts to add nulls
TimeStamp: 0     Value: null
TimeStamp: 1     Value: null
TimeStamp: 2     Value: 1.0
TimeStamp: 3     Value: 2.0
TimeStamp: 4     Value: 3.0
TimeStamp: 5     Value: 4.0

filled ts to make nulls 0s
TimeStamp: 0     Value: 0.0
TimeStamp: 1     Value: 0.0
TimeStamp: 2     Value: 1.0
TimeStamp: 3     Value: 2.0
TimeStamp: 4     Value: 3.0
TimeStamp: 5     Value: 4.0

# Additive White Gaussian Noise (AWGN)
>>> noise_ts = ts.transform(transformers.awgn(mean=0.0,sd=.03))
>>> print(noise_ts)
TimeStamp: 0     Value: 0.9962378841388397
TimeStamp: 1     Value: 1.9681980879378596
TimeStamp: 2     Value: 3.0289374962174405
TimeStamp: 3     Value: 3.990728648807705
TimeStamp: 4     Value: 4.935338359740761

TimeStamp: 5     Value: 6.03395072999318

세그먼트화

세분화 또는 윈도잉은 시계열을 복수의 세그먼트로 분할하는 프로세스입니다. 시계열 라이브러리는 다양한 양식의 세분화를 지원하며 사용자 정의 세그먼트 작성도 허용합니다.

  • 창 기반 세그먼트화

    시계열의 이 유형의 세분화는 사용자가 지정하는 세그먼트 크기를 기반으로 합니다. 세그먼트는 레코드 기반 또는 시간 기반일 수 있습니다. 텀블링뿐 아니라 슬라이딩 창 기반 세그먼트 작성을 허용하는 옵션이 있습니다.

    >>> import tspy
    >>> ts_orig = tspy.builder()
      .add(tspy.observation(1,1.0))
      .add(tspy.observation(2,2.0))
      .add(tspy.observation(6,6.0))
      .result().to_time_series()
    >>> ts_orig
    timestamp: 1     Value: 1.0
    timestamp: 2     Value: 2.0
    timestamp: 6     Value: 6.0
    
    >>> ts = ts_orig.segment_by_time(3,1)
    >>> ts
    timestamp: 1     Value: original bounds: (1,3) actual bounds: (1,2) observations: [(1,1.0),(2,2.0)]
    timestamp: 2     Value: original bounds: (2,4) actual bounds: (2,2) observations: [(2,2.0)]
    timestamp: 3     Value: this segment is empty
    timestamp: 4     Value: original bounds: (4,6) actual bounds: (6,6) observations: [(6,6.0)]
    
  • 앵커 기반 세그먼트화

    앵커 기반 세분화는 간단한 값일 수 있는 특정 람다에서 고정하여 세그먼트를 작성하는 매우 중요한 유형의 세분화입니다. 하나의 예는 500개의 오류가 선행한 이벤트 찾기 또는 이상 항목을 관찰한 후 값을 조사하는 것입니다. 앵커 기반 세분화의 변종은 다중 마커를 갖는 범위 제공을 포함합니다.

    >>> import tspy
    >>> ts_orig = tspy.time_series([1.0, 2.0, 3.0, 4.0, 5.0])
    >>> ts_orig
    timestamp: 0     Value: 1.0
    timestamp: 1     Value: 2.0
    timestamp: 2     Value: 3.0
    timestamp: 3     Value: 4.0
    timestamp: 4     Value: 5.0
    
    >>> ts = ts_orig.segment_by_anchor(lambda x: x % 2 == 0, 1, 2)
    >>> ts
    timestamp: 1     Value: original bounds: (0,3) actual bounds: (0,3) observations: [(0,1.0),(1,2.0),(2,3.0),(3,4.0)]
    timestamp: 3     Value: original bounds: (2,5) actual bounds: (2,4) observations: [(2,3.0),(3,4.0),(4,5.0)]
    
  • 세그먼터

    segmenters 패키지를 가져와서(from tspy.functions import segmenters 사용) 즉시 제공되는 몇 가지 특수화된 세그먼트가 있습니다. 세분화기의 예는 회귀를 사용하여 시계열을 세분화하는 것입니다.

    >>> ts = tspy.time_series([1.0,2.0,3.0,4.0,5.0,2.0,1.0,-1.0,50.0,53.0,56.0])
    >>> max_error = .5
    >>> skip = 1
    >>> reg_sts = ts.to_segments(segmenters.regression(max_error,skip,use_relative=True))
    >>> reg_sts
    
    timestamp: 0     Value:   range: (0, 4)   outliers: {}
    timestamp: 5     Value:   range: (5, 7)   outliers: {}
    timestamp: 8     Value:   range: (8, 10)   outliers: {}
    

감축기

감축기는 단일 값을 생성하기 위해 시계열 세트 사이의 값에 적용되는 함수입니다. 시계열 reducer 함수는 Hadoop/Spark에서 사용하는 감축기 개념과 유사합니다. 이 단일 값이 콜렉션일 수 있지만, 보다 일반적으로는 단일 오브젝트입니다. 감축기 함수의 예는 시계열 값을 평균화하는 것입니다.

다음을 포함하여 여러 reducer 함수가 지원됩니다.

  • 거리 감축기

    거리 감축기는 두 시계열 사이의 거리를 계산하는 감축기 클래스입니다. 라이브러리는 시퀀스에 대한 숫자뿐 아니라 카테고리 거리 함수도 지원합니다. 여기에는 Itakura Parallelogram, Sakoe-Chiba Band, DTW 비제한 및 DTW 비시간 왜곡 제한조건 같은 시간 왜곡 측정이 포함됩니다. Hungarian 거리 및 Earth-Movers 거리 같은 분산 거리도 사용할 수 있습니다.

    카테고리 시계열 거리 측정을 위해 Damerau Levenshtein 및 Jaro-Winkler 거리 측정을 사용할 수 있습니다.

    >>> from tspy.functions import *
    >>> ts = tspy.time_series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
    >>> ts2 = ts.transform(transformers.awgn(sd=.3))
    >>> dtw_distance = ts.reduce(ts2,reducers.dtw(lambda obs1, obs2: abs(obs1.value - obs2.value)))
    >>> print(dtw_distance)
    1.8557981638880405
    
  • 산술 감축기

    숫자 시계열에 대한 여러 가지 편리한 산술 감축기가 제공됩니다. 여기에는 평균, 합계, 표준 편차 및 모멘트 같은 기본 감축기가 포함됩니다. 엔트로피, kurtosis, FFT 및 그의 변종, 다양한 상관 및 히스토그램도 포함됩니다. 편리한 기본 요약 감축기는 시계열에 관한 기본 정보를 제공하는 describe 함수입니다.

    >>> from tspy.functions import *
    >>> ts = tspy.time_series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
    >>> ts2 = ts.transform(transformers.awgn(sd=.3))
    >>> corr = ts.reduce(ts2, reducers.correlation())
    >>> print(corr)
    0.9938941942380525
    
    >>> adf = ts.reduce(reducers.adf())
    >>> print(adf)
    pValue: -3.45
    satisfies test: false
    
    >>> ts2 = ts.transform(transformers.awgn(sd=.3))
    >>> granger = ts.reduce(ts2, reducers.granger(1))
    >>> print(granger) #f_stat, p_value, R2
    -1.7123613937876463,-3.874412217575385,1.0
    
  • 시계열을 1차적으로 이해하기 위해 매우 유용한 또 다른 기본 감축기는 서술 감축기입니다. 다음이 이 감축기를 보여줍니다.

    >>> desc = ts.describe()
    >>> print(desc)
    min inter-arrival-time: 1
    max inter-arrival-time: 1
    mean inter-arrival-time: 1.0
    top: null
    unique: 6
    frequency: 1
    first: TimeStamp: 0     Value: 1.0
    last: TimeStamp: 5     Value: 6.0
    count: 6
    mean:3.5
    std:1.707825127659933
    min:1.0
    max:6.0
    25%:1.75
    50%:3.5
    75%:5.25
    

일시적 결합

라이브러리는 일시적 결합 또는 시간소인을 기반으로 하는 시계열 결합을 위한 함수를 포함하고 있습니다. 결합 함수는 left, right, outer, inner, left outer, right outer joins 등을 포함한 데이터베이스의 함수와 비슷합니다. 다음 샘플 코드는 이들 결합 함수의 몇 가지를 보여줍니다.

# Create a collection of observations (materialized TimeSeries)
observations_left = tspy.observations(tspy.observation(1, 0.0), tspy.observation(3, 1.0), tspy.observation(8, 3.0), tspy.observation(9, 2.5))
observations_right = tspy.observations(tspy.observation(2, 2.0), tspy.observation(3, 1.5), tspy.observation(7, 4.0), tspy.observation(9, 5.5), tspy.observation(10, 4.5))

# Build TimeSeries from Observations
ts_left = observations_left.to_time_series()
ts_right = observations_right.to_time_series()

# Perform full join
ts_full = ts_left.full_join(ts_right)
print(ts_full)

TimeStamp: 1     Value: [0.0, null]
TimeStamp: 2     Value: [null, 2.0]
TimeStamp: 3     Value: [1.0, 1.5]
TimeStamp: 7     Value: [null, 4.0]
TimeStamp: 8     Value: [3.0, null]
TimeStamp: 9     Value: [2.5, 5.5]
TimeStamp: 10     Value: [null, 4.5]

# Perform left align with interpolation
ts_left_aligned, ts_right_aligned = ts_left.left_align(ts_right, interpolators.nearest(0.0))

print("left ts result")
print(ts_left_aligned)
print("right ts result")
print(ts_right_aligned)

left ts result
TimeStamp: 1     Value: 0.0
TimeStamp: 3     Value: 1.0
TimeStamp: 8     Value: 3.0
TimeStamp: 9     Value: 2.5
right ts result
TimeStamp: 1     Value: 0.0
TimeStamp: 3     Value: 1.5
TimeStamp: 8     Value: 4.0
TimeStamp: 9     Value: 5.5

예측

시계열 라이브러리가 제공하는 핵심 기능은 예측입니다. 라이브러리에는 ARIMA, Exponential, Holt-Winters 및 BATS를 포함한 단순 및 복합 예측 모델을 위한 함수가 포함되어 있습니다. 다음 예는 Holt-Winters를 작성하기 위한 함수를 보여줍니다.

import random

model = tspy.forecasters.hws(samples_per_season=samples_per_season, initial_training_seasons=initial_training_seasons)

for i in range(100):
    timestamp = i
    value = random.randint(1,10) * 1.0
    model.update_model(timestamp, value)

print(model)

Forecasting Model
  Algorithm: HWSAdditive=5 (aLevel=0.001, bSlope=0.001, gSeas=0.001) level=6.087789839896166, slope=0.018901997884893912, seasonal(amp,per,avg)=(1.411203455586738,5, 0,-0.0037471500727535465)

#Is model init-ed
if model.is_initialized():
    print(model.forecast_at(120))

6.334135728495107

ts = tspy.time_series([float(i) for i in range(10)])

print(ts)

TimeStamp: 0     Value: 0.0
TimeStamp: 1     Value: 1.0
TimeStamp: 2     Value: 2.0
TimeStamp: 3     Value: 3.0
TimeStamp: 4     Value: 4.0
TimeStamp: 5     Value: 5.0
TimeStamp: 6     Value: 6.0
TimeStamp: 7     Value: 7.0
TimeStamp: 8     Value: 8.0
TimeStamp: 9     Value: 9.0

num_predictions = 5
model = tspy.forecasters.auto(8)
confidence = .99

predictions = ts.forecast(num_predictions, model, confidence=confidence)

print(predictions.to_time_series())

TimeStamp: 10     Value: {value=10.0, lower_bound=10.0, upper_bound=10.0, error=0.0}
TimeStamp: 11     Value: {value=10.997862810553725, lower_bound=9.934621260488143, upper_bound=12.061104360619307, error=0.41277640121597475}
TimeStamp: 12     Value: {value=11.996821082897318, lower_bound=10.704895525154571, upper_bound=13.288746640640065, error=0.5015571318964149}
TimeStamp: 13     Value: {value=12.995779355240911, lower_bound=11.50957896664928, upper_bound=14.481979743832543, error=0.5769793776877866}
TimeStamp: 14     Value: {value=13.994737627584504, lower_bound=12.33653268707341, upper_bound=15.652942568095598, error=0.6437557559526337}

print(predictions.to_time_series().to_df())

timestamp      value  lower_bound  upper_bound     error
0         10  10.000000    10.000000    10.000000  0.000000
1         11  10.997863     9.934621    12.061104  0.412776
2         12  11.996821    10.704896    13.288747  0.501557
3         13  12.995779    11.509579    14.481980  0.576979
4         14  13.994738    12.336533    15.652943  0.643756

시계열 SQL

시계열 라이브러리는 Apache Spark와 단단히 통합됩니다. Spark Catalyst에서 새 데이터 유형을 사용하여 Apache Spark를 사용하여 수평적으로 규모 확장하는 시계열 SQL 오퍼레이션을 수행할 수 있습니다. 이를 통해 IBM Analytics Engine 시계열 확장 기능을 쉽게 사용할 수 있으며, watsonx.ai Studio Spark 환경과 같은 IBM Analytics Engine 기능이 포함된 솔루션에서도 시계열 확장 기능을 사용할 수 있습니다.

SQL 확장은 세그먼트화, 변환, 감축기, 예측, I/O 등 시계열 함수의 대부분의 측면을 포함합니다. 시계열 데이터 분석을 참조하십시오.

자세히 알아보기

tspy Python SDK를 사용하려면 tspy Python SDK 문서를 참조하십시오.

상위 주제: 시계열 분석