UMEHOSHI ITA TOP PAGE COMPUTER SHIEN LAB
「UMEHOSHI ITA」にESP32-WROOM-32E-N16を、「UMEHOSHI ITA」へ取り付ける例で、
このページの続きの内容です。
3.7V定格のコアレスブラシ付きモータを4個使って、マルチコプター型ドローンをの制御を検討します。
| 添え字範囲 | 4要素の意味 |
|---|---|
| 0〜3 | 現在の各計測値:Roll / Pitch / Yaw / 高さ |
| 4〜7 | 下記(t-1)で判定された各モータの指示:M1Act/M2Act/M3Act/M4Act |
| 8〜11 | 現在から1つ前の各計測値:Roll / Pitch / Yaw / 高さ |
| 12〜15 | 下記(t-2)で判定された各モータの指示:M1Act/M2Act/M3Act/M4Act |
| 16〜19 | 現在から2つ前の各計測値:Roll / Pitch / Yaw / 高さ |
| 20〜23 | 下記(t-3)で判定された各モータの指示:M1Act/M2Act/M3Act/M4Act |
| 24〜27 | 現在から3つ前の各計測値:Roll / Pitch / Yaw / 高さ |
# ppo_actor.py
# MicroPython PPO Actor inference
# Network: 28 -> 64 -> 12
# MultiCategorical: 4 x Categorical(3)
import math
import random
from numarray import NumArray
class PPOActor:
INPUT_SIZE = 28
HIDDEN_SIZE = 64
OUTPUT_SIZE = 12
def __init__(self):
self.W1 = NumArray()
self.B1 = NumArray()
self.W2 = NumArray()
self.B2 = NumArray()
self.loaded = False
def load_params(self, path="ppo_weights.bin"):
with open(path, "rb") as f:
self.W1.read(f)
self.B1.read(f)
self.W2.read(f)
self.B2.read(f)
# Check parameter dimensions
if self.W1.shapeR[:2] != [64, 28]:
raise ValueError("W1 shape error")
if self.B1.shapeR[0] != 64:
raise ValueError("B1 shape error")
if self.W2.shapeR[:2] != [12, 64]:
raise ValueError("W2 shape error")
if self.B2.shapeR[0] != 12:
raise ValueError("B2 shape error")
self.loaded = True
# Tanh(タンエイチ) activation : 双曲線正接 活性化関数
@staticmethod
def tanh_array(x:NumArray):
for i in range(len(x.array)):
x.array[i] = math.tanh(x.array[i])
return x
# Softmax for each motor
@staticmethod
def softmax3(a, offset):
# Numerical overflow protection
m = max(
a[offset],
a[offset + 1],
a[offset + 2]
)
e0 = math.exp(a[offset] - m)
e1 = math.exp(a[offset + 1] - m)
e2 = math.exp(a[offset + 2] - m)
total = e0 + e1 + e2
return [
e0 / total,
e1 / total,
e2 / total
]
# Forward calculation
def predict_proba(self, inputs):
if not self.loaded:
raise RuntimeError("Model parameters not loaded")
if len(inputs) != self.INPUT_SIZE:
raise ValueError("Input must contain 28 values")
# Convert list to NumArray
x = NumArray.createByArray(inputs)
# Layer 1: 28 -> 64
h = NumArray.dot(x, self.W1)
h.add_matrix(self.B1)
self.tanh_array(h) # Tanh
# Layer 2: 64 -> 12
y = NumArray.dot(h, self.W2)
y.add_matrix(self.B2)
# MultiCategorical softmax
result = []
for motor in range(4):
offset = motor * 3
p = self.softmax3(
y.array,
offset
)
result.extend(p)
return result
# Deterministic action selection 決定論的な行動選択
def predict(self, inputs):
probabilities = self.predict_proba(inputs)
actions = []
for motor in range(4):
offset = motor * 3
best = 0
for i in range(1, 3):
if probabilities[offset + i] > probabilities[offset + best]:
best = i
actions.append(best)
return actions
# Stochastic action selection 確率的な行動選択
def sample(self, inputs):
probabilities = self.predict_proba(inputs)
actions = []
for motor in range(4):
offset = motor * 3
r = random.random()
total = 0.0
selected = 2
for i in range(3):
total += probabilities[offset + i]
if r < total:
selected = i
break
actions.append(selected)
return actions
# ppo_trainer.py
# Supervised imitation training for PPOActor
# Network: 28 -> 64 -> 12
# MultiCategorical: 4 x Categorical(3)
import math
import random
from ppo_actor import PPOActor
from numarray import NumArray
# ----------------------------------------------------------------
# 教師あり学習クラス (NumArray利用版)
# PPOActorを継承
# ----------------------------------------------------------------
class PPOTrainer(PPOActor):
def __init__(self, seed=123):
super().__init__()
random.seed(seed)
# 学習データ
# (入力28個, 正解アクション4個)
self.samples = []
# Adam設定
self.lr = 0.001
self.beta1 = 0.9
self.beta2 = 0.999
self.epsilon = 1e-8
self.step = 0
# 重みの初期化
self._initialize_weights()
# Adamの内部状態
self.m = []
self.v = []
self._initialize_adam()
# ------------------------------------------------
# 重みの初期化
# ------------------------------------------------
def _initialize_weights(self):
# W1 : 28入力 -> 64出力
self.W1 = NumArray(64, 28)
self.B1 = NumArray(64)
# W2 : 64入力 -> 12出力
self.W2 = NumArray(12, 64)
self.B2 = NumArray(12)
# Xavier初期化
scale1 = math.sqrt(2.0 / (28 + 64))
scale2 = math.sqrt(2.0 / (64 + 12))
for i in range(len(self.W1.array)):
self.W1.array[i] = normal_random(0, scale1)
for i in range(len(self.W2.array)):
self.W2.array[i] = normal_random(0, scale2)
# PPOActor.predict() の利用を許可
# 元のPPOActorがloadedをチェックする場合に必要
self.loaded = True
# ------------------------------------------------
# Adam初期化
# ------------------------------------------------
def _initialize_adam(self):
params = [self.W1, self.B1, self.W2, self.B2]
for p in params:
self.m.append(NumArray(
p.shapeR[0], p.shapeR[1], p.shapeR[2]
))
self.v.append(NumArray(
p.shapeR[0], p.shapeR[1], p.shapeR[2]
))
# ------------------------------------------------
# 学習データ追加
# ------------------------------------------------
def add_sample(self, inputs, actions):
if len(inputs) != self.INPUT_SIZE:
raise ValueError("Input must contain 28 values")
if len(actions) != 4:
raise ValueError("Actions must contain 4 values")
x = [float(v) for v in inputs]
a = [int(v) for v in actions]
for v in a:
if v < 0 or v > 2:
raise ValueError("Action must be 0, 1 or 2")
self.samples.append((x, a))
# ------------------------------------------------
# 順方向計算
# ------------------------------------------------
def _forward(self, inputs):
x = NumArray.createByArray(inputs)
# 入力28 -> 中間層64
h = NumArray.dot(x, self.W1)
h.add_matrix(self.B1)
self.tanh_array(h)
# 中間層64 -> 出力12
y = NumArray.dot(h, self.W2)
y.add_matrix(self.B2)
return h, y
# ------------------------------------------------
# MultiCategorical Softmax
# ------------------------------------------------
def _softmax(self, y):
p = NumArray(12)
# 4モータを個別にSoftmax
for motor in range(4):
offset = motor * 3
values = self.softmax3(y.array, offset)
for i in range(3):
p.array[offset + i] = values[i]
return p
# ------------------------------------------------
# 学習1回(全サンプルを使用)
# ------------------------------------------------
def train_batch(self):
n = len(self.samples)
if n == 0:
raise ValueError("No training samples")
# 勾配の初期化
gW1 = NumArray(64, 28)
gB1 = NumArray(64)
gW2 = NumArray(12, 64)
gB2 = NumArray(12)
loss = 0.0
# 全サンプルについて勾配を集計
for x, actions in self.samples:
# 順方向計算
h, y = self._forward(x)
# 確率計算
p = self._softmax(y)
# 正解ラベル(One-Hot)
target = NumArray(12)
for motor in range(4):
target.array[motor * 3 + actions[motor]] = 1.0
# 交差エントロピー誤差
for i in range(12):
if target.array[i] == 1.0:
loss -= math.log(max(p.array[i], 1e-10))
# 出力層の誤差
# Softmax + Cross Entropy
# dy = p - target
dy = p.deepcopy()
for i in range(12):
dy.array[i] -= target.array[i]
# ----------------------------------------
# 出力層 -> 中間層の逆伝播
# ----------------------------------------
dh = NumArray(64)
for j in range(64):
s = 0.0
for k in range(12):
idx = j * 12 + k
# W2の勾配
gW2.array[idx] += h.array[j] * dy.array[k]
# 中間層へ誤差を伝播
s += self.W2.array[idx] * dy.array[k]
# Tanhの微分
dh.array[j] = s * (1.0 - h.array[j] ** 2)
# B1の勾配
gB1.array[j] += dh.array[j]
# ----------------------------------------
# 中間層 -> 入力層の逆伝播
# ----------------------------------------
for i in range(28):
for j in range(64):
idx = i * 64 + j
# W1の勾配
gW1.array[idx] += x.array[i] * dh.array[j]
# 出力層のバイアス勾配
for k in range(12):
gB2.array[k] += dy.array[k]
# --------------------------------------------
# 勾配の平均
# --------------------------------------------
loss /= n
grads = [gW1, gB1, gW2, gB2]
for g in grads:
g.mul_scalar(1.0 / n)
# Adamによる重み更新
self._adam_update(grads)
return loss
# ------------------------------------------------
# Adamによる重み更新
# ------------------------------------------------
def _adam_update(self, grads):
self.step += 1
params = [self.W1, self.B1, self.W2, self.B2]
b1 = self.beta1
b2 = self.beta2
# バイアス補正
correction1 = 1.0 - b1 ** self.step
correction2 = 1.0 - b2 ** self.step
for p in range(4):
param = params[p].array
grad = grads[p].array
m = self.m[p].array
v = self.v[p].array
for i in range(len(param)):
g = grad[i]
# 1次モーメント
m[i] = b1 * m[i] + (1.0 - b1) * g
# 2次モーメント
v[i] = b2 * v[i] + (1.0 - b2) * g * g
# バイアス補正
mh = m[i] / correction1
vh = v[i] / correction2
# パラメータ更新
param[i] -= (
self.lr * mh /
(math.sqrt(vh) + self.epsilon)
)
# ------------------------------------------------
# 学習実行
# ------------------------------------------------
def fit(self, epochs=1000, print_interval=100):
if len(self.samples) == 0:
raise ValueError("No training samples")
loss = 0.0
for epoch in range(epochs):
random.shuffle(self.samples)
loss = self.train_batch()
if (
print_interval > 0 and
(epoch + 1) % print_interval == 0
):
print(
"Epoch:", epoch + 1,
"Loss:", loss
)
return loss
# ------------------------------------------------
# 学習結果の保存
# ------------------------------------------------
def save_weights(self, path="ppo_weights.bin"):
with open(path, "wb") as f:
self.W1.write(f)
self.B1.write(f)
self.W2.write(f)
self.B2.write(f)
print("Saved:", path)
# ------------------------------------------------
# 学習精度の確認
# PPOActorのpredict()を利用
# ------------------------------------------------
def accuracy(self):
if len(self.samples) == 0:
return 0.0
correct = 0
total = len(self.samples) * 4
for x, target in self.samples:
# 継承元の判定処理
pred = self.predict(x)
for i in range(4):
if pred[i] == target[i]:
correct += 1
return correct / total
actor = PPOActor()
print(actor)
trainer = PPOTrainer()
print('------------------------')
training_data = [
([ # ある時点の入力28個
0, 0, 0, 0.5, #現在の各計測値:Roll / Pitch / Yaw / 高さ
1, 1, 1, 1, #下記(t-1)で判定された各モータの指示:M1Act/M2Act/M3Act/M4Act
0, 0, 0, 0.2, #現在から1つ前の各計測値:Roll / Pitch / Yaw / 高さ
1, 1, 1, 1, #下記(t-2)で判定された各モータの指示:M1Act/M2Act/M3Act/M4Act
0, 0, 0, 0.1, #現在から2つ前の各計測値:Roll / Pitch / Yaw / 高さ
1, 1, 1, 1, #下記(t-3)で判定された各モータの指示:M1Act/M2Act/M3Act/M4Act
0, 0, 0, 0, #現在から3つ前の各計測値:Roll / Pitch / Yaw / 高さ
], [1, 1, 1, 1]# 正解のモータ動作---------------------------------------------------------
),
]
print(training_data[0][0])
print('------------------------')
print(training_data[0][1])
print('------------------------')
trainer.add_sample(training_data[0][0], training_data[0][1])
print(trainer)
# 学習
loss = trainer.fit(
epochs=1000,
print_interval=100
)
# # 学習精度
# print("Accuracy:", trainer.accuracy())
# # 重み保存
# trainer.save_weights()
# ESP32内Micropythonのサーバ側で実行したprint表示をクライアント側で表示する。 # try: import server print = server.send # printをクライアントへ出力する機能に置き換える except Exception as e: pass from numarray import NumArray from ppo_actor import PPOActor from ppo_trainer import PPOTrainer import graph x = [x for x in range(-10,10)] nx=NumArray.createByArray(x) # 1次元目サイスが6,2次元目が2の3次配列にしている。(3次元目は自動的に残りのサイズで、3が設定) ny=PPOActor.tanh_array(nx.deepcopy()) print(nx) print(ny) graph.plot(nx.array, ny.array)