forked from zemlyansky/ppo-tfjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
108 lines (103 loc) · 2.67 KB
/
test.js
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
const tf = require('@tensorflow/tfjs-node-gpu');
const PPO = require('./dist/ppo.js');
console.log(PPO);
class EnvDiscrete {
constructor() {
this.actionSpace = {
'class': 'Discrete',
'n': 4
}
this.observationSpace = {
'class': 'Box',
'shape': [2],
'dtype': 'float32'
}
}
async step(action) {
switch (action) {
case 0:
this.state[1] -= 0.01
break
case 1:
this.state[1] += 0.01
break
case 2:
this.state[0] -= 0.01
break
case 3:
this.state[0] += 0.01
break
}
this.i += 1
var reward = -Math.sqrt(this.state[0] * this.state[0] + this.state[1] * this.state[1])
var done = this.i > 100 || reward > -0.01
if (reward > -0.01) {
console.log('Goal reached:', this.state)
}
return [this.state.slice(0), reward, done]
}
reset() {
this.state = [
Math.random() - 0.5,
Math.random() - 0.5,
]
this.i = 0
return this.state.slice(0)
}
}
class EnvContinuous {
constructor() {
this.actionSpace = {
'class': 'Box',
'shape': [2],
}
this.observationSpace = {
'class': 'Box',
'shape': [2],
'dtype': 'float32'
}
}
async step(action) {
this.state[0] += action[0] * 0.1
this.state[1] += action[1] * 0.1
this.i += 1
var reward = -Math.sqrt(this.state[0] * this.state[0] + this.state[1] * this.state[1])
var done = this.i > 100 || reward > -0.01
if (reward > -0.01) {
console.log('Goal reached:', this.state)
}
return [this.state.slice(0), reward, done]
}
reset() {
this.state = [
Math.random() - 0.5,
Math.random() - 0.5,
]
this.i = 0
return this.state.slice(0)
}
}
test('PPO Learn (Discrete)', async () => {
var env = new EnvDiscrete()
var ppo = new PPO(env, {'nSteps': 50})
await ppo.learn({
'totalTimesteps': 100,
'callback': {
'onTrainingStart': function (p) {
console.log(p.config)
}
}
})
})
test('PPO Learn (Continuos)', async () => {
var env = new EnvContinuous()
var ppo = new PPO(env, {'nSteps': 50})
await ppo.learn({
'totalTimesteps': 100,
'callback': {
'onTrainingStart': function (p) {
console.log(p.config)
}
}
})
})