-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathagent.go
149 lines (125 loc) · 3.61 KB
/
agent.go
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
// Package reinforce is an agent implementation of the REINFORCE algorithm.
package reinforce
import (
"fmt"
"time"
"golang.org/x/exp/rand"
"github.com/aunum/gold/pkg/v1/dense"
"github.com/aunum/goro/pkg/v1/model"
"gonum.org/v1/gonum/stat/distuv"
agentv1 "github.com/aunum/gold/pkg/v1/agent"
"github.com/aunum/gold/pkg/v1/common/num"
envv1 "github.com/aunum/gold/pkg/v1/env"
"gorgonia.org/tensor"
)
// Agent is a dqn agent.
type Agent struct {
// Base for the agent.
*agentv1.Base
// Hyperparameters for the dqn agent.
*Hyperparameters
// Policy by which the agent acts.
Policy model.Model
// Memory of the agent.
Memory *Memory
env *envv1.Env
}
// Hyperparameters for the dqn agent.
type Hyperparameters struct {
// Gamma is the discount factor (0≤γ≤1). It determines how much importance we want to give to future
// rewards. A high value for the discount factor (close to 1) captures the long-term effective award, whereas,
// a discount factor of 0 makes our agent consider only immediate reward, hence making it greedy.
Gamma float32
}
// DefaultHyperparameters are the default hyperparameters.
var DefaultHyperparameters = &Hyperparameters{
Gamma: 0.99,
}
// AgentConfig is the config for a dqn agent.
type AgentConfig struct {
// Base for the agent.
Base *agentv1.Base
// Hyperparameters for the agent.
*Hyperparameters
// PolicyConfig for the agent.
PolicyConfig *PolicyConfig
}
// DefaultAgentConfig is the default config for a dqn agent.
var DefaultAgentConfig = &AgentConfig{
Hyperparameters: DefaultHyperparameters,
PolicyConfig: DefaultPolicyConfig,
Base: agentv1.NewBase("REINFORCE"),
}
// NewAgent returns a new dqn agent.
func NewAgent(c *AgentConfig, env *envv1.Env) (*Agent, error) {
if c == nil {
c = DefaultAgentConfig
}
if c.Base == nil {
c.Base = DefaultAgentConfig.Base
}
if env == nil {
return nil, fmt.Errorf("environment cannot be nil")
}
policy, err := MakePolicy(c.PolicyConfig, c.Base, env)
if err != nil {
return nil, err
}
return &Agent{
Base: c.Base,
Hyperparameters: c.Hyperparameters,
Memory: NewMemory(),
Policy: policy,
env: env,
}, nil
}
// Learn the agent.
func (a *Agent) Learn() error {
states, actions, rewards := a.Memory.Pop()
err := a.Policy.ResizeBatch(len(states))
if err != nil {
return err
}
// discount future rewards
discounted := make([]float32, len(rewards))
var running float32
for i := len(rewards) - 1; i >= 0; i-- {
running = rewards[i] + a.Gamma*running
discounted[i] = running
}
// normalize rewards
rewardsT := tensor.New(tensor.WithBacking(discounted))
rewardsNorm, err := dense.ZNorm(rewardsT)
if err != nil {
return err
}
// make advantage
advShape := []int{len(states)}
advShape = append(advShape, a.Policy.Y().Squeeze()...)
advantages := dense.Zeros(tensor.Float32, advShape...)
for i := 0; i < len(states); i++ {
advantages.SetAt(rewardsNorm.Get(i), i, int(actions[i]))
}
statesT, err := dense.Concat(0, states...)
if err != nil {
return err
}
err = a.Policy.FitBatch(statesT, advantages)
if err != nil {
return err
}
return nil
}
// Action selects the best known action for the given state.
func (a *Agent) Action(state *tensor.Dense) (action int, err error) {
actionProbsVal, err := a.Policy.Predict(state)
if err != nil {
return action, err
}
actionProbs := actionProbsVal.(*tensor.Dense)
// Get action as a random value of the probability distribution.
weights := num.F32SliceToF64(actionProbs.Data().([]float32))
dist := distuv.NewCategorical(weights, rand.NewSource(uint64(time.Now().UnixNano())))
action = int(dist.Rand())
return
}