from tensorflow import keras import numpy as np import matplotlib.pyplot as plt %matplotlib inline # 한글설정
x = np.arange(20) y = x * 3 + 10 plt.plot(x,y)
train을 위한 data로 x= 0, 1, 2, 3, ...., 19
, y= 10, 13, 16, 19, ..., 67
인 데이터를 준비했다.
이를 시각화하면 위와 같이 1차 함수가 그려진다.
x_test = np.arange(50,70) y_test = x_test * 3 + 10
test를 위한 data로는 x= 50, 51, 52, ..., 69
, y= 160, 163, 166, ..., 217
인 데이터를 준비했다.
in_dim = 1 out_dim = 1
입력과 출력의 차원은 1로 설정했다.
Keras에서는 Sequential
, Functional
방식으로 모델을 구현한다.
Sequential
방식은 모델에 필요한 layer들을 순차적으로 쌓는 방법이고, Functional
방식은 모델을 수식처럼 구현하는 방법이다.
두 방식 모두 함수 또는 클래스 형태로 만들 수 있다.
def model_sequential(in_dim, out_dim): model = models.Sequential() model.add(layers.Dense(units=out_dim, input_shape=(in_dim,))) return model
함수 형태로 만드는 경우, models.Sequential()
을 사용해 Sequential스타일로 진행한다고 설정한다.
이후 model.add()
를 사용해 layer들을 쌓아주면 된다.
class modeling_sequential_class(models.Sequential): def __init__(self, in_dim, out_dim): self.in_dim = in_dim self.out_dim = out_dim super().__init__() self.add(layers.Dense(units =out_dim, input_shape=(in_dim,)))
클래스 형태로 만드는 경우. models.Sequential
을 상속받아 작성한다.
먼저 self.in_dim
, self.out_dim
으로 멤버 변수로 모델에 사용할 변수를 선언한다.
이후 super().__init__()
상속받은 Sequential 클래스를 초기화한 후에 모델에 레이어를 추가한다.
이때는 model.add()
이 아닌 self.add()
를 사용한다.
def modeling_functional(in_dim, out_dim): inputs = layers.Input(shape=(in_dim, )) y = layers.Dense(out_dim)(inputs) model = models.Model(inputs=inputs, outputs=y) return model
먼저 layers.Input(shape=(in_dim, ))
으로 input layer를 정의한다. 이때 shape
은 입력받는 벡터의 크기를 의미한다.
이후 layers.Dense(out_dim)(inputs)
으로 layer를 쌓는다. 이전 layer인 input
을 입력으로 받고, out_dim
을 출력한다.
y = layers.Dense(out_dim)(inputs)
을 계속 입력해서 모델 layer를 계속 쌓을 수 있다.
layer를 다 만들고 나면 models.Model(inputs=inputs, outputs=y)
로 모델을 선언한다. 이때 입력과 출력을 인자로 입력한다.
class modeling_functional_class(models.Model): def __init__(self, in_dim, out_dim): self.in_dim = in_dim self.n_out = out_dim input = layers.Input(shape=(in_dim,)) output = layers.Dense(out_dim) x = input y = output(x) super().__init__(x, y)
클래스 형식으로 모델을 만들때는 Sequential과 동일하게 self
를 사용해 클래스 내에서 멤버 변수로 모델에 사용할 변수와 레이어를 선언한다.
x = input y = output(x)
로 layer를 연결한다.
super().__init__(x, y)
로 상속받은 모델의 클래스를 초기화한다.
model.summary()
나 plot_model(model)
을 사용한다.model.summary()
가 좀더 간편하다.model = modeling_sequential(n_in, n_out) model.summary()
from tensorflow.keras.utils import plot_model model = modeling_functional(n_in, n_out) plot_model(model, show_shapes=True)
model.compile(loss="mse", optimizer='sgd')
history = model.fit(x, y, batch_size=5, epochs=100, validation_split=0.2)
loss = model.evaluate(x_test, y_test, batch_size=20) print('loss : %.4f'%(loss))
new_x = np.arange(100, 120) true_y = new_x * 3 + 10
test data를 먼저 만들어준다.
true_y는 위에서 만들었던 모델식을 사용해 만들면 된다.
pred_y = model.predict(new_x, batch_size=20, verbose = 0) pred_y = np.reshape(pred_y,(-1,)) for y in zip(new_x, true_y, pred_y): print("x: %.2f, y : %.2f, y_predict : %.2f"%(y[0], y[1], y[2]))
이제 train data를 FC모델에 넣고, 예측값을 출력해봤다.
꽤나 정답에 근사하게 예측하는 것을 볼 수 있다.