vincentiusyoshuac commited on
Commit
e25b866
·
verified ·
1 Parent(s): c9387f0

Update network.py

Browse files
Files changed (1) hide show
  1. network.py +43 -38
network.py CHANGED
@@ -1,19 +1,19 @@
1
- # cognitive_net/network.py
2
  import torch
3
  import torch.nn as nn
4
  import torch.optim as optim
5
  import math
6
- from typing import Dict, List, Optional
 
7
  from .node import CognitiveNode
8
 
9
  class DynamicCognitiveNet(nn.Module):
10
- """Self-organizing neural architecture with structural plasticity"""
11
  def __init__(self, input_size: int, output_size: int):
12
  super().__init__()
13
  self.input_size = input_size
14
  self.output_size = output_size
15
 
16
- # Neural population
17
  self.input_nodes = nn.ModuleList([
18
  CognitiveNode(i, 1) for i in range(input_size)
19
  ])
@@ -21,31 +21,31 @@ class DynamicCognitiveNet(nn.Module):
21
  CognitiveNode(input_size + i, 1) for i in range(output_size)
22
  ])
23
 
24
- # Structural configuration
25
- self.connections: Dict[str, nn.Parameter] = nn.ParameterDict()
26
  self._init_base_connections()
27
 
28
- # Meta-learning components
29
  self.emotional_state = nn.Parameter(torch.tensor(0.0))
30
  self.optimizer = optim.AdamW(self.parameters(), lr=0.001)
31
  self.loss_fn = nn.MSELoss()
32
 
33
  def _init_base_connections(self):
34
- """Initialize sparse input-output connectivity"""
35
- for i, in_node in enumerate(self.input_nodes):
36
- for j, out_node in enumerate(self.output_nodes):
37
  conn_id = f"{in_node.id}->{out_node.id}"
38
  self.connections[conn_id] = nn.Parameter(
39
  torch.randn(1) * 0.1
40
  )
41
 
42
  def forward(self, x: torch.Tensor) -> torch.Tensor:
43
- # Input processing
44
  activations = {}
45
  for i, node in enumerate(self.input_nodes):
46
  activations[node.id] = node(x[i].unsqueeze(0))
47
 
48
- # Output integration
49
  outputs = []
50
  for out_node in self.output_nodes:
51
  integrated = []
@@ -58,58 +58,63 @@ class DynamicCognitiveNet(nn.Module):
58
  combined = sum(integrated) / math.sqrt(len(integrated))
59
  outputs.append(out_node(combined))
60
 
61
- return torch.cat(outputs)
62
 
63
  def structural_update(self, global_reward: float):
64
- """Evolutionary architecture modification"""
65
- # Connection strength adaptation
66
- for conn_id, weight in self.connections.items():
67
- if global_reward > 0:
68
- new_weight = weight + 0.1 * global_reward
69
- else:
70
- new_weight = weight * 0.95
71
  self.connections[conn_id].data = new_weight.clamp(-1, 1)
72
 
73
- # Structural neurogenesis
74
  if global_reward < -0.5:
75
- new_conn = self._generate_connection()
76
- if new_conn not in self.connections:
77
- self.connections[new_conn] = nn.Parameter(
78
- torch.randn(1) * 0.1
79
- )
80
 
81
- def _generate_connection(self) -> str:
82
- """Create new input-output connection based on activity"""
83
  input_act = {n.id: np.mean(n.recent_activations)
84
  for n in self.input_nodes if n.recent_activations}
85
  output_act = {n.id: np.mean(n.recent_activations)
86
  for n in self.output_nodes if n.recent_activations}
87
 
88
  if not input_act or not output_act:
89
- return ""
90
 
91
- src = min(input_act, key=input_act.get) # type: ignore
92
- tgt = min(output_act, key=output_act.get) # type: ignore
93
  return f"{src}->{tgt}"
94
 
95
  def train_step(self, x: torch.Tensor, y: torch.Tensor) -> float:
 
96
  self.optimizer.zero_grad()
97
- pred = self(x)
98
- loss = self.loss_fn(pred, y)
99
 
100
- # Structural regularization
 
 
 
 
 
 
 
101
  reg_loss = sum(p.abs().mean() for p in self.connections.values())
102
  total_loss = loss + 0.01 * reg_loss
103
 
104
- total_loss.backward()
105
- self.optimizer.step()
 
 
 
 
106
 
107
- # Emotional state adaptation
108
  self.emotional_state.data = torch.sigmoid(
109
  self.emotional_state + (0.5 - loss.item()) * 0.1
110
  )
111
 
112
- # Structural reorganization
113
  self.structural_update(0.5 - loss.item())
114
 
115
  return total_loss.item()
 
 
1
  import torch
2
  import torch.nn as nn
3
  import torch.optim as optim
4
  import math
5
+ import numpy as np
6
+ from typing import Dict, Optional
7
  from .node import CognitiveNode
8
 
9
  class DynamicCognitiveNet(nn.Module):
10
+ """Jaringan dengan manajemen koneksi yang robust"""
11
  def __init__(self, input_size: int, output_size: int):
12
  super().__init__()
13
  self.input_size = input_size
14
  self.output_size = output_size
15
 
16
+ # Node input/output
17
  self.input_nodes = nn.ModuleList([
18
  CognitiveNode(i, 1) for i in range(input_size)
19
  ])
 
21
  CognitiveNode(input_size + i, 1) for i in range(output_size)
22
  ])
23
 
24
+ # Manajemen koneksi
25
+ self.connections = nn.ParameterDict()
26
  self._init_base_connections()
27
 
28
+ # Konteks pembelajaran
29
  self.emotional_state = nn.Parameter(torch.tensor(0.0))
30
  self.optimizer = optim.AdamW(self.parameters(), lr=0.001)
31
  self.loss_fn = nn.MSELoss()
32
 
33
  def _init_base_connections(self):
34
+ """Inisialisasi koneksi input-output"""
35
+ for in_node in self.input_nodes:
36
+ for out_node in self.output_nodes:
37
  conn_id = f"{in_node.id}->{out_node.id}"
38
  self.connections[conn_id] = nn.Parameter(
39
  torch.randn(1) * 0.1
40
  )
41
 
42
  def forward(self, x: torch.Tensor) -> torch.Tensor:
43
+ # Pemrosesan input
44
  activations = {}
45
  for i, node in enumerate(self.input_nodes):
46
  activations[node.id] = node(x[i].unsqueeze(0))
47
 
48
+ # Integrasi output
49
  outputs = []
50
  for out_node in self.output_nodes:
51
  integrated = []
 
58
  combined = sum(integrated) / math.sqrt(len(integrated))
59
  outputs.append(out_node(combined))
60
 
61
+ return torch.stack(outputs).squeeze()
62
 
63
  def structural_update(self, global_reward: float):
64
+ """Update struktur dengan validasi koneksi"""
65
+ # Adaptasi kekuatan koneksi
66
+ for conn_id in list(self.connections.keys()):
67
+ new_weight = self.connections[conn_id] + 0.1 * global_reward
 
 
 
68
  self.connections[conn_id].data = new_weight.clamp(-1, 1)
69
 
70
+ # Pembuatan koneksi baru
71
  if global_reward < -0.5:
72
+ new_conn = self._find_underutilized_connection()
73
+ if new_conn and new_conn not in self.connections:
74
+ self.connections[new_conn] = nn.Parameter(torch.randn(1) * 0.1)
 
 
75
 
76
+ def _find_underutilized_connection(self) -> Optional[str]:
77
+ """Mencari koneksi input-output yang underutilized"""
78
  input_act = {n.id: np.mean(n.recent_activations)
79
  for n in self.input_nodes if n.recent_activations}
80
  output_act = {n.id: np.mean(n.recent_activations)
81
  for n in self.output_nodes if n.recent_activations}
82
 
83
  if not input_act or not output_act:
84
+ return None
85
 
86
+ src = min(input_act, key=lambda k: input_act[k])
87
+ tgt = min(output_act, key=lambda k: output_act[k])
88
  return f"{src}->{tgt}"
89
 
90
  def train_step(self, x: torch.Tensor, y: torch.Tensor) -> float:
91
+ """Training step dengan error handling"""
92
  self.optimizer.zero_grad()
 
 
93
 
94
+ try:
95
+ pred = self(x)
96
+ loss = self.loss_fn(pred, y)
97
+ except RuntimeError as e:
98
+ print(f"Error selama forward pass: {e}")
99
+ return float('nan')
100
+
101
+ # Regularisasi struktural
102
  reg_loss = sum(p.abs().mean() for p in self.connections.values())
103
  total_loss = loss + 0.01 * reg_loss
104
 
105
+ try:
106
+ total_loss.backward()
107
+ self.optimizer.step()
108
+ except RuntimeError as e:
109
+ print(f"Error selama backpropagation: {e}")
110
+ return float('nan')
111
 
112
+ # Update state emosional
113
  self.emotional_state.data = torch.sigmoid(
114
  self.emotional_state + (0.5 - loss.item()) * 0.1
115
  )
116
 
117
+ # Update struktur
118
  self.structural_update(0.5 - loss.item())
119
 
120
  return total_loss.item()