Files
mesa-GA/GA_Agent_0925/绘图.py
2026-03-15 17:15:30 +08:00

59 lines
1.5 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import pandas as pd
import matplotlib.pyplot as plt
# # ==============================
# # 1⃣ 读取 CSV
# # ==============================
# csv_file = "convergence0119_data.csv"
# df = pd.read_csv(csv_file)
#
# # ==============================
# # 2⃣ 选择一次完整 GA 运行
# # ==============================
# target_ts = "2026-01-26 22:30:22"
# run_df = df[df["Timestamp"] == target_ts].copy()
#
# # 按代数排序,取前 50 代
# run_df = run_df.sort_values("Generation").head(100)
# 读取 CSV
csv_file = "convergence0119_data.csv"
df = pd.read_csv(csv_file)
# 按 Generation 排序
run_df = df.sort_values("Generation")
# ==============================
# 3⃣ 提取数据
# ==============================
generations = run_df["Generation"].values
best_fitness = run_df["Best_Fitness_Percentage"].values
# ==============================
# 4⃣ 计算滑动平均(窗口=5可调
# ==============================
window_size = 5
run_df["MA"] = run_df["Best_Fitness_Percentage"].rolling(
window=window_size,
min_periods=1
).mean()
# ==============================
# 5⃣ 绘图:点 + 连线 + 滑动平均
# ==============================
plt.figure(figsize=(10, 6))
# 原始点
plt.scatter(generations, best_fitness, s=30, alpha=0.6, label="Best Error")
# 连线
plt.plot(generations, best_fitness, linewidth=1, alpha=0.6)
plt.xlabel("Generation")
plt.ylabel("Best Error")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("ga_convergence_me_.png", dpi=300)
plt.show()