잠토의 잠망경

[ML] Univariate CNN Models 본문

공부/Python

[ML] Univariate CNN Models

잠수함토끼 2020. 2. 15. 10:43

GITHUB

https://github.com/yiwonjae/Project_Lotto/blob/master/Book_001/p091.py

0. 목표

연속된 하나의 sequcence에서 다음 하나의(univariate) 값을 예측한다.

 

data : [10, 20, 30, 40, 50, 60, 70, 80, 90]

x       y
10 20 30   40
20 30 40   50
30 40 50   60

 

1. DATA

raw_seq = [10, 20, 30, 40, 50, 60, 70, 80, 90]

n_steps = 3

 

2. DATA 정제

X

def splite_sequence(sequence:list, n_steps:int)->(ndarray, ndarray):


    x, y = [], []

    for i in range(len(sequence)):

        if(i+n_steps >= len(sequence)):
            break

        x.append(sequence[i:i+n_steps])
        y.append(sequence[i+n_steps])

    return (np.asarray(x), np.asarray(y))


(x, y) = splite_sequence(raw_seq, n_steps)

#reshape from [samples, timesteps] to [sample, timesteps, features]
n_feature = 1 # kind수
x = x.reshape((x.shape[0], x.shape[1], n_feature))

 

Y

 

3. 학습

from keras import Sequential
from keras.layers import Dense, Conv1D, MaxPool1D, Flatten

model = Sequential()
model.add(Conv1D(64, 2, activation='relu', input_shape=(n_steps, n_feature)))
model.add(MaxPool1D())
model.add(Flatten())
model.add(Dense(50, activation='relu'))
model.add(Dense(1))
model.compile(loss='mse', optimizer='adam')

model.fit(x, y, epochs=1000, verbose=1)

 

4. 표시

x_input = np.array([70, 80, 90])
x_input = x_input.reshape((1, n_steps, n_feature))

yhat = model.predict(x_input)

print(yhat)
Comments