5강
딥러닝 프로그램 꾸미기
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper Libraries
import numpy as np
import matplotlib.pyplot as plt
# Tensorflow version check
print(tf.__version__)
- 상수 설정
#Define Constants
batch_size = 128
epochs = 100
num_classes = 10
# Download MNIST dataset.
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
** 이미지와 해당 이미지 값을 가져온다.
** train 이미지가 6만개, test 이미지가 1만개이다.
- Tensorflow가 계산하기 쉽게 255.0으로 나눠준다.
# Normalize the input image so that each pixel value is between 0 to 1.
train_images = train_images / 255.0
test_images = test_images / 255.0
- 모델 생성
# Define the model architecture
# Create Stack
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28,28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(num_classes, activation='softmax')
])
# Compile
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
** Sequential을 list형식으로 만들 수 있다.
** Flatten() : 28x28의 2차원 배열을 1차원으로 변환
** 128개의 은닉층
** activation='softmax' = activation=tf.nn.softmax 는 같은 것이다.
** SparseCategoricalCrossentropy : Multinomial Classification이기 때문
- 학습
history = model.fit(train_images, train_labels, epochs=epochs, batch_size=batch_size)
** input : train_images
** result : train_labels
** batch_size=batch_size : 몇 번 단위로 데이터를 확인할 것인지를 설정하는 것
# Evaluate the model using test dataset.
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test Accuracy: ', test_acc)
- 숫자를 보여주는 함수
import math
[참조]
- 그래프를 그리는 함수
# Helper function to display digit images
def show_sample(images, labels, sample_count=25):
# Create a square with can fit {sample_count} images
grid_count = math.ceil(math.ceil(math.sqrt(sample_count)))
grid_count = min(grid_count, len(images), len(labels))
** math.sqrt(숫자) : 숫자에 루트를 씌운 개수만큼 격자형태를 만든다.
ex) math.sqrt(25) : 5 x 5 의 격자형태
plt.figure(figsize=(2*grid_count, 2*grid_count))
for i in range(sample_count):
plt.subplot(grid_count, grid_count, i+1)
plt.xticks([])
plt.yticks([])
plt.imshow(images[i], cmap=plt.cm.gray)
plt.xlabel(labels[i])
plt.show()
** plt.grid(False) : 그리드가 보이지 않게 표시
** cmap=plt.cm.gray : 하얀 바탕으로 표시, default는 보라색 바탕
# Helper function to display specific digit images
def show_sample_digit(images, labels, digit, sample_count=25):
- 숫자가 7인 경우의 처리
# Create a square with can fit {sample_count} images
grid_count = math.ceil(math.ceil(math.sqrt(sample_count)))
grid_count = min(grid_count, len(images), len(labels))
plt.figure(figsize=(2*grid_count, 2*grid_count))
i = 0
digit_count = 0
while digit_count < sample_count:
i += 1
if (digit == labels[i]):
plt.subplot(grid_count, grid_count, digit_count+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(images[i], cmap=plt.cm.gray)
plt.xlabel(labels[i])
digit_count += 1
plt.show()
- 특정한 하나의 이미지를 보여주는 함수
# Helper function to display specific digit images
def show_digit_image(image):
# Draw digit image
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 29, 5)
minor_ticks = np.arange(0, 29, 1)
ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)
# And a corresponding grid
ax.grid(which='both')
# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)
ax.imshow(image, cmap=plt.cm.binary)
plt.show()
- 테스트용 이미지를 가져옴
# Show the first 25 images in the training dataset.
show_sample(test_images, ['Label: %s' % label for label in test_labels])
- 학습용 이미지 확인
# Show the first 25 images in the training dataset.
show_sample(train_images, ['Label: %s' % label for label in train_labels])
- 숫자 7의 외국 표기법이 다름. 숫자 7의 이미지를 가져오게 함.
# Show digit 7 the first 25 images in the training dataset.
show_sample_digit(train_images, train_labels, 7)
- 모델 평가
# Evaluate the model using test dataset. - Show performance
fig, loss_ax = plt.subplots()
fig, acc_ax = plt.subplots()
# Loss용 그래프
loss_ax.plot(history.history['loss'], 'ro')
loss_ax.set_xlabel('epoch')
loss_ax.set_ylabel('loss')
# Accuracy용그래프
acc_ax.plot(history.history['accuracy'], 'bo')
acc_ax.set_xlabel('epoch')
acc_ax.set_ylabel('accuracy')
** ro : red의 o모양
** bo : blue의 o모양
** Loss는 점점 줄어들고 Accuracy는 점점 증가한다.
- 전체 테스트 데이터를 가지고 예측
# Predict the labels of digit images in our test dataset.
predictions = model.predict(test_images)
# Then plot the first 25 test images and their predicted labels.
show_sample(test_images, ['Predicted: %d ' % np.argmax(result) for result in predictions])
** 테스트 이미지 1만개를 전부 예측하고, 그 중 제일 정확도가 높은 상위 25개만 표시한다.
** argmax() : 값이 높은 것을 찾아낸다.
Digit = 8448 #@param {type:"slider", min:1, max:10000, step:1}
selected_digit = Digit – 1
# 실제 리스트 상에서는 0번째이므로 -1로 계산해준다.
result = predictions[selected_digit]
result_number = np.argmax(result)
print('Number is %2d' % result_number)
show_digit_image(test_images[selected_digit])
기재: 본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
패스트캠퍼스 [직장인 실무교육]
프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.
fastcampus.co.kr
'패스트캠퍼스 챌린지' 카테고리의 다른 글
패스트캠퍼스 챌린지 49일차 (0) | 2022.03.13 |
---|---|
패스트캠퍼스 챌린지 48일차 (0) | 2022.03.12 |
패스트캠퍼스 챌린지 46일차 (0) | 2022.03.10 |
패스트캠퍼스 챌린지 45일차 (0) | 2022.03.09 |
패스트캠퍼스 챌린지 44일차 (0) | 2022.03.08 |