MNIST Neural Network 뉴럴네트워크
MNIST Neural Network
# MNIST CNN
## 손글씨 데이터
## 0~9까지 0개 클래스로 분류
28*28 - 2차원으로
# 필요한 패키지 가져오기
import tensorflow as tf
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
import matplotlib.pyplot as plt
from tensorflow.keras.utils import to_categorical
# to_categorical 0~9까지 식별하는 분류기를 만들거면 노드 수를 10개. 0~9개 뽑아내는 것은 softmax 함수. 이걸 다 합치면 1
# 이미지 정보가 있고,9개 layer 중에서 한 개만 1 값이 주어지는 것이다. 이를 원핫인코딩이라고 부른다
# 이걸 해서 넣어줘야 한다. 케라스에는 투 카테고리 함수 이다
# 하이퍼 파라미터 설정
# 뉴럴테크워크. 이걸 1줄로 펴줘야 한다
batch_size = 128
num_classes = 10
epochs = 10
# 데이터 가져오기
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train.shape
x_test.shape
# 데이터 전처리
# 뉴럴테크워크. 이걸 1줄로 펴줘야 한다
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
y_train[:10]
# 데이터 10개만 보자
# 숫자 0은 원핫인코딩에서 9개 레이어 중에 값을 넣어줘야 한다
# 목표 변수 전처리 - one-hot 인코딩
# 원핫인코딩 할 값을 넣고, 클래스 갯수를 넣는다
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)
y_train.shape
y_train[0] #숫자 5가 이렇게 바뀌었다. 이걸 반드시 해줘야 한다
# 모형 구조 정의하기
# 시퀀셜 모델 만들었다.
# 첫번째 히든 레이어를 넣었다. 512개 짜리. 그 다음에 드룹아웃은? 20%는 랜덤하게 지우면서 해라
# 또 히든레이어 512개. 드롭아웃 20%
# 마지막. 아웃풋이 10개 이기 때문에
# 히든레이어 2개짜리 뉴럴네크워크 만든거다
# 들어오는게 784개 + 바이어스 1개 * 512개 = 401920
# 513[바이어스 1개 포함]*512
# 513 * 10 = 5130개
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
print(model.summary())
# 학습 정의하기
# 로스를 카테고리칼
model.compile(loss='categorical_crossentropy',
metrics=['accuracy'],
optimizer='adam')
# 학습하기
# .fit 학습
history = model.fit(x_train, y_train,
batch_size=batch_size, epochs=epochs,
verbose=1, validation_split=0.3)
# 성능 평가하기
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
score
# 첫번째가 스코어 두번째 로스값
#성능 그래프로 그리기
# graph
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epoch_range = range(1, len(acc) + 1)
epoch_range
plt.plot(epoch_range, loss, 'bo', label='Training loss')
plt.plot(epoch_range, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.figure()
plt.plot(epoch_range, acc, 'bo', label='Training acc')
plt.plot(epoch_range, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.figure()
MNIST Neural Network Lab
이미지 인식 CNN Lab
•cifar10훈련데이터를 이용해서 CNN 을 학습하시오
–네트워크 구조 , 학습 정의는 입력 노드수를 제외하고는 MNIST 사례와 동일하게 하시오
•학습된 인공신경망의 성능을 테스트집합을 통해서 확인하시오
•손실함수와 정확도를 그래프로 그리시오
# 필요한 패키지 가져오기
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
import matplotlib.pyplot as plt
from tensorflow.keras.utils import to_categorical
1. 다음 파이썬 코드를 이용해서 cifar10 데이터 집합을 읽어들이시오.
# 데이터 가져오기
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
from keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
2. 훈련데이터를 이용해서 인공신경망을 학습하시오.
- 네트워크 구조, 학습 정의는 입력 노드수를 제외하고는 MNIST 사례와 동일하게 하시오.
batch_size = 128
num_classes = 10
epochs = 10
x_train.shape
# 채널이 3개.
(50000, 32, 32, 3)
x_train[0]
# 0~255까지 값이 있다. 그래서 255로 나눠주는 것이다
x_train[0].max()
x_test.shape
10000, 32, 32, 3)
# 데이터 전처리
# 뉴럴테크워크. 이걸 1줄로 펴줘야 한다
x_train = x_train.reshape(50000, 3072)
# 이게 32 * 32 * 3 = 3072 그래서 이전과 숫자가 다르다
x_test = x_test.reshape(10000, 3072)
# 이게 32 * 32 * 3 = 3072 그래서 이전과 숫자가 다르다
x_train = x_train.astype('float32') # 실수로 변경
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
y_train.shape
(50000, 10)
y_train[0]
|
array([0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], dtype=float32) |
# 타겟에 대해서 원핫인코딩
# 숫자 0은 원핫인코딩에서 9개 레이어 중에 값을 넣어줘야 한다
# 목표 변수 전처리 - one-hot 인코딩
# 원핫인코딩 할 값을 넣고, 클래스 갯수를 넣는다
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)
# 클래스갯수는 똑같음
y_train.shape
(50000, 10)
y_train[0] #2차원 데이터
|
array([0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], dtype=float32) |
# 모형 구조 정의하기
# 시퀀셜 모델 만들었다.
# 첫번째 히든 레이어를 넣었다. 512개 짜리. 그 다음에 드룹아웃은? 20%는 랜덤하게 지우면서 해라
# 또 히든레이어 512개. 드롭아웃 20%
# 마지막. 아웃풋이 10개 이기 때문에
# 히든레이어 2개짜리 뉴럴네크워크 만든거다
# 들어오는게 784개 + 바이어스 1개 * 512개 = 401920
# 513[바이어스 1개 포함]*512
# 513 * 10 = 5130개
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(3072,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
print(model.summary())
# 학습 정의하기
# 로스를 카테고리칼
model.compile(loss='categorical_crossentropy',
metrics=['accuracy'],
optimizer='adam')
3. 학습된 인공신경망의 성능을 테스트 집합을 통해서 확인하시오.
# 학습하기
# .fit 학습
# 어큐러시가 너무 낮아서 40번 돌렸으나 별 차이가 없다
history = model.fit(x_train, y_train,
batch_size=batch_size, epochs=40,
verbose=1, validation_split=0.3)
# 성능 평가하기
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
4. 손실함수와 정확도를 그래프로 그리시오.
#성능 그래프로 그리기
# graph
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epoch_range = range(1, len(acc) + 1)
epoch_range
plt.plot(epoch_range, loss, 'bo', label='Training loss')
plt.plot(epoch_range, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.figure()
plt.plot(epoch_range, acc, 'bo', label='Training acc')
plt.plot(epoch_range, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.figure()