import tensorflow as tf
import numpy as np
from tensorflow.keras.datasets import mnist
(x_train, t_train), (x_test, t_test) = mnist.load_data()
print('\n train shape =', x_train.shape, ', train label shape = ', t_train.shape)
print(' test shape =', x_test.shape, ', test label shape=', t_test.shape)
print('\n train label = ', t_train) # 학습 데이터
print(' test label =', t_test) # 테스트 데이터
print(x_train[0])
import matplotlib.pyplot as plt
# 25개 이미지 출력
plt.figure(figsize=(6,6))
for index in range(25): # 25개 이미지 출력
plt.subplot( 5, 5, index + 1) # 5행 5열
plt.imshow(x_train[index], cmap='gray')
plt.axis('off')
# plt.title(str(t_train[index]))
plt.show()
# 학습 데이터 / 테스트 데이터 정규화
x_train = (x_train - 0.0) / (255.0 - 0.0)
x_test = (x_test - 0.0) / (255.0 - 0.0)
# 정답 데이터 원핫 인코딩
t_train = tf.keras.utils.to_categorical(t_train, num_classes=10)
t_test = tf.keras.utils.to_categorical(t_test, num_classes=10)
print(x_train[0])
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(100, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3), loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
hist = model.fit(x_train, t_train, epochs=30, validation_split=0.3)
model.evaluate(x_test, t_test)
plt.title('Loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.grid()
plt.plot(hist.history['loss'], label='train loss')
plt.plot(hist.history['val_loss'], label='validation loss')
plt.legend(loc='best')
plt.show()
plt.title('Accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.grid()
plt.plot(hist.history['accuracy'], label='train accuracy')
plt.plot(hist.history['val_accuracy'], label='validation accuracy')
plt.legend(loc='best')
plt.show()
'Python' 카테고리의 다른 글
TensorFlow 2.x버전으로 CNN 실습하기 # 2 (이미지 분석) (0) | 2022.02.11 |
---|---|
TensorFlow 2.x버전으로 CNN 실습하기 # 1 (문자 분석) (0) | 2022.02.11 |
Python 으로 공공 데이터 API을 이용한 크롤링( 코로나 확진자 알아보기 ) # 2 (0) | 2022.02.09 |
[Python] TensorFlow를 활용한 딥러닝 실습예제 (placeholder, variable) (0) | 2022.02.09 |
[Python] module 'tensorflow' has no attribute 'placeholder' 에러 해결법 (0) | 2022.02.09 |