레이어가 늘어날수록 웨이팅계수가 많아지기때문에 시간이 더 오래걸림
## 3-1
from keras.datasets import imdb
(train_data, train_labels),(test_data, test_labels) = imdb.load_data(num_words=10000)
## 3-2
import numpy as np
def vectorize_sequences(sequences, dimension=10000):
# 크기가 (len(sequences), dimension)) 이고 모든 원소가 0인 행렬을 만듦
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences) :
results[i, sequence] = 1. # result[i]에서 특정 인덱스의 위치를 1로 만듦
return results
# 훈련 데이터를 벡터로 변환
x_train = vectorize_sequences(train_data)
# 테스트 데이터를 벡터로 변환
x_test = vectorize_sequences(test_data)
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')
## 3-3 모델 정의하기
from keras import models
from keras import layers
model = models.Sequential()
Smallermodel = models.Sequential()
Biggermodel = models.Sequential()
## 3-3
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
## 4-4
Smallermodel.add(layers.Dense(6, activation='relu', input_shape=(10000,))) ## 16에서 6으로 축소됨!
Smallermodel.add(layers.Dense(6, activation='relu'))
Smallermodel.add(layers.Dense(1, activation='sigmoid'))
## 4-5
Biggermodel.add(layers.Dense(1024, activation='relu', input_shape=(10000,))) ## 16에서 6으로 축소됨!
Biggermodel.add(layers.Dense(1024, activation='relu'))
Biggermodel.add(layers.Dense(1, activation='sigmoid'))
## 3-4 모델 컴파일 하기
model.compile(optimizer = 'rmsprop',
loss = 'binary_crossentropy',
metrics=['accuracy'])
## overfitting 을 막기위해 축소된 모델
Smallermodel.compile(optimizer = 'rmsprop',
loss = 'binary_crossentropy',
metrics=['accuracy'])
Biggermodel.compile(optimizer = 'rmsprop',
loss = 'binary_crossentropy',
metrics=['accuracy'])
## 3-5 옵티마이저 설정하기
from keras import optimizers
model.compile(optimizer = optimizers.RMSprop(lr=0.001),
loss = 'binary_crossentropy',
metrics=['accuracy'])
## 3-6 손실과 측정을 함수 객체로 지정하기
from keras import losses
from keras import metrics
model.compile(optimizer=optimizers.RMSprop(lr=0.001),
loss = losses.binary_crossentropy,
metrics=[metrics.binary_accuracy])
## 3-7 검증 세트 준비하기
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val=y_train[:10000]
partial_y_train = y_train[10000:]
## 3-8 모델 훈련하기
#model.compile(optimizer='rmsprop',
# loss = 'binary_crossentropy',
# metrics=['acc'])
history = model.fit(partial_x_train,
partial_y_train,
epochs=20,
batch_size=512,
validation_data = (x_val, y_val))
SmallerHistory = Smallermodel.fit(partial_x_train,
partial_y_train,
epochs=20,
batch_size=512,
validation_data = (x_val, y_val))
BiggerHistory = Biggermodel.fit(partial_x_train,
partial_y_train,
epochs=20,
batch_size=512,
validation_data = (x_val, y_val))
## 3-9 훈련과 검증손실 그리기
import matplotlib.pyplot as plt
history_dict = history.history
history_dict2 = SmallerHistory.history
history_dict3 = BiggerHistory.history
#loss = history_dict['loss']
val_loss = history_dict['val_loss']
val_loss_small = history_dict2['val_loss']
val_loss_big = history_dict3['val_loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, val_loss, '+', label = 'Original model') ## 'bo'는 파란색 점을 의미함
plt.plot(epochs, val_loss_small, 'bo', label = 'Small model')
plt.plot(epochs, val_loss_big, '*', label = 'Big model')
plt.title('Comparison Original,Bigger,Smaller')
plt.xlabel('Epochs')
plt.ylabel('Validation loss')
plt.legend()
plt.show()
'딥러닝' 카테고리의 다른 글
0806 합성곱 신경망 (0) | 2019.08.06 |
---|---|
0806 +) 가중치규제, 드롭아웃 (0) | 2019.08.06 |
0805 Tesorflow GPU 설정을 위한 환경 만들기 (0) | 2019.08.05 |
0805 신경망의 구조 - 용어들의 의미 (0) | 2019.08.05 |
0805 CNN익히기 (0) | 2019.08.05 |