본문 바로가기
딥러닝

[딥러닝] 텐서플로우 예측 ANN: loss= 'mse', activation= 'linear'

by eyoo 2022. 6. 10.

자동차 구매 가격을 예측하는 ANN을 만들어 보자.

 

데이터셋 속의 사람들의 각종 정보들을 이용해서 고객이 얼마정도의 차를 구매할 수 있을지 예측한다.

 

먼저 전처리 작업을 한다.

 

# Nan 처리
df.isna().sum()

# X, y구분
X = df.iloc[:,3:-1]
y = df['Car Purchase Amount']

# 피처 스케일링
from sklearn.preprocessing import MinMaxScaler
scaler_X = MinMaxScaler()
X = scaler_X.fit_transform(X)

y = y.values.reshape(500,1) # y 형태 2차원으로 변경
scaler_y = MinMaxScaler()
y = scaler_y.fit_transform(y)

# 트레이닝셋과 테스트셋으로 분리
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X_scaled,y_scaled,test_size= 0.2 , random_state=11)

 

 

그 후 딥러닝을 이용한 모델링을 시작한다.

 

def build_model() :
  model = Sequential()
  model.add( Dense(units=5, activation='relu', input_shape=(5, )) ) # input layer
  model.add( Dense(units=25, activation='relu') )
  model.add( Dense(units=10, activation='relu') )
  model.add( Dense(units=1, activation='linear') )
  model.compile('adam', 'mse')
  return model
  
model = build_model()

# 예측하기위해 컴파일할때 loss함수로 mse(mean_squared_error)를 사용했다.

# 예측결과를 나타내기 위해 아웃풋 엑티베이션으로 linear 함수를 사용했다.

 

 

모델링 한 다음, 학습을 진행한다.

 

epoch_history = model.fit(X_train,y_train, epochs= 20, batch_size= 10)

# 예측하는것이기 때문에 metrics로 accuracy(정확도)를 띄울수 없다.

 

 

학습이 끝나면 학습이 잘되었는지 평가한다.

 

in:

y_pred = model.predict(X_test)

((y_test - y_pred)**2).mean()

out:

0.0002960850123550005

# mse가 낮게 나온것을 보니 학습이 잘 되었다는것을 알수있다.

# evaluate함수로도 평가지표들을 볼수있다.

 

 

이를 시각화 해보자.

 

in:

plt.plot(y_test)
plt.plot(y_pred)
plt.legend(['Real','Pred'])
plt.show()

out:

# 거의 동일한 그래프를 그리는것을 볼수있다.

 

 

주어진 데이터로 학습된 모델을 이용하여 예측해보자.

 

고객의 나이는 38, 연봉은 90000, 카드빚은 2000, 순자산은 500000 일때, 어느정도의 차량을 구매할 수 있을지 예측하자.

 

in:

new_data = np.array([0,38,90000,2000,5000000])

new_data = new_data.reshape(1,5)

new_data = scaler_X.transform(new_data)

y_pred = model.predict(new_data)

scaler_y.inverse_transform(y_pred)

out:

array([[130231.38]], dtype=float32)

# 130231.38달러가 예측됬다.

 

 

 

 

 

 

댓글