728x90
반응형
[1] 시계열 데이터 : y=0.5sini(x) - cos(x/2)정의
import tensorflow as tf
import numpy as np
import matplotlib.pygame as plt
from tensorflow.keras.layers import SimpleRNN, Dense
from tensorflow.keras import Sequential
X = np.arragne(0, 100, 0.1) # 1000개의 시계열 데이터
Y = 0.5 * np.sin(2*x) - np.cos(x/2.0)
seq_data = y.reshape(-1, 1) # RNN입력에 필수적인 3차원 텐서 형태의 입력 데이터로 쉽게 만들기 위해서 사용 -> (1000, 1) 행렬로 바꾸어 줌
print(seq_data.shape)
print(seq_data[:5])
plt.grid()
plt.title('0.5 * sin(2x)-cos(x/2)')
plt.xlabel('time')
plt.ylabel('amplitude')
plt.plot(seq_data)
plt.show
[2] 입력 데이터 x, 정답 데이터 y 생성
w=20 # window size
h=1 # horizon size
X, Y = seq2dataset(seq_data, w, h)
print(X.shape, Y.shape)
def seq2dataset(seq, window, horizon):
X = []
Y = []
for i in range(len(seq_ - (window+horizon)+1):
x=seq[i:(i+window)] # 슬라이싱으로 리스트 형태로 x 데이터 생성
y=(seq[i+window+horizon-1])
X.append(x)
Y.append(y)
return np.array(X), np.array(Y) # 2차원 행렬을 np.array()함수를 통해서 3차원 텐서로 변환하여 리턴
[3] 트레이닝 데이터 / 테스트 데이터 분리
split_ratio = 0.8
split = int(split_ratio * len(x))
x_train = X[0:split]
y_train = Y[0:split]
x_test = X[split:]
y_test = Y[split:]
print(x_train.shape, y_train.shape, x_test.shape, y_test.shape)
[4] SimpleRNN 모델 구축
model = Sequential()
model.add(SimpleRNN(unit=128, activation='tanh', input_shape=x_train[0].shape))
model.add(Dense())
model.summary()
[5] SimpleRNN 모델 컴파일 및 학습
model.complie(loss='msg', optimizer='admin', metrics=['mae']
hist=model.fit(x_train, y_train, epochs=100, validation_data=(x_test, y_test)
[6] 정확도 및 손실
pred = model.predict(x_test)
print(pred.shape)
rand_idx=np.random.randint(0, len(y_test), size=5)
print('random idx = ', rand_dix, '\n')
print('read = ', pred.flatten()[rand_idx])
print('label = ', y_test.flatten()[rand_idx])
rand_idx=np.random.randint(0, len(y_test), size=5)
print('random idx = ', rand_dix, '\n')
print('read = ', pred.flatten()[rand_idx])
print('label = ', y_test.flatten()[rand_idx])
plt.plot(pred, label = 'prediction')
plt.plot(y_test, label = 'label')
plt_grid()
plt.legend(loc='best')
plt.show()
반응형
'IT > 머신러닝공부' 카테고리의 다른 글
LSTM을 활용한 삼성 주가 예측 스크립트 (0) | 2022.12.29 |
---|---|
LSTM 개념, 구조, 동작원리 간단 정리(Long Short-Term memory) (0) | 2022.12.29 |
RNN(Recurrent Neural Network) - 순환신경망 간단정리 (0) | 2022.12.29 |
CIFAR-10을 이용한 CNN 성능 향상 과정 예제 스크립트 (0) | 2022.12.29 |
CNN-ImageDataGenerator를 활용한 예제 스크립트 (0) | 2022.12.29 |