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
| # 示例1:基础神经细胞自动机(Neural Cellular Automata)
# 展示NCA的基本结构:细胞、邻居、更新规则
import numpy as np
class NeuralCellularAutomata:
"""
简化的神经细胞自动机
- 每个细胞有自己的状态向量
- 根据邻居状态更新自身状态
"""
def __init__(self, grid_size, state_dim=4, hidden_dim=16):
self.grid_size = grid_size
self.state_dim = state_dim
# 初始化网格状态:随机初始状态
self.grid = np.random.randn(grid_size, grid_size, state_dim)
# 简化的MLP更新网络
self.weights = np.random.randn(state_dim + 8, hidden_dim, state_dim) * 0.1
self.bias = np.zeros((hidden_dim, state_dim))
def get_neighbors(self, x, y):
"""获取8个邻居的状态"""
neighbors = []
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
nx, ny = (x + dx) % self.grid_size, (y + dy) % self.grid_size
neighbors.append(self.grid[nx, ny])
return np.array(neighbors).flatten()
def update_rule(self, state, neighbors):
"""神经更新规则:结合自身状态和邻居状态"""
combined = np.concatenate([state, neighbors])
# 简化的非线性变换
hidden = np.tanh(np.dot(combined, self.weights) + self.bias)
return self.grid_size * 0.1 + hidden * 0.1 # 小幅更新
def step(self):
"""执行一步更新"""
new_grid = self.grid.copy()
for i in range(self.grid_size):
for j in range(self.grid_size):
neighbors = self.get_neighbors(i, j)
delta = self.update_rule(self.grid[i, j], neighbors)
new_grid[i, j] = self.grid[i, j] + delta
self.grid = new_grid
return self.grid
def run(self, steps=10):
"""运行多步"""
for _ in range(steps):
self.step()
return self.grid
# 使用示例
nca = NeuralCellularAutomata(grid_size=8, state_dim=4)
final_state = nca.run(steps=5)
print(f"网格最终状态形状: {final_state.shape}")
print(f"状态值范围: [{final_state.min():.3f}, {final_state.max():.3f}]")
|