관리 메뉴

ComputerVision Jack

[스터디 - RNN 예제] 본문

DeepLearning Study/모두의 딥러닝 예제

[스터디 - RNN 예제]

JackYoon 2020. 5. 25. 20:14
반응형

[RNN Dataset]

이번 스터디에선 Amazon 주식 dataset을 사용하여 내일의 주식 가격을 예측해보는 시간을 보냈습니다.

csv 파일을 보시면 시계열로 데이터가 나열되어 있음을 확인할 수 있습니다.

 

AMZN Dataset

우선 판다스의 데이터 전처리 과정을 통해서 데이터를 수정하겠습니다.

우선 date는 크게 영향을 줄거 같지 않아 제거한 후, Close와 Adj Close는 비슷하여 하나로 통합 후,  Y라는 변수로 추가하였습니다.

데이터 전처리 후

<코드>

def MinMaxScalar(data):

  numerator = data - np.min(data, 0)

  denominator = np.max(data, 0) - np.min(data, 0)

  return numerator / (denominator + 1e-7)

#데이터의 값을 MinMaxScalar() 함수를 통하여 비슷한 값으로 맞춰줍니다.

 

seq_length = 28

data_dim = 5

hidden_dim = 20

output_dim = 1

learning_rate = 0.01

iterations = 700

#하이퍼 파라미터 설정

 

def build_dataset(time_seriesseq_length):

    dataX = []

    dataY = []

    for i in range(0, len(time_series) - seq_length):

        _x = time_series[i:i + seq_length, :]

        _y = time_series[i + seq_length, [-1]]  # Next close price

        print(_x, "->", _y)

        dataX.append(_x)

        dataY.append(_y)

    return np.array(dataX), np.array(dataY)

#추출할 사이즈 만큼 dataX와 dataY를 수정합니다.

 

trainX, trainY = build_dataset(train_set, seq_length)

testX, testY = build_dataset(test_set, seq_length)

#train set과 test set을 구분합니다.

 

X = tf.placeholder(tf.float32, [None, seq_length, data_dim])

Y = tf.placeholder(tf.float32, [None, 1])

 

cell = tf.contrib.rnn.BasicLSTMCell(

    num_units=hidden_dim, state_is_tuple=True, activation=tf.nn.softsign)

outputs, _states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)

Y_pred = tf.contrib.layers.fully_connected(

    outputs[:, -1], output_dim, activation_fn=tf.identity) 

#모두의 딥러닝에서 학습한 방법처럼 RNN을 구현합니다.

 

loss = tf.reduce_sum(tf.square(Y_pred - Y))

optimizer = tf.train.AdamOptimizer(learning_rate)

train = optimizer.minimize(loss)

#cost 함수와 optimizer 최적화를 사용합니다.

학습

import matplotlib.pyplot as plt

%matplotlib inline

plt.figure(figsize = (10, 10))

plt.plot(testY , label = 'Y')

plt.plot(test_predict, label = 'Pre')

plt.xlabel("Time Period")

plt.ylabel("Stock Price")

plt.show()

#위의 학습한 결과를 matplotlib.pyplot을 이용하여 시각화 해보겠습니다.

주식가격 예측 시각화

recent_data = np.array([data[len(data) - seq_length : ]])

print("recent_Data.shape", recent_data.shape)

print("recent_data :", recent_data)

#test set의 최근 데이터를 이용하여 학습된 모델에 입력으로 넣어줍니다.

 

def reverese_min_max_scaling(org_xx):

  org_x_np = np.asarray(org_x)

  x_np = np.asarray(x)

  return (x_np * (org_x_np.max() - org_x_np.min() + 1e-7)) + org_x_np.min()

#다시 min_max_scalar_reverser 과정을 통하여 역으로 그 값을 변환합니다.

최종 실행결과
AMZN.csv
0.35MB
RnnAmajon.ipynb
0.41MB

반응형
Comments