compile_day.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #!/usr/bin/env python3
  2. """编译单日课程(周六 10:00 批处理)"""
  3. import argparse
  4. import os
  5. import sys
  6. from pathlib import Path
  7. from jinja2 import Template
  8. import yaml
  9. # 添加项目根目录到路径
  10. PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
  11. sys.path.insert(0, str(PROJECT_ROOT))
  12. def load_config() -> dict:
  13. """加载配置"""
  14. config_path = PROJECT_ROOT / "skills" / "mathlab" / "config.yaml"
  15. with open(config_path, "r", encoding="utf-8") as f:
  16. return yaml.safe_load(f)
  17. def generate_symbol_decoder(topic: str) -> str:
  18. """生成符号解码字典(示例:感知机)"""
  19. return r"""
  20. <div class="symbol-map">
  21. <strong>$w$</strong> → <code>self.weights</code> (权重向量,shape: [d])
  22. </div>
  23. <div class="symbol-map">
  24. <strong>$b$</strong> → <code>self.bias</code> (偏置标量,shape: [])
  25. </div>
  26. <div class="symbol-map">
  27. <strong>$x$</strong> → <code>input_tensor</code> (输入样本,shape: [d])
  28. </div>
  29. <div class="symbol-map">
  30. <strong>$y$</strong> → <code>label</code> (标签,值域:{-1, +1})
  31. </div>
  32. <div class="symbol-map">
  33. <strong>$\sign(\cdot)$</strong> → <code>np.sign()</code> (符号函数)
  34. </div>
  35. <div class="symbol-map">
  36. <strong>$\xi$</strong> → <code>margin</code> (间隔,用于更新步长)
  37. </div>
  38. """
  39. def generate_math_derivation(topic: str) -> str:
  40. """生成数学推导(示例:感知机)"""
  41. return r"""
  42. ### 感知机预测函数
  43. $$f(x) = w \cdot x + b$$
  44. 其中 $\cdot$ 表示向量点积。
  45. ### 损失函数( hinge loss 的简化形式)
  46. $$L(w, b) = -\sum_{x_i \in M} y_i (w \cdot x_i + b)$$
  47. $M$ 是误分类点集合。
  48. ### 梯度下降更新规则
  49. $$w \leftarrow w + \eta \cdot y_i \cdot x_i$$
  50. $$b \leftarrow b + \eta \cdot y_i$$
  51. 其中 $\eta$ 是学习率。
  52. """
  53. def generate_html(day: int, topic: str, config: dict) -> str:
  54. """生成课程 HTML"""
  55. template_path = PROJECT_ROOT / "skills" / "mathlab" / "templates" / "course_template.html"
  56. with open(template_path, "r", encoding="utf-8") as f:
  57. template_content = f.read()
  58. template = Template(template_content)
  59. html_content = template.render(
  60. day=day,
  61. topic=topic,
  62. technical_debt="之前的算法无法处理线性不可分数据,导致泛化能力差。感知机通过引入决策边界,将分类问题转化为优化问题。",
  63. visual_intuition="想象一条直线(或超平面)将两类点分开。权重向量 $w$ 决定直线的方向,偏置 $b$ 决定直线的位置。",
  64. bilibili_keyword="感知机 直观解释",
  65. symbol_decoder=generate_symbol_decoder(topic),
  66. math_derivation=generate_math_derivation(topic),
  67. optimization_bottleneck=r"全量梯度下降需要遍历所有样本,复杂度 $O(N \cdot d)$。现代框架使用 mini-batch SGD 加速。",
  68. oj_mission="实现感知机的 forward 和 update 函数,在 XOR 数据集上验证无法收敛(线性不可分)。",
  69. katex_css="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css",
  70. katex_js="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"
  71. )
  72. return html_content
  73. def generate_exercise(day: int, topic: str) -> str:
  74. """生成练习题"""
  75. return f'''"""
  76. Day {day} - {topic} 练习
  77. 任务:实现 {topic} 的核心算法
  78. """
  79. import numpy as np
  80. import matplotlib.pyplot as plt
  81. class {topic.replace(" ", "_").lower()}:
  82. """{topic} 类"""
  83. def __init__(self, learning_rate: float = 0.01):
  84. self.learning_rate = learning_rate
  85. self.weights = None
  86. self.bias = None
  87. def forward(self, X: np.ndarray) -> np.ndarray:
  88. """前向传播
  89. Args:
  90. X: 输入数据,shape: [n_samples, n_features]
  91. Returns:
  92. 预测结果,shape: [n_samples]
  93. """
  94. # TODO: 实现 f(x) = sign(w · x + b)
  95. raise NotImplementedError
  96. def compute_loss(self, X: np.ndarray, y: np.ndarray) -> float:
  97. """计算损失"""
  98. # TODO: 实现损失函数
  99. raise NotImplementedError
  100. def update(self, X_i: np.ndarray, y_i: int):
  101. """更新参数
  102. Args:
  103. X_i: 单个样本,shape: [n_features]
  104. y_i: 标签,值域 {-1, +1}
  105. """
  106. # TODO: 实现梯度下降更新
  107. raise NotImplementedError
  108. def fit(self, X: np.ndarray, y: np.ndarray, max_iter: int = 100):
  109. """训练模型"""
  110. # TODO: 实现训练循环
  111. raise NotImplementedError
  112. def plot_concept():
  113. """可视化概念"""
  114. # 生成二维数据
  115. np.random.seed(42)
  116. X = np.random.randn(100, 2)
  117. y = np.sign(X[:, 0] + X[:, 1] - 0.5) * 1
  118. # 绘制散点图
  119. plt.figure(figsize=(8, 6))
  120. scatter = plt.scatter(X[:, 0], X[:, 1], c=y, cmap="bwr", s=100, edgecolors="black")
  121. plt.xlabel("x1")
  122. plt.ylabel("x2")
  123. plt.title("Day {day} - {topic} 可视化")
  124. plt.colorbar(scatter)
  125. plt.grid(True, alpha=0.3)
  126. plt.savefig("./plots/day{day}_concept.png", dpi=150)
  127. print(f"✅ 可视化已保存:plots/day{day}_concept.png")
  128. if __name__ == "__main__":
  129. plot_concept()
  130. '''
  131. def generate_test(day: int, topic: str) -> str:
  132. """生成测试用例"""
  133. return f'''"""
  134. Day {day} - {topic} 测试用例
  135. """
  136. import numpy as np
  137. import sys
  138. sys.path.append("../exercises")
  139. # TODO: 导入对应的类
  140. # from day{day}_task import *
  141. def test_forward_shape():
  142. """测试前向传播输出形状"""
  143. # TODO: 实现测试
  144. assert True
  145. def test_loss_computation():
  146. """测试损失计算"""
  147. # TODO: 实现测试
  148. assert True
  149. def test_update_rule():
  150. """测试参数更新规则"""
  151. # TODO: 实现测试
  152. assert True
  153. def test_convergence():
  154. """测试收敛性"""
  155. # TODO: 实现测试
  156. assert True
  157. '''
  158. def main():
  159. parser = argparse.ArgumentParser(description="编译单日课程")
  160. parser.add_argument("--day", type=int, required=True, help="天数 (1-7)")
  161. parser.add_argument("--topic", type=str, required=True, help="主题名称")
  162. args = parser.parse_args()
  163. config = load_config()
  164. # 创建 staging 目录
  165. staging_dir = PROJECT_ROOT / config["output"]["staging"]
  166. staging_dir.mkdir(exist_ok=True)
  167. exercises_dir = staging_dir / "exercises"
  168. tests_dir = staging_dir / "tests"
  169. exercises_dir.mkdir(exist_ok=True)
  170. tests_dir.mkdir(exist_ok=True)
  171. # 生成 HTML
  172. html_content = generate_html(args.day, args.topic, config)
  173. html_path = staging_dir / f"course_day{args.day}.html"
  174. with open(html_path, "w", encoding="utf-8") as f:
  175. f.write(html_content)
  176. print(f"✅ 生成课程 HTML: {html_path}")
  177. # 生成练习题
  178. exercise_content = generate_exercise(args.day, args.topic)
  179. exercise_path = exercises_dir / f"day{args.day}_task.py"
  180. with open(exercise_path, "w", encoding="utf-8") as f:
  181. f.write(exercise_content)
  182. print(f"✅ 生成练习题:{exercise_path}")
  183. # 生成测试
  184. test_content = generate_test(args.day, args.topic)
  185. test_path = tests_dir / f"test_day{args.day}.py"
  186. with open(test_path, "w", encoding="utf-8") as f:
  187. f.write(test_content)
  188. print(f"✅ 生成测试用例:{test_path}")
  189. print(f"\n🎉 Day {args.day} 编译完成!文件已保存到 staging/")
  190. if __name__ == "__main__":
  191. main()