Beispiel #1
0
def maxQvalue(screen, isFile, model0, model1, last0, last1, option):

    # 새로운 상태(=s')에서 각 행동 a'를 취했을 때의 보상값 Q(s', a') 구하기
    if isFile:
        if option % 3 == 0 or option % 3 == 1:
            Qvalues = Qlearning_deep_GPU.modelOutput(model0, [screen])
        elif option % 3 == 2:
            Qvalues = Qlearning_deep_GPU.modelOutput(model1, [screen])
    else:
        return 0

    # 그 보상값의 최댓값 반환
    if option % 3 == 2: return max(Qvalues[last1][0])
    return max(Qvalues[last0][0])
Beispiel #2
0
def getQvalues(screen, isFile, model0, model1, last0, last1, func0, actions,
               option):

    # 각 action에 대해 Q(s, a)의 값 구하기
    if isFile:
        if option % 3 == 0 or option % 3 == 1:
            Qvalues = Qlearning_deep_GPU.modelOutput(
                model0, [screen])  # 이미 flatten된 screen임
            if option % 3 == 0:
                print('Qval of decision whose next state is above:\n' +
                      str(Qvalues[last0][0]) + '\n\n')
            return Qvalues[last0][0]
        elif option % 3 == 2:
            Qvalues = Qlearning_deep_GPU.modelOutput(model1, [screen])
            print('Qval of decision whose next state is above:\n' +
                  str(Qvalues[last1][0]) + '\n\n')
            return Qvalues[last1][0]

    else:
        return [func0] * actions
                        Qlearning_deep_GPU.deepQlearning(0, NN, op, lc, inputs, outputs, None, None, 'WPCNdeep', [epoc, None], None, None, False, False, True, deviceName)

                        # 6. 테스트 결과 확인하고 정답과 비교하기
                        newModel = Qlearning_deep_GPU.deepLearningModel('WPCNdeep_0', False)
                        sumTestThroughput = 0.0 # test throughput의 합계
                        sumCorrectMaxThroughput = 0.0 # 정답의 throughput의 합계 (training data를 생성할 때와 같은 방법으로 최대 throughput 확인)

                        optiInfo = open('optiInfo_' + str(problemNo) + '.txt', 'r')
                        optiInformation = optiInfo.readlines()
                        optiInfo.close()

                        print('testing...')
                        
                        for i in range(numTest):
                            testScreen = originalScreen[numTrain + i] # 테스트할 스크린
                            testOutput = Qlearning_deep_GPU.modelOutput(newModel, [testScreen]) # 테스트 결과
                            testOutputLayer = testOutput[len(testOutput)-1] # 테스트 결과의 output layer의 값

                            # 6-0. 테스트 결과 확인
                            # 출력값 받아오기
                            optiY_test = Qlearning_deep_GPU_helper.invSigmoid(testOutputLayer[0][0], size-1) # 테스트 결과로 나온 throughput 최대화 y좌표
                            optiX_test = Qlearning_deep_GPU_helper.invSigmoid(testOutputLayer[0][1], size-1) # 테스트 결과로 나온 throughput 최대화 x좌표

                            # 출력값 중 HAP의 좌표를 정수로 조정
                            optiY_test = int(round(optiY_test, 0))
                            if optiY_test >= size: optiY_test = size-1
                            elif optiY_test < 0: optiY_test = 0
                            
                            optiX_test = int(round(optiX_test, 0))
                            if optiX_test >= size: optiX_test = size-1
                            elif optiX_test < 0: optiX_test = 0
Beispiel #4
0
                        newModel1 = Qlearning_deep_GPU.deepLearningModel('WPCNdeepNN1_0', False)
                        newModel2 = Qlearning_deep_GPU.deepLearningModel('WPCNdeepNN2_0', False)
                        
                        sumTestThroughput = 0.0 # test throughput의 합계
                        sumCorrectMaxThroughput = 0.0 # 정답의 throughput의 합계 (training data를 생성할 때와 같은 방법으로 최대 throughput 확인)

                        optiInfo = open('optiInfo_' + str(problemNo) + '.txt', 'r')
                        optiInformation = optiInfo.readlines()
                        optiInfo.close()

                        print('testing...')
                        
                        for i in range(numTest):
                            testScreen = originalScreen[numTrain + i] # 테스트할 스크린
                            
                            testOutput0 = Qlearning_deep_GPU.modelOutput(newModel0, [testScreen]) # 테스트 결과
                            testOutput1 = Qlearning_deep_GPU.modelOutput(newModel1, [testScreen]) # 테스트 결과
                            testOutput2 = Qlearning_deep_GPU.modelOutput(newModel2, [testScreen]) # 테스트 결과
                            
                            testOutput0Layer = testOutput0[len(testOutput0)-1] # 테스트 결과의 output layer의 값
                            testOutput1Layer = testOutput1[len(testOutput1)-1] # 테스트 결과의 output layer의 값
                            testOutput2Layer = testOutput2[len(testOutput2)-1] # 테스트 결과의 output layer의 값

                            # 6-0. 테스트 결과 확인
                            # 출력값 받아오기
                            optiY_test0 = Qlearning_deep_GPU_helper.invSigmoid(testOutput0Layer[0][0], size-1) # 테스트 결과로 나온 throughput 최대화 y좌표
                            optiX_test0 = Qlearning_deep_GPU_helper.invSigmoid(testOutput0Layer[0][1], size-1) # 테스트 결과로 나온 throughput 최대화 x좌표

                            optiY_test1 = Qlearning_deep_GPU_helper.invSigmoid(testOutput1Layer[0][0], size-1) # 테스트 결과로 나온 throughput 최대화 y좌표
                            optiX_test1 = Qlearning_deep_GPU_helper.invSigmoid(testOutput1Layer[0][1], size-1) # 테스트 결과로 나온 throughput 최대화 x좌표
        Qlearning_deep_GPU.deepQlearning(i, NN, op, 'mean_squared_error',
                                         states, outputs, Qdiff, 25,
                                         'test' + str(i), [20, 25],
                                         [8, 'sigmoid', 'sigmoid'],
                                         [6, 'sigmoid', 'sigmoid'], True, True,
                                         False, deviceName)

        # test
        print('\n ' + ('#===' * 16) + ' <<<< option:' + str(i) +
              ' TEST >>>> ' + ('===#' * 16) + '\n')

        if i % 3 == 0 or i % 3 == 1:
            print('\n << test output (첫번째 Neural Network) >>\n')
            newModel = Qlearning_deep_GPU.deepLearningModel(
                'test' + str(i) + '_0', False)
            testOutput = Qlearning_deep_GPU.modelOutput(
                newModel, [[4, 2.5], [6, 3.5], [7, 4.5]])
            print('\n[[4, 2.5], [6, 3.5], [7, 4.5]]에 대한 학습 결과:\n')

            for j in range(len(testOutput)):
                print(' << layer No: ' + str(j) + ' >>')
                print(str(testOutput[j]))

        if i % 3 == 1 or i % 3 == 2:
            print('\n << test output (두번째(또는 Dueling) Neural Network) >>\n')
            newModel = Qlearning_deep_GPU.deepLearningModel(
                'test' + str(i) + '_1', False)
            testOutput = Qlearning_deep_GPU.modelOutput(
                newModel, [[4, 2.5], [6, 3.5], [7, 4.5]])
            print('\n[[4, 2.5], [6, 3.5], [7, 4.5]]에 대한 학습 결과:\n')

            for j in range(len(testOutput)):
Beispiel #6
0
def decideAction(option, screen, screenCopy, point, additional, isFile, model0,
                 model1, last0, last1, gameNo, charSize, actions, exceedValue,
                 charValue, randomProb_, feasible_, getNextState_):

    screenSize = len(screen)  # screen의 가로/세로 길이
    learningSize = int(math.sqrt(
        len(screenCopy)))  # learningSize (screen의 캐릭터 주변부의 가로/세로 길이)

    around = int((learningSize - charSize) / 2)  # 캐릭터 주변 8방향으로 몇 칸까지 볼 것인가?
    charRadius = int((charSize - 1) / 2)  # 캐릭터의 중심점에서 주변 8방향으로 몇 칸까지 캐릭터인가?

    # 랜덤하게 실행
    if random.random() < randomProb_(gameNo, option):
        print('랜덤하게 행동 실행')
        while (1):
            action = random.randint(0, actions - 1)
            if feasible_(screen, action, additional, point): return action

    # 각 action에 대해 Q(s, a)의 값 구하기
    if isFile:
        # 기본 DQN
        # Q(s_t, a_t)에 대하여 a_t 값을 구해야 하므로 현재 상태인 screenCopy를 이용
        if option % 3 == 0:
            Qvalues = Qlearning_deep_GPU.modelOutput(model0, [screenCopy])

            # Double DQN
        elif option % 3 == 1:
            Qvalues = [-1000000] * actions

            for action in range(actions):  # 각 행동에 대하여

                # 다음 상태인 newScreen 구하기
                newScreen = getNextState_(screen, action)
                if newScreen == None:  # 다음 상태가 없으면(해당 action 실행 결과 index 오류 발생) 고려하지 않기
                    Qvalues[action] == -1000000
                    continue

                newPoint = [-1, -1]

                # newScreen에서 캐릭터의 위치 찾기
                for i in range(screenSize):
                    broken = False
                    for j in range(screenSize):
                        if newScreen[i][j] == charValue:
                            newPoint = [i + charRadius,
                                        j + charRadius]  # 캐릭터의 중심점
                            broken = True
                            break
                    if broken: break

                # newScreen에서 캐릭터 주변만 추출하기
                newScreenCopy = []
                for i in range(newPoint[0] - charRadius - around,
                               newPoint[0] + charRadius + around + 1):
                    for j in range(newPoint[1] - charRadius - around,
                                   newPoint[1] + charRadius + around + 1):
                        # 가능한 범위를 넘어서는 경우 exceedValue를 적용
                        if exceed(newScreen, i, j):
                            newScreenCopy.append(exceedValue)
                        else:
                            newScreenCopy.append(newScreen[i][j])

                # model 0에 대한 Q value (action별 reward)
                # Q(s_(t+1), ...)에서 상태가 s_(t+1)이므로 다음 상태인 newScreen을 이용
                Qvalues0 = Qlearning_deep_GPU.modelOutput(
                    model0, [newScreenCopy])

                # model 1에 대한 Q value (reward가 가장 큰 action만 one-hot으로 1임)
                # Q(s_(t+1), argmax(a)Q(s_(t+1), a))에서 상태가 s_(t+1)이므로 newScreen을 이용
                Qvalues1 = Qlearning_deep_GPU.modelOutput(
                    model1, [newScreenCopy])

                # Qvalues1 으로부터 argmax(a)Q(s_(t+1), a)) 구하기
                argmaxA = -1
                for i in range(len(Qvalues1[last0][0])):
                    if Qvalues1[last0][0][i] == max(Qvalues1[last0][0]):
                        argmaxA = i
                        break

                # Qvalues0 으로부터 Q(s_(t+1), argmax(a)Q(s_(t+1), a))의 값 = Qvalue0[argmaxA] 구하기
                Qvalues[action] = Qvalues0[last0][0][argmaxA]

        # Dueling Network
        elif option % 3 == 2:
            Qvalues = Qlearning_deep_GPU.modelOutput(model1, [screenCopy])

    else:
        while (1):
            action = random.randint(0, actions - 1)
            if feasible_(screen, action, additional, point): return action

    if option % 3 == 1:
        print('final Qvalues (below is result of action made by them):',
              Qvalues)

    # 실행할 수 없는 action을 제거
    for i in range(actions):
        if not feasible_(screen, i, additional, point):
            if option % 3 == 1: Qvalues[i] = -1000000
            elif option % 3 == 2: Qvalues[last1][0][i] = -1000000
            else: Qvalues[last0][0][i] = -1000000

    # 보상값이 최대인 행동을 반환
    if option % 3 == 1:
        for i in range(actions):
            if Qvalues[i] == max(Qvalues): return i
    elif option % 3 == 2:
        for i in range(actions):
            if Qvalues[last1][0][i] == max(Qvalues[last1][0]): return i
    else:
        for i in range(actions):
            if Qvalues[last0][0][i] == max(Qvalues[last0][0]): return i