728x90
반응형
[1] MNIST 데이터 불러오기 및 정규화
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Input, Conv2D, MaxPool2D
from tensorflow.keras.layers import Flatten, Dense, Dropout
from tensorflow.keras.models import Model
(x_train, y_train), (x_test, y_test) = mnist.load_data() # 데이터 불러오기
x_train = x_train.reshape(-1, 28, 28, 1) # 텐서로 변환 (높이, 너비, 채널)
x_test = x_test.reshape(-1, 28, 28, 1) # 텐서로 변환 (높이, 너비, 채널)
print(x_train.shape, x_test.shape)
print(y_train.shape, y_test.shape)
x_train = x_train/255.0 # 정규화
x_test = x_test/255.0 # 정규화
[2] Functional API CNN 모델 구축
input_ = Input(shape=(28, 28, 1))
x = Conv2D(32, 3, activation='relu')(input_)
x = Conv2D(64, 3, activation='relu')(x)
x = MaxPool2D(pool_size=(2, 2))(x)
x = Dropout(0.25(x)
x = Flatten()(x)
x = Dense(128, activation='relu')(x)
x = Dropout(0.5)(x)
output_ = Dense(10, activation='softmax')(x)
cnn = Model(inputs=input_, outputs=output_)
[3] CNN 모델 컴파일 및 학습
cnn.compile(loss='sparse_categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(), metrics=['accuracy'])
hist = cnn.fit(x_train, y_train, batch_size=128, epochs=30, validation_data=(x_test, y_test))
[4] 모델 (정확도) 평가
cnn.evaluate(x_test, y_test)
[5] 정확도 및 손실
import matplotlib.pyplot as plt
plt.plot(hist.history['accuracy'])
plt.plot(hist.history['val_accuracy'])
plt.title('Accuracy Trend')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.legend(['train', 'validation'], loc = 'best')
plt.grid()
plt.show()
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('Lostt Trend')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.legend(['train', 'validation'], loc='best')
plt.grid()
plt.show()
반응형
'IT > 머신러닝공부' 카테고리의 다른 글
전이학습 Transfer Learning 간단 정리 (0) | 2022.12.31 |
---|---|
Functional API 사용시 혼동하는 경우 간단 정리 (0) | 2022.12.30 |
Functional API 모델, 간단 요약 정리 (0) | 2022.12.30 |
GRU(Gated Recurrent Unit) 게이트 순환 유닛 간단정리 (0) | 2022.12.29 |
LSTM을 활용한 삼성 주가 예측 스크립트 (0) | 2022.12.29 |