6주차 딥러닝 (4)

정지원·2024년 3월 26일
0

에이블 스쿨 복습

목록 보기
27/51
post-thumbnail

시계열모델링

  • 시간에 따라 변화하는 데이터를 분석하고 예측하기 위한 통계적 모델링 기법
  • 경제, 금융, 기상, 주가 등 분야 사용
  • 과거 데이터를 기반으로 미래의 값을 예측하는 데 사용함
  • 시간흐름 구간 데이터로 예측 대상 지점과의 관계로 부터 패턴 추출함

RNN

  • 최근 x일간 데이터를 기반으로 다음날 주가 예측
  • x일 동안의데이터를 현재에 반영하여 학습하도록 설계

RNN을 위한 전처리

1) 데이터 분할: x, y

x = data.loc[:, ['AvgTemp']]
y = data.loc[:,'y']

2) 스케일링 (만약 데이터가 많으면 분할 전 스케일링 가능)

  • x스케일링
  • y 값이 크면 최적화를 위해 스케일링 필요
# x 스케일링
scaler = MinMaxScaler()
x = scaler.fit_transform(x)

# 데이터 확인
x.shape, y.shape

3) 3차원 데이터셋 만들기

  • 2차원 데이터셋(x) -> timesteps 단위로 잘라서 함

3차원 변환 함수

# 시계열 데이터 전처리 2차원 --> 3차원으로 변환 함수
def temporalize(x, y, timesteps):
    nfeature = x.shape[1]
    output_x = []
    output_y = []
    for i in range(len(x) - timesteps + 1):
        t = []
        for j in range(timesteps):
            t.append(x[[(i + j)], :])
        output_x.append(t)
        output_y.append(y[i + timesteps - 1])
    return np.array(output_x).reshape(-1,timesteps, nfeature), np.array(output_y)

3차원 변환

x2, y2 = temporalize(x, y, 4) # 3차원 구조
x2.shape, y2.shape

4) 데이터 분할2: train, val

x_train, x_val, y_train, y_val = train_test_split(x2, y2, test_size= 53, shuffle = False)

RNN 모델링 - SimpleRNN

  • SimpleRNN
  • 노드 수 1개 -> 레이어 출력형태: timesteps * 노드수
  • return_sequences 출력데이터를 다음 레이어에 전달할 크기 결정
    • True : 출력 크기 전체 전달
    • False : 가장 마지막 값만 전달
# 한개일 경우
model = Sequential([SimpleRNN(1, input_shape(timesteps, nfeatures), return_sequences=False),
				   Dense(1) ])


# 두개 이상일 경우
model = Sequential([SimpleRNN(16, input_shape=(timesteps, nfeatures), return_sequences=True),
					SimpleRNN(8, return_sequences=True),
					SimpleRNN(1, return_sequences=False),
                    Dense(1) ])

Flatten() 이용

  • 중간과정의 hidden state값들을 펼침 (2차원 -> 1차원)
  • Dense로 연결함
model = Sequential(SimpleRNN(16, input_shape=(timesteps, nfeatures), return_sequences=True),
				   SimpleRNN(8, return_sequences=True),
                   Flatten(),
                   Dense(8, activation='relu'),
                   Dense(1) ])

활성화 함수 tanh

  • 그래디언트 소실문제를 해결하기 위해
  • 그래디언트 소실문제(gradient가 작아져 학습이 어려워지는 현상)
  • tanh 함수 사용
  • 따로 사용하지 않아도 디폴트로 적용됨

LSTM

  • RNN의 장기 읜존성 문제: 긴 시간 동안 정보를 유지하고 활용하는데 어려움 발생
  • Cell state: 긴 시퀸스 동안 정보를 보존
    • Forget Gate: 불필요한 과거 지움
    • Input Gate: 현재 정보 중 중요한 것은 기억
  • Hidden state: Cell에서 hidden으로 업데이트

LSTM 모델 구조

데이터 준비

# 3차원 나눔
timesteps = 8
x2, y2 = temporalize(x, y, timesteps)

# 데이터 분할
x_train, x_val, y_train, y_val = train_test_split(x2, y2, test_size= 53, shuffle = False)

입력구조

timesteps = x_train.shape[1]
nfeatures = x_train.shape[2]

모델 생성

clear_session()

model4 = Sequential([LSTM(10, input_shape= (timesteps, nfeatures), return_sequences=True),
                    LSTM(8, return_sequences=True),
                    LSTM(4, return_sequences=True),
                    Flatten(),
                    Dense(8, activation='relu'),
                    Dense(1)])
model4.summary()

컴파일 및 학습

model4.compile(optimizer=Adam(0.001), loss='mse')
hist = model4.fit(x_train, y_train, epochs=200, verbose=0, validation_split=.2).history

예측 및 평가

pred4 = model4.predict(x_val)
print(mean_absolute_error(y_val, pred4))
profile
뒤늦게 프로그래밍을 시작한 응애

0개의 댓글