본문 바로가기
인공지능 개발하기/Machine Learning

[Tensorflow] 10. 모델 훈련 결과 시각화 하기 (feat. matplolib)

by 선의공 2024. 1. 4.
반응형

 
 
 

이번 포스팅은
모델 훈련 결과를 시각화 해보겠습니다.
 
데이터를 그래프로 나타낼건데요,
matplotlib라는 패키지의 도움을 받아보겠습니다~
 
먼저 이 패키지가 무엇인지 알아야
사용을 할 수 있을것 같아요.
 
 


 
 
 

1. matplotlib이란??

https://matplotlib.org/

 

Matplotlib — Visualization with Python

seaborn seaborn is a high level interface for drawing statistical graphics with Matplotlib. It aims to make visualization a central part of exploring and understanding complex datasets. statistical data visualization Cartopy Cartopy is a Python package des

matplotlib.org

" Matplotlib is a comprehensive library for creating static,
animated, and interactive visualizations in Python. "
 
 
"Python에서 정적 시각화 , 애니메이션 시각화 , 대화형 시각화를
생성하기 위한 포괄적 라이브러리라고 설명하네요.  "
(대화형 시각화 :   그래픽 표현을 통해 데이터를 조작, 탐색 및 분석할 수 있도록 하는 기술)
 
즉 제가 구현할 데이터를 시각화 해준다는 거죠.
 
대학교 때 잠시 만져봤던(싫어했던) matlab이 생각나네요.
지금 이었으면 정말 열심히 했을건데요 ㅜㅜ
 
시각화 모델은 아래와 같습니다.
이번에는 도큐먼트의 함수를 뒤적거리기보단
이 그림에서 필요한 모델을 찾으면 편할 것 같다고 생각해서
가져와봤습니다.
https://matplotlib.org/stable/plot_types/index

 

Plot types — Matplotlib 3.8.2 documentation

Plot types Overview of many common plotting commands provided by Matplotlib. See the gallery for more examples and the tutorials page for longer examples. Pairwise data Plots of pairwise \((x, y)\), tabular \((var\_0, \cdots, var\_n)\), and functional \(f(

matplotlib.org

 

 

 
 
저는 이 데이터 모델중에
scatter(점을 찍어줌)
plot(선을 그려줌)
을 해보겠습니다. 
 
 
 
 


 

 

2. 사용해보기

 
 
 
x라는 입력데이터, y라는 출력데이터가 있구요

# 1. 데이터
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 3, 4, 6, 5, 7, 8, 9, 10])

 
x,y를 이용해서 그래프를 선으로 그러보겠습니다.
import로
matplotlib패키지의 pyplot 이라는 모듈을 plt라는 이름으로
가져와서
scatter(a,b) 함수로 점을 찍고
show() 함수로 그래프를 그려줬습니다.

import matplotlib.pyplot as plt
plt.scatter(x,y) #점 찍기
plt.show() #그래프 보이기

 
 
 
 
 
이번엔 모델 훈련을 시키고
예측값들을 선(그래프)으로
그려보겠습니다.
훈련시킨 모델에 x를 10개 넣어줘서 예측 값(result) 10개를 받았습니다.
(x는 벡터형태인데
predict를 거치고 난 결과는
행렬 형태군요... 예를들어 [1]과 1은 동일시 하는걸까요??)
 
이걸 plot()함수로 선을 긋고
마찬가지로 show() 함수로 출력해줬습니다.

model.fit(x_train, y_train, epochs=500 , batch_size=1)

#평가 , 예측
result = model.predict(x) #x : [1,2,3,4,5,6,7,8,9,10]. 
'''
result:[[0.8769375]
 [1.8886313]
 [2.9003253]
 [3.912019 ]
 [4.9237137]
 [5.935407 ]
 [6.9471006]
 [7.9587927]
 [8.970488 ]
 [9.9821825]]
 '''

import matplotlib.pyplot as plt
plt.plot(x, result, color = 'red') #선을 긋기
plt.show() #그래프 보이기

 
 
 
 
선과 점을 같이 찍어보겠습니다.

plt.scatter(x,y) #점 찍기
plt.plot(x, result, color = 'red') #선을 긋기
plt.show() #그래프 보이기

이렇게 시각화하며
입력값에 대한 출력값을 보면서
훈련 결과를 그래프로 확인할 수 있었습니다.
 
 
 
 
"matplotlib"
크고 복잡한 데이터를 분석할 땐
시각화해서
데이터를 보는게 중요하겠죠.
 
데이터를 적절하게
활용할 수 있도록 
더 정진하겠습니다.
 
 
 
 
그럼 전체 코드 첨부하고 포스팅 마무리하겠습니다
틀린부분이 있다면 말씀 주시면 감사하겠습니다!

import numpy as np
from keras.models import Sequential
from keras.layers import Dense

from sklearn.model_selection import train_test_split

# 1. 데이터
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 3, 4, 6, 5, 7, 8, 9, 10])

#데이터 전처리
x_train, x_test, y_train, y_test = train_test_split(
    x,
    y,
    train_size= 0.7,
    test_size=0.3,
    shuffle=True,
    random_state=1500
)

#모델구성
model = Sequential()
model.add(Dense(1, input_dim = 1))
model.add(Dense(10))
model.add(Dense(10))
model.add(Dense(10))
model.add(Dense(1))

#컴파일, 훈련
model.compile(loss='mse', optimizer='adam')
model.fit(x_train, y_train, epochs=500 , batch_size=1)

#평가 , 예측
loss = model.evaluate(x_test, y_test)
result = model.predict(x) #10개가 들어감.

print("loss 값: ", loss)
print("예측 값: ", result)

import matplotlib.pyplot as plt

plt.scatter(x,y) #점 찍기
plt.plot(x, result, color = 'red') #선을 긋기
plt.show() #그래프 보이기

 

 
 
 

반응형