■ 순환 신경망을 만드는 방법을 보여준다.
▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
import keras.callbacks as callbacks import keras.models as models import keras.layers as layers import keras.utils as utils import matplotlib.pyplot as pp import numpy as np np.random.seed(5) # 손실 이력 클래스를 정의한다. class LossHistory(callbacks.Callback): def init(self): self.lossList = [] def on_epoch_end(self, batch, logDictionary = {}): self.lossList.append(logDictionary.get("loss")) # 특징 리스트 구하기 함수를 정의한다. def GetFeatureList(code): featureList = [] featureList.append(scaleDictionary[code[0]] / float(maximumScale)) featureList.append(lengthDictionary[code[1]]) return featureList # 소스 ND 배열 구하기 함수를 정의한다. def GetSourceNDArray(sourceList, windowSize): targetInputList = [] targetCorrectOutputList = [] for i in range(len(sourceList) - windowSize): subsetList = sourceList[i:(i + windowSize + 1)] for j in range(len(subsetList) - 1): featureList = GetFeatureList(subsetList[j]) targetInputList.append(featureList) targetCorrectOutputList.append([codeDictionary[subsetList[windowSize]]]) return np.array(targetInputList), np.array(targetCorrectOutputList) print("데이터 로드를 시작합니다.") maximumScale = 6.0 scaleDictionary = {"c" : 0, "d" : 1, "e" : 2, "f" : 3, "g" : 4, "a" : 5, "b" : 6} lengthDictionary = {"4" : 0, "8" : 1} codeDictionary = {"c4" : 0, "d4" : 1, "e4" : 2, "f4" : 3 , "g4" : 4 , "a4" : 5 , "b4" : 6, "c8" : 7, "d8" : 8, "e8" : 9, "f8" : 10, "g8" : 11, "a8" : 12, "b8" : 13} indexDictionary = {0 : "c4", 1 : "d4", 2 : "e4", 3 : "f4", 4 : "g4", 5 : "a4", 6 : "b4", 7 : "c8", 8 : "d8", 9 : "e8", 10 : "f8", 11 : "g8", 12 : "a8", 13 : "b8"} sequenceList = ["g8", "e8", "e4", "f8", "d8", "d4", "c8", "d8", "e8", "f8", "g8", "g8", "g4", "g8", "e8", "e8", "e8", "f8", "d8", "d4", "c8", "e8", "g8", "g8", "e8", "e8", "e4", "d8", "d8", "d8", "d8", "d8", "e8", "f4", "e8", "e8", "e8", "e8", "e8", "f8", "g4", "g8", "e8", "e4", "f8", "d8", "d4", "c8", "e8", "g8", "g8", "e8", "e8", "e4"] trainInputNDArray, trainCorrectOutputNDArray = GetSourceNDArray(sequenceList, windowSize = 4) trainInputNDArray = np.reshape(trainInputNDArray, (50, 4, 2)) trainCorrectOutputNDArray = utils.np_utils.to_categorical(trainCorrectOutputNDArray) outputNodeCount = trainCorrectOutputNDArray.shape[1] print("데이터 로드를 종료합니다.") print("모델 정의를 시작합니다.") model = models.Sequential() model.add(layers.LSTM(128, batch_input_shape = (1, 4, 2), stateful = True)) model.add(layers.Dense(outputNodeCount, activation = "softmax")) model.compile(loss = "categorical_crossentropy", optimizer = "adam", metrics = ["accuracy"]) print("모델 정의를 종료합니다.") print("모델 학습을 시작합니다.") epochCount = 2000 history = LossHistory() history.init() for epochIndex in range(epochCount): print("epoch : " + str(epochIndex)) model.fit(trainInputNDArray, trainCorrectOutputNDArray, epochs = 1, batch_size = 1, verbose = 2, shuffle = False, callbacks = [history]) model.reset_states() pp.plot(history.lossList) pp.ylabel("loss") pp.xlabel("epoch") pp.legend(["train"], loc = "upper left") pp.show() print("모델 학습을 종료합니다.") print("모델 평가를 시작합니다.") evaluationList = model.evaluate(trainInputNDArray, trainCorrectOutputNDArray, batch_size = 1) print("%s : %.2f%%" %(model.metrics_names[1], evaluationList[1] * 100)) model.reset_states() print("모델 평가를 종료합니다.") print("모델 사용을 시작합니다.") predictionCount = 50 print("한 스텝 예측을 시작합니다.") resultSequenceList = ["g8", "e8", "e4", "f8"] predictionNDArray = model.predict(trainInputNDArray, batch_size = 1) for i in range(predictionCount): index = np.argmax(predictionNDArray[i]) resultSequenceList.append(indexDictionary[index]) model.reset_states() print("한 스텝 예측 : ", resultSequenceList) print("한 스텝 예측을 종료합니다.") print("곡 전체 예측을 시작합니다.") inputSequenceList = ["g8", "e8", "e4", "f8"] resultSequenceList = inputSequenceList inputSequenceFeatureList = [] for inputSequenceItem in inputSequenceList: featureList = GetFeatureList(inputSequenceItem) inputSequenceFeatureList.append(featureList) for i in range(predictionCount): inputSequenceNDArray = np.array(inputSequenceFeatureList) inputSequenceNDArray = np.reshape(inputSequenceNDArray, (1, 4, 2)) # 샘플 수, 타임 스텝 수, 속성 수 predictionNDArray = model.predict(inputSequenceNDArray) index = np.argmax(predictionNDArray) resultSequenceList.append(indexDictionary[index]) featureList = GetFeatureList(indexDictionary[index]) inputSequenceFeatureList.append(featureList) inputSequenceFeatureList.pop(0) model.reset_states() print("곡 전체 예측 : ", resultSequenceList) print("곡 전체 예측을 종료합니다.") |