잠토의 잠망경

[ML] Multiple Input Series - Multi-headed CNN Model 본문

공부/Python

[ML] Multiple Input Series - Multi-headed CNN Model

잠수함토끼 2020. 2. 15. 11:46

GITHUB

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

 

0. 목표

 

model의 새로운 형태

 

이전 형태에서 model만 바꾼 것으로 input 값의 종류에 따라 layer를 변경한 것이다.

 

1. DATA

# data sample
in_seq1 = np.asarray([10, 20, 30, 40, 50, 60, 70, 80, 90])
in_seq2 = np.asarray([15, 25, 35, 45, 55, 65, 75, 85, 95])
out_seq = np.asarray([in_seq1[i]+in_seq2[i] for i in range(len(in_seq1))])  # sample용 의미 없음

in_seq1 = in_seq1.reshape((in_seq1.shape[0], 1))    # vertical로 만든다.
in_seq2 = in_seq2.reshape((in_seq2.shape[0], 1))
out_seq = out_seq.reshape((out_seq.shape[0], 1))

dataset = np.hstack((in_seq1, in_seq2, out_seq))    # 횡으로 합친다.

이전 형태에서 있는 그림을 참고하면 좋을 것 같다.

 

2. DATA 정제

X

from numpy import ndarray
import numpy as np


def split_sequence(sequence:list, n_steps)->(ndarray, ndarray):

    x, y = [], []

    for i in range(len(sequence)):

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

        x.append(sequence[i:i+n_steps, 0:2])
        y.append(sequence[i+n_steps-1, -1])

    return (np.asarray(x), np.asarray(y))
    
    
n_steps = 3

(x, y) = split_sequence(dataset, n_steps)   # x, y로 나눈다.

# new feature

print(x.shape)  #(7, 3, 2)
n_feature = 1

x1 = x[:,:,0].reshape(x.shape[0], x.shape[1], n_feature)    #(7, 3, 1)  가로 가로 세로
x2 = x[:,:,1].reshape(x.shape[0], x.shape[1], n_feature)    #(7, 3, 1)  가로 가로 세로

print(x1.shape)
print(x2.shape)

input 값을 분리해야 하므로 reshape 작업이 필요하다.

slide의 목적

Y

 

3. 학습

from keras import Sequential
from keras.layers import Conv1D, Dense, Flatten, MaxPool1D, Input, concatenate
from keras import Model

v1 = Input(shape=(n_steps, n_feature))
cnn1 = Conv1D(64, 2, activation='relu')(v1)
cnn1 = MaxPool1D()(cnn1)
cnn1 = Flatten()(cnn1)

v2 = Input(shape=(n_steps, n_feature))
cnn2 = Conv1D(64, 2, activation='relu')(v2)
cnn2 = MaxPool1D()(cnn2)
cnn2 = Flatten()(cnn2)

merge  = concatenate([cnn1, cnn2])
dense  = Dense(50, activation='relu')(merge)
output = Dense(1)(dense)

model = Model(inputs=[v1, v2], outputs=output)
model.compile(loss='mse', optimizer='adam')

model.fit([x1, x2], y, epochs=2000, verbose=1)

 

코드의 도식화

 

4. 표시

x_input = np.asarray([[80,85],[90,95],[100, 105]])  # 205 나올 것으로 예측

x1 = x_input[:,0].reshape((1, n_steps, n_feature))
x2 = x_input[:,1].reshape((1, n_steps, n_feature))

yhat = model.predict([x1, x2], verbose=1)

print(yhat) #[[205.39845]]

input의 형태가 달라졌으므로 수정이 필요하다.

Comments