본문 바로가기

Study/class note

딥러닝 / 2층 신경망을 텐서 플로우로 구현

문제133. 2층 신경망을 텐서 플로우로 구현하시오.

# 1. 필요한 패키지 가져오는 코드 

import tensorflow as tf   # 텐써 플로우 2.0 
from tensorflow.keras.datasets.mnist import load_data  # 텐써플로우에 내장되어있는 
                                                       # mnist 데이터를 가져온다.
from tensorflow.keras.models import Sequential  # 모델을 구성하기 위한 모듈
from tensorflow.keras.layers import Dense  # 완전 연결계층을 구성하기 위한 모듈
from tensorflow.keras.layers import Flatten 
from tensorflow.keras.utils import to_categorical # one encoding 하는 모듈

tf.random.set_seed(777)

(x_train, y_train), (x_test, y_test) = load_data(path='mnist.npz')  # mnist 데이터 로드
    
# 2. 정규화 진행  
# x_train = (x_train.reshape((60000, 28 * 28))) / 255 
# x_test = (x_test.reshape((10000, 28 * 28))) / 255

x_train = x_train/255
x_test = x_test/255

# 3. 정답 데이터를 준비한다. 

# 하나의 숫자를 one hot encoding 한다. (예:  4 ---> 0 0 0 0 1 0 0 0 0 0 ) 
y_train = to_categorical(y_train)  # 훈련 데이터의 라벨(정답)을 원핫 인코딩
y_test = to_categorical(y_test)    # 테스트 데이터의 라벨(정답)을 원핫 인코딩 

# 4. 모델을 구성합니다. 3층 신경망으로 구성
model = Sequential()
model.add(Flatten(input_shape=(28,28))) # 입력층(0층)
model.add(Dense(100, activation = 'sigmoid'))  #은닉층(1층)
model.add(Dense(10, activation = 'softmax'))  #출력층


# 5. 모델을 설정합니다. ( 경사하강법, 오차함수를 정의해줍니다. )
model.compile(optimizer='SGD', 
              loss = 'categorical_crossentropy', 
              metrics=['acc'])  # 학습과정에서 정확도를 보려고 

#6. 모델을 훈련시킵니다. 
history = model.fit(x_train, y_train, 
                    epochs = 30,  # 30에폭
                    batch_size = 100)

# 7.모델을 평가합니다. (오차, 정확도가 출력됩니다.)
model.evaluate(x_test, y_test)  #[0.3085502088069916, 0.9143999814987183]

 

 

문제134. 위의 2층 신경망을 3층으로 구현하시오.

# 1. 필요한 패키지 가져오는 코드 

import tensorflow as tf   # 텐써 플로우 2.0 
from tensorflow.keras.datasets.mnist import load_data  # 텐써플로우에 내장되어있는 
                                                       # mnist 데이터를 가져온다.
from tensorflow.keras.models import Sequential  # 모델을 구성하기 위한 모듈
from tensorflow.keras.layers import Dense  # 완전 연결계층을 구성하기 위한 모듈
from tensorflow.keras.layers import Flatten 
from tensorflow.keras.utils import to_categorical # one encoding 하는 모듈

tf.random.set_seed(777)

(x_train, y_train), (x_test, y_test) = load_data(path='mnist.npz')  # mnist 데이터 로드
    
# 2. 정규화 진행  
# x_train = (x_train.reshape((60000, 28 * 28))) / 255 
# x_test = (x_test.reshape((10000, 28 * 28))) / 255

x_train = x_train/255
x_test = x_test/255

# 3. 정답 데이터를 준비한다. 

# 하나의 숫자를 one hot encoding 한다. (예:  4 ---> 0 0 0 0 1 0 0 0 0 0 ) 
y_train = to_categorical(y_train)  # 훈련 데이터의 라벨(정답)을 원핫 인코딩
y_test = to_categorical(y_test)    # 테스트 데이터의 라벨(정답)을 원핫 인코딩 

# 4. 모델을 구성합니다. 3층 신경망으로 구성
model = Sequential()
model.add(Flatten(input_shape=(28,28))) # 입력층(0층)
model.add(Dense(50, activation = 'sigmoid'))  #은닉층(1층)
model.add(Dense(50, activation = 'sigmoid'))  #은닉층(2층)
model.add(Dense(10, activation = 'softmax'))  #출력층


# 5. 모델을 설정합니다. ( 경사하강법, 오차함수를 정의해줍니다. )
model.compile(optimizer='SGD', 
              loss = 'categorical_crossentropy', 
              metrics=['acc'])  # 학습과정에서 정확도를 보려고 

#6. 모델을 훈련시킵니다. 
history = model.fit(x_train, y_train, 
                    epochs = 30,  # 30에폭
                    batch_size = 100)

# 7.모델을 평가합니다. (오차, 정확도가 출력됩니다.)
model.evaluate(x_test, y_test)  #[0.3981786072254181, 0.8894000053405762]

 

 

문제135. 날코딩 신경망과 비슷한 정확도가 나오려면 날코딩에서 했던 것처럼 러닝레이트를 0.1로 하고 수행하시오.

# 1. 필요한 패키지 가져오는 코드 

import tensorflow as tf   # 텐써 플로우 2.0 
from tensorflow.keras.datasets.mnist import load_data  # 텐써플로우에 내장되어있는 
                                                       # mnist 데이터를 가져온다.
from tensorflow.keras.models import Sequential  # 모델을 구성하기 위한 모듈
from tensorflow.keras.layers import Dense  # 완전 연결계층을 구성하기 위한 모듈
from tensorflow.keras.layers import Flatten 
from tensorflow.keras.utils import to_categorical # one encoding 하는 모듈

tf.random.set_seed(777)

(x_train, y_train), (x_test, y_test) = load_data(path='mnist.npz')  # mnist 데이터 로드
    
# 2. 정규화 진행  
# x_train = (x_train.reshape((60000, 28 * 28))) / 255 
# x_test = (x_test.reshape((10000, 28 * 28))) / 255

x_train = x_train/255
x_test = x_test/255

# 3. 정답 데이터를 준비한다. 

# 하나의 숫자를 one hot encoding 한다. (예:  4 ---> 0 0 0 0 1 0 0 0 0 0 ) 
y_train = to_categorical(y_train)  # 훈련 데이터의 라벨(정답)을 원핫 인코딩
y_test = to_categorical(y_test)    # 테스트 데이터의 라벨(정답)을 원핫 인코딩 

# 4. 모델을 구성합니다. 3층 신경망으로 구성
model = Sequential()
model.add(Flatten(input_shape=(28,28))) # 입력층(0층)
model.add(Dense(50, activation = 'sigmoid'))  #은닉층(1층)
model.add(Dense(50, activation = 'sigmoid'))  #은닉층(2층)
model.add(Dense(10, activation = 'softmax'))  #출력층


# 5. 모델을 설정합니다. ( 경사하강법, 오차함수를 정의해줍니다. )
model.compile(optimizer='SGD', 
              loss = 'categorical_crossentropy', 
              metrics=['acc'])  # 학습과정에서 정확도를 보려고 

#6. 모델을 훈련시킵니다. 
# learning rate
from tensorflow.keras  import   backend  as  K  # 텐써 플로우를 사용하지 않았을때의 코드로 구현할 수
                                                                # 있게 하는 코드 
K.set_value( model.optimizer.learning_rate, 0.1 ) # 러닝레이트를 0.01 로 하겠다
print ("Learning rate before second fit:" , model.optimizer.learning_rate.numpy()  )

history = model.fit(x_train, y_train, 
                    epochs = 30,  # 30에폭
                    batch_size = 100)

# 7.모델을 평가합니다. (오차, 정확도가 출력됩니다.)
model.evaluate(x_test, y_test)  #[0.1341455727815628, 0.9610000252723694]

 

 

문제136. 날코딩 했을때처럼 훈련데이터와 테스트데이터의 정확도를 시각화하시오.

train_acc_list = history.history['acc']
test_acc_list = history.history['val_acc']

import matplotlib.pyplot as plt

x = np.arange(len(train_acc_list))

plt.plot(x, train_acc_list, label = 'train_acc')
plt.plot(x, test_acc_list, label = 'test_acc')

plt.ylim(0.8,1)
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.legend()
plt.show()

 

 

반응형