-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlearning_world_model.py
More file actions
56 lines (39 loc) · 1.53 KB
/
learning_world_model.py
File metadata and controls
56 lines (39 loc) · 1.53 KB
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
class LearningWorldModel:
"""
Learns environment dynamics from experience.
"""
def __init__(self):
# (state, action) -> observed next state samples
self.memory = []
# simple learned weights (placeholder model)
self.weights = {
"move": -0.05,
"interact": -0.1,
"idle": 0.01
}
# =====================================================
# PREDICT
# =====================================================
def predict(self, state, action):
new_state = state.copy()
delta = self.weights.get(action, 0)
new_state["energy"] = state.get("energy", 1.0) + delta
return new_state
# =====================================================
# OBSERVE REAL RESULT
# =====================================================
def observe(self, state, action, next_state):
self.memory.append((state, action, next_state))
if len(self.memory) > 1000:
self.memory.pop(0)
self._update_model()
# =====================================================
# LEARNING STEP
# =====================================================
def _update_model(self):
# very simplified learning rule
for state, action, next_state in self.memory[-50:]:
predicted = self.predict(state, action)
error = next_state["energy"] - predicted["energy"]
# gradient-like update
self.weights[action] = self.weights.get(action, 0) + 0.01 * error