Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
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
Archives
Today
Total
관리 메뉴

에코프로.AI

[Tensorflow] Tensorflow 소개 및 간단한 모델링 본문

AI Tutorial

[Tensorflow] Tensorflow 소개 및 간단한 모델링

AI_HitchHiker 2024. 8. 22. 10:31

https://datascientest.com/en/files/2023/10/formation-tensorflow-1024x453.jpg

 

TensorFlow 란 무엇입니까?

  • TensorFlow는 구글에서 만든 수치계산, 대규모 머신러닝, 딥러닝, 기타 통계 및 예측 분석 워크로드를 위한 오픈 소스 라이브러리입니다. 개발자들이 머신러닝 모델을 구현하는 것을 더 빠르고 쉽게 만들어 줍니다.
  • TensorFlow는 기존 CPU(중앙처리장치) 또는 GPU(고성능 그래픽 처리 장치) 에서 실행할 수 있습니다. TensorFlow는 Google에서 개발했기 때문에 TensorFlow 작업속도를 높이기 위해 특별히 설계된 회사 자체 텐서 처리장치 (TPU)에서도 작동합니다.
  • TensorFlow로 심층신경망을 학습시켜서 아래와 같은 작업을 할 수 있습니다.
    • 손으로 쓴 숫자 분류
    • 이미지 인식
    • 단어 임베딩 및 자연어 처리(NLP)
  • TensorFlow는 현재 가장 인기있는 딥러닝 라이브러리 중 하나이고, 텐서보드 및 Keras와 같은 추상화 라이브러리 및 사전에 학습된 모델들을 통해 사용자가 딥러닝을 편리하게 사용하도록 도와줍니다.

간단한 신경망모델 구성

  • 인공신경망(ANN, Artificial Neural Network)
    • 어떻게 생물적으로 뇌가 감각 입력의 자극에 반응하는지에 대한 이해로부터 얻어진 모델입니다.
    • 입력신호와 출력신호 간의 관계를 모델링
    • 뇌가 막대한 병렬 프로세서를 생성하기 위해 뉴런(Neuron) 이라는 세로포 연결된 망을 사용하듯이 ANN은 학습문제를 풀기 위해 인공뉴런이나 노드의 망을 사용


유방암데이터를 이용한 Tensorflow 신경망 모델링 구성

  • 데이터 불러오기
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer()
x_data = data.data
y_data = data.target

x_data.shape, y_data.shape

 

  • train, test 데이터 분류 및 표준화 스케일링
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# test_size = 0.25 / 기본설정
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, stratify = y_data, random_state = 0)

print(x_train.shape, y_test.shape)

scaler = StandardScaler()
scaler.fit(x_train)

x_train_zs = scaler.transform(x_train)
x_test_zs = scaler.transform(x_test)

print(x_train[:5], x_train_zs[:5])

 

  • tensorflow - Sequential 모델 구현
    • 신경망 모델은 입력층(Input Layer), 은닉층(Hidden Layer), 출력층(Out Layer)로 구성된다.
      • 아래의 모델은 1개의 입력층, 3개의 은닉층, 1개의 출력층 으로 구성

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input

model = Sequential()

EPOCHS = 50

# Layer 추가

# 입력노드(Input Layer)의 수는 입력데이터의 속성(Column) 개수로 결정
model.add(Input(shape=(30,)))                   # Input Layer

# 모델을 시작하기 전 은닉층의 노드 개수를 결정하지만,
# 적당한 은닉층의 노드 개수를 결정하는 규칙은 없다.
model.add(Dense(64, activation='relu'))         # Hidden Layer
model.add(Dense(32, activation='relu'))         # Hidden Layer
model.add(Dense(8, activation='relu'))          # Hidden Layer

# 출력노드(Out Layer)의 수는 결과의 분류개수(종속변수의 분류 개수)나 모델의 결과 수로 결정
model.add(Dense(2, activation='softmax'))       # Out Layer

model.summary()
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

# one-hot encoding!
from tensorflow.keras.utils import to_categorical
y_train_oh = to_categorical(y_train)
y_test_oh = to_categorical(y_test)
print(y_train[:5], y_train_oh[:5])

# 모델을 학습
hist = model.fit(x_train_zs, y_train_oh, validation_data = (x_test_zs, y_test_oh), epochs = EPOCHS)

# epoch에 따른 train,test 데이터의 accuracy 그래프 그리기
import matplotlib.pyplot as plt
plt.plot(range(EPOCHS), hist.history['accuracy'], label = 'Train data')
plt.plot(range(EPOCHS), hist.history['val_accuracy'], label = 'Test data')
plt.legend()
plt.grid()
plt.xlabel('Epoch')
plt.ylabel('Accuracy')

 

model.summary() 의 출력 값

 

설정 된 epoch= 50회 동안 진행

 

epoch에 따른 train, test 데이터의 Accuracy 를 그래프로 표시