티스토리 뷰

CNN을 통해서 기본적인 regression을 하는 방법을 설명하겠다.

기본적으로 python에서 숫자를때 차원을 제대로 고려하는 것이 중요하다.

데이터 셋은 다음과 같다. 

1
2
3
# define dataset
= array([[102030], [203040], [304050], [405060]])
= array([40506070])
cs

 

위의 데이터 셋은 차원을 아는 것이 중요하다.

X데이터의 경우 차원이 (4,3,1)

Y데이터 경우 차원이 (4,)이 도출된다. 

왼쪽 4라는 숫자를 맞춰주어야 한다. 

1
2
print("X.shape", X.shape)  #X.shape (4, 3, 1)
print("Y.shape", y.shape) #Y.shape (4,)
cs

 

 

 

Keras 문법을 시작하겠다.

일렬로 쭉 늘어졌기 때문에 Conv1D 함수를 사용하였고 input_shape는 Xshape (4,3,1)중에 (3,1)을 사용한다

또한 50가지 뉴럴넷을 사용하고 activation 함수는 relu 함수를 사용한다.  

compile시 optimizer는 adam을 사용하고 regression이기 때문에 mse를 사용한다. 

마지막 값은 1개가 도출되어야 하기 때문에 Dense(1) 을 더한다 

1
2
3
4
5
6
7
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(31)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation='relu'))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
cs

 

 

model.fit 함수 사용하여 도출하고 x_input 값 [50,60,70]을 넣어본다. 

최종값은 [[82.24064]] 가 도출된다. 

1
2
3
4
5
6
7
# fit model
model.fit(X, y, epochs=1000, verbose=0)
# demonstrate prediction
x_input = array([506070])
x_input = x_input.reshape((131))
yhat = model.predict(x_input, verbose=0)
print(yhat) #[[82.24064]]
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
#CNN 기본 코드
# univariate cnn example
from numpy import array
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
 
# define dataset
= array([[102030], [203040], [304050], [405060]])
= array([40506070])
# reshape from [samples, timesteps] into [samples, timesteps, features]
= X.reshape((X.shape[0], X.shape[1], 1))
print("X.shape[0]",X.shape[0]) #X.shape[0] 4
print(" X.shape[1]", X.shape[1])#X.shape[1] 3
print("X.shape", X.shape)  #X.shape (4, 3, 1)
print("Y.shape", y.shape) #Y.shape (4,)
 
# define model
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=2, activation='relu', input_shape=(31)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation='relu'))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
 
 
# fit model
model.fit(X, y, epochs=1000, verbose=0)
# demonstrate prediction
x_input = array([506070])
x_input = x_input.reshape((131))
yhat = model.predict(x_input, verbose=0)
print(yhat) #[[82.24064]]
 
 
cs
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2024/05   »
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
글 보관함