conditional_ratio_calc.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """
  2. 条件概率计算工具:
  3. 1)计算某个人设树节点在父节点下的条件概率;
  4. 2)计算某个 pattern 的条件概率。
  5. """
  6. from __future__ import annotations
  7. import json
  8. from pathlib import Path
  9. from typing import Any
  10. # 已推导列表:每项为 (已推导的选题点, 推导来源人设树节点),如 ("分享","分享")、("柴犬","动物角色")
  11. # 推导来源人设树节点的 post_ids 在计算条件概率时从人设树中读取
  12. DerivedItem = tuple[str, str]
  13. def _tree_dir(account_name: str, base_dir: Path | None = None) -> Path:
  14. """人设树目录:../input/{account_name}/原始数据/tree/(相对本文件所在目录)。"""
  15. if base_dir is not None:
  16. return base_dir / account_name / "原始数据" / "tree"
  17. return Path(__file__).resolve().parent.parent / "input" / account_name / "原始数据" / "tree"
  18. def _load_trees(account_name: str, base_dir: Path | None = None) -> list[tuple[str, dict]]:
  19. """加载该账号下所有维度的人设树。返回 [(维度名, 根节点 dict), ...]。"""
  20. td = _tree_dir(account_name, base_dir)
  21. if not td.is_dir():
  22. return []
  23. result = []
  24. for p in td.glob("*.json"):
  25. try:
  26. with open(p, "r", encoding="utf-8") as f:
  27. data = json.load(f)
  28. # 文件格式为 { "实质": { ... } } 或 { "形式": { ... } }
  29. for dim_name, root in data.items():
  30. if isinstance(root, dict):
  31. result.append((dim_name, root))
  32. break
  33. except Exception:
  34. continue
  35. return result
  36. def _post_ids_of(node: dict) -> list[str]:
  37. """从树节点中取出 _post_ids,无则返回空列表。"""
  38. return list(node.get("_post_ids") or [])
  39. def _build_node_index(account_name: str, base_dir: Path | None = None) -> dict[str, tuple[list[str], list[str]]]:
  40. """
  41. 遍历所有维度的人设树,建立 节点名 -> (该节点 post_ids, 父节点 post_ids)。
  42. 同一节点名在多个分支出现时,保留第一次遇到的(保证父子一致)。
  43. """
  44. index: dict[str, tuple[list[str], list[str]]] = {}
  45. for _dim, root in _load_trees(account_name, base_dir):
  46. parent_pids = _post_ids_of(root)
  47. def walk(parent_ids: list[str], node_dict: dict) -> None:
  48. for name, child in (node_dict.get("children") or {}).items():
  49. if not isinstance(child, dict):
  50. continue
  51. if name not in index:
  52. index[name] = (_post_ids_of(child), list(parent_ids))
  53. walk(_post_ids_of(child), child)
  54. walk(parent_pids, root)
  55. return index
  56. def _derived_post_ids_from_sources(
  57. derived_list: list[DerivedItem],
  58. index: dict[str, tuple[list[str], list[str]]],
  59. ) -> set[str]:
  60. """根据 derived_list 中的「推导来源人设树节点」在人设树中的 post_ids 取交集,得到已推导的帖子集合。"""
  61. common: set[str] | None = None
  62. for _topic_point, source_node in derived_list:
  63. if source_node not in index:
  64. continue
  65. pids = set(index[source_node][0])
  66. if common is None:
  67. common = pids
  68. else:
  69. common &= pids
  70. return common if common is not None else set()
  71. def calc_node_conditional_ratio(
  72. account_name: str,
  73. derived_list: list[DerivedItem],
  74. tree_node_name: str,
  75. base_dir: Path | None = None,
  76. ) -> float:
  77. """
  78. 计算人设树节点 N 在父节点 P 下的条件概率。
  79. 参数:
  80. account_name: 账号名称
  81. derived_list: 已推导列表,每项 (已推导的选题点, 推导来源人设树节点)
  82. tree_node_name: 人设树节点 N 的名称(字符串匹配)
  83. base_dir: 可选,input 根目录;不传则使用相对本文件的 ../input
  84. 计算规则:
  85. 已推导的帖子集合 = 各「推导来源人设树节点」在人设树中的 post_ids 的交集(方法内从树读取)
  86. 分子 = |已推导的帖子集合 ∩ N 的 post_ids|
  87. 分母 = |已推导的帖子集合 ∩ P 的 post_ids|
  88. 条件概率 = 分子/分母,且 ≤1;分母为 0 时返回 1。
  89. """
  90. index = _build_node_index(account_name, base_dir)
  91. derived_post_ids = _derived_post_ids_from_sources(derived_list, index)
  92. if tree_node_name not in index:
  93. return 1.0
  94. n_pids, p_pids = index[tree_node_name]
  95. set_n = set(n_pids)
  96. set_p = set(p_pids)
  97. den = len(derived_post_ids & set_p)
  98. if den == 0:
  99. return 0.0
  100. num = len(derived_post_ids & set_n)
  101. return min(1.0, num / den)
  102. def _pattern_nodes_and_post_count(pattern: dict[str, Any]) -> tuple[list[str], int]:
  103. """从 pattern 中解析出节点列表和 post_count。支持 nodes + post_count 或 i + post_count。"""
  104. nodes = pattern.get("nodes")
  105. if nodes is not None and isinstance(nodes, list):
  106. nodes = [str(x).strip() for x in nodes if x]
  107. else:
  108. raw = pattern.get("i") or pattern.get("pattern_str") or ""
  109. nodes = [x.strip() for x in str(raw).replace("+", " ").split() if x.strip()]
  110. post_count = int(pattern.get("post_count", 0))
  111. return nodes, post_count
  112. def calc_pattern_conditional_ratio(
  113. account_name: str,
  114. derived_list: list[DerivedItem],
  115. pattern: dict[str, Any],
  116. base_dir: Path | None = None,
  117. ) -> float:
  118. """
  119. 计算某个 pattern 的条件概率。
  120. 参数:
  121. account_name: 账号名称
  122. derived_list: 已推导列表,每项 (已推导的选题点, 推导来源人设树节点)
  123. pattern: 至少包含节点列表与 post_count。
  124. - 节点列表: key 为 "nodes"(list)或 "i"(字符串,用 + 连接)
  125. - post_count: 该 pattern 的帖子数量,作为分子
  126. base_dir: 可选,input 根目录
  127. 计算规则:
  128. 取 pattern 中「已被推导」的节点(其名称出现在 derived 的推导来源中),
  129. 在人设树中取这些节点的 post_ids 的交集作为分母;
  130. 分子 = pattern.post_count。
  131. 条件概率 = 分子/分母,且 ≤1;分母为 0 时返回 1。
  132. """
  133. pattern_nodes, post_count = _pattern_nodes_and_post_count(pattern)
  134. if not pattern_nodes or post_count <= 0:
  135. return 1.0
  136. derived_sources = set(source for _post, source in derived_list)
  137. # pattern 中已被推导的节点
  138. derived_pattern_nodes = [n for n in pattern_nodes if n in derived_sources]
  139. if not derived_pattern_nodes:
  140. return 1.0
  141. index = _build_node_index(account_name, base_dir)
  142. # 仅使用在人设树中存在的「已被推导」节点,取它们在树中的 post_ids 的交集
  143. derived_in_tree = [n for n in derived_pattern_nodes if n in index]
  144. if not derived_in_tree:
  145. return 1.0
  146. common: set[str] | None = None
  147. for name in derived_in_tree:
  148. pids = set(index[name][0])
  149. if common is None:
  150. common = pids
  151. else:
  152. common &= pids
  153. if common is None or len(common) == 0:
  154. return 1.0
  155. den = len(common)
  156. return min(1.0, post_count / den)
  157. def _test_with_user_example() -> None:
  158. """
  159. 使用你提供的测试数据:已推导 (分享|分享)、(柴犬|动物角色);
  160. 人设树节点:恶作剧;pattern:分享+动物角色+创意表达 post_count=2。
  161. 推导来源的 post_ids 在方法内部从人设树读取。
  162. """
  163. account_name = "家有大志"
  164. # 已推导列表:(已推导的选题点, 推导来源人设树节点)
  165. derived_list: list[DerivedItem] = [
  166. ("分享", "分享"),
  167. # ("柴犬", "动物角色"),
  168. ]
  169. # 1)人设树节点「恶作剧」的条件概率
  170. r_node = calc_node_conditional_ratio(account_name, derived_list, "恶作剧")
  171. print(f"1) 人设树节点「恶作剧」条件概率: {r_node}")
  172. # 2)pattern 分享+动物角色+创意表达 post_count=2 的条件概率
  173. pattern = {"i": "分享+动物角色+创意表达", "post_count": 2}
  174. r_pattern = calc_pattern_conditional_ratio(account_name, derived_list, pattern)
  175. print(f"2) pattern 分享+动物角色+创意表达 (post_count=2) 条件概率: {r_pattern}")
  176. if __name__ == "__main__":
  177. _test_with_user_example()