1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SimpleRNN, Flatten, Dense, Dropout
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import load_img, img_to_array, ImageDataGenerator
import matplotlib.pyplot as plt
 
 
# raw 데이터 생성
x_data = np.arange(03650.1)
y_data = 2*np.sin(1.2*x_data) - np.cos(x_data/1.5+ 1  # np.array(3650,)
 
y_data = y_data.reshape(-11)  # np.array(3650,) -> np.array(3650, 1)
 
## y_data 확인
# plt.grid()
# plt.plot(y_data)
# plt.show()
 
# 데이터셋 생성
window_size = 30
horizon_factor = 1
 
 
def makeDataset(y_data, window_size, horizon_factor):
    temp_x = []
    temp_y = []
 
    for i in range(len(y_data)-(window_size+horizon_factor)+1):
        x = y_data[i:(i+window_size)]
        y = (y_data[i+window_size+horizon_factor-1])
 
        temp_x.append(x)
        temp_y.append(y)
 
    return np.array(temp_x), np.array(temp_y)  # (4, 5) -> (1, 4, 5)
 
 
x_train, y_train = makeDataset(y_data, window_size, horizon_factor) # shape : (3620, 30, 1), (3620, 1)
 
split_ratio = 0.75
train_num = int(len(x_train)*split_ratio)
 
x_val = x_train[train_num:]
y_val = y_train[train_num:]
 
x_train = x_train[0:train_num]
y_train = y_train[0:train_num]
 
 
# 모델 생성
def make_model():
    model = Sequential()
    model.add(SimpleRNN(units=32, activation='tanh', input_shape=(301)))
    model.add(Dense(8, activation='relu'))
    model.add(Dense(1))
 
    return model
 
 
model = make_model()
model.compile(loss='mse', optimizer=tf.keras.optimizers.RMSprop(), metrics=['mae'])
 
history = model.fit(x_train, y_train, epochs=50, validation_data=(x_val, y_val))
 
# 훈련의 정확도 확인
plt.plot(history.history['mae'])
plt.plot(history.history['val_mae'])
plt.xlabel('epoch')
plt.ylabel('mae')
plt.legend(['train''validation'], loc='best')
plt.show()
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SimpleRNN, Flatten, Dense, Dropout
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import load_img, img_to_array, ImageDataGenerator
import matplotlib.pyplot as plt
 
# raw 데이터 생성
x_data = np.arange(03650.1)
y_data = 2 * np.sin(1.2 * x_data) - np.cos(x_data / 1.5+ 1  # np.array(3650,)
 
y_data = y_data.reshape(-11)  # np.array(3650,) -> np.array(3650, 1)
 
## y_data 확인
# plt.grid()
# plt.plot(y_data)
# plt.show()
 
# 데이터셋 생성
window_size = 30
horizon_factor = 1
 
 
def makeDataset(y_data, window_size, horizon_factor):
    temp_x = []
    temp_y = []
 
    for i in range(len(y_data) - (window_size + horizon_factor) + 1):
        x = y_data[i:(i + window_size)]
        y = (y_data[i + window_size + horizon_factor - 1])
 
        temp_x.append(x)
        temp_y.append(y)
 
    return np.array(temp_x), np.array(temp_y)  # (4, 5) -> (1, 4, 5)
 
 
x_train, y_train = makeDataset(y_data, window_size, horizon_factor)  # shape : (3620, 30, 1), (3620, 1)
 
split_ratio = 0.75
train_num = int(len(x_train) * split_ratio)
 
x_val = x_train[train_num:]
y_val = y_train[train_num:]
 
x_train = x_train[0:train_num]
y_train = y_train[0:train_num]
 
 
# 모델 생성
def make_model():
    model = Sequential()
    model.add(SimpleRNN(units=32, activation='tanh', input_shape=(301)))
    model.add(Dense(1))
 
    return model
 
 
model = make_model()
model.compile(loss='mse', optimizer=tf.keras.optimizers.RMSprop(), metrics=['mae'])
 
history = model.fit(x_train, y_train, epochs=1, validation_data=(x_val, y_val))
 
 
# 모델 평가
pred = model.predict(x_val)  # shape = (905, 1)
random_idx = np.random.randint(0len(x_val), size=10)
 
print(pred.flatten()[random_idx])  # shape = (905, )
print(y_val.flatten()[random_idx])
 
plt.plot(pred, label='prediction')
plt.plot(y_val, label='label')
plt.legend(loc='best')
plt.show()출력
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SimpleRNN, Flatten, Dense, Dropout
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import load_img, img_to_array, ImageDataGenerator
import matplotlib.pyplot as plt
 
 
# SimpleRNN 인자 : return_sequences, return_state
 
x_data = [[120110100], [908095], [404560]]
x_data = np.array(x_data, dtype=np.float32).reshape(-133)
 
rnn = SimpleRNN(2)
hidden_state = rnn(x_data)  # shape = (1, 2), 마지막 시점의 은닉 상태만 출력
 
rnn2 = SimpleRNN(2, return_sequences=True)  # shape = (1, 3, 2), 모든 시점에 대해서 은닉 상태의 값을 출력
hidden_state2 = rnn2(x_data)
 
# return_state가 True일 경우, return_sequences와 상관없이 마지막 시점의 은닉 상태를 출력
cs

 

반응형

+ Recent posts