-
Notifications
You must be signed in to change notification settings - Fork 9
/
QLearning.swift
executable file
·63 lines (41 loc) · 1.73 KB
/
QLearning.swift
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
//
// QLearning.swift
// ReinforcementLearning
//
// Created by Adnan Zahid on 12/30/16.
// Copyright © 2016 Adnan Zahid. All rights reserved.
//
import Foundation
class QLearning {
static func updateQValues(box: Box, newBox: Box, direction: Direction) {
var updatablePortion: Portion
if direction == Direction.Left {
updatablePortion = box.portions[0]
} else if direction == Direction.Right {
updatablePortion = box.portions[1]
} else if direction == Direction.Down {
updatablePortion = box.portions[2]
} else {
updatablePortion = box.portions[3]
}
// updatablePortion.qValue = (1 - updatablePortion.learning) * updatablePortion.qValue + updatablePortion.learning * (rewardForEachState + discountFactor * newBox.value)
let changeInQValue: Double = (newBox.value - updatablePortion.qValue) * updatablePortion.learning
updatablePortion.qValue += changeInQValue
/**
* If and only if changeInQValue is greater than zero
*/
if changeInQValue > 0 {
/**
* Decrease Q Learning value over time for less learning rate (for convergence of values)
*/
updatablePortion.learning *= 1.0 - (changeInQValue * 0.99999)
}
var maxQValue: Double = 0.0
for portion in box.portions {
maxQValue = max(maxQValue, portion.qValue)
}
box.value = maxQValue
box.preferenceValue *= 0.9
box.traversed = true
}
}