신경망 처음부터 끝까지 구현하기 06
def run_train(x, y):
y_hat, aux_nn_x = forward_neuralnet(x)
loss, aux_pp_diff = forward_postproc(y_hat, y)
accuracy = eval_accuracy(y_hat, y)
G_output = backprop_postproc(aux_pp_diff)
backprop_neuralnet(G_output, aux_nn_x)
return loss, accuracy
def run_test(x,y):
y_hat, _ = forward_neuralnet(x)
accuracy = eval_accuracy(y_hat, y)
return accuracy
def train_and_test(epoch_count, mb_size, report, train_ratio):
mini_batch_step_count = arrange_data(mb_size, train_ratio)
test_x, test_y = get_test_data()
losses_mean_row = []
accs_mean_row = []
for epoch in range(epoch_count):
losses = []
accs = []
for n in range(mini_batch_step_count):
train_x, train_y = get_train_data(mb_size, n)
loss, acc = run_train(train_x, train_y)
losses.append(loss)
accs.append(acc)
if report > 0 and (epoch + 1) % report == 0:
acc = run_test(test_x, test_y)
print("Epoch {} : Train - Loss = {:.3f}, Accuracy = {:.3f} / Test - Accuracy = {:.3f}".\
format(epoch + 1, np.mean(losses), np.mean(accs), acc))
losses_mean = np.mean(losses)
accs_mean = np.mean(accs) * 100
losses_mean_row.append(losses_mean)
accs_mean_row.append(accs_mean)
final_acc = run_test(test_x, test_y)
print("=" * 30, "Final TEST", "=" * 30)
print("\nFinal Accuracy : {:.3f}".format(final_acc))
return losses_mean_row, accs_mean_row, final_acc