WFGY/tools/wfgy_e_resonance_colab.ipynb
2025-08-07 12:55:40 +08:00

116 lines
3.1 KiB
Text

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 🧪 WFGY e_resonance Demo (v0.1)\n",
"Measure how a prompt + answer jointly resonate with a given semantic field."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Formula\n",
"For a set of anchor vectors **D = {d₁ … dₙ}** representing a domain:\n",
"$$ e_{res} = \\frac{1}{n}\\sum_{i=1}^{n}\\bigl[\\cos(I,d_i)\\;\\times\\;\\cos(G,d_i)\\bigr] $$\n",
"Where *I* = prompt intent, *G* = generated answer."
]
},
{
"cell_type": "code",
"metadata": { "id": "install" },
"source": [
"!pip -q install sentence-transformers --upgrade"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": { "id": "imports" },
"source": [
"from sentence_transformers import SentenceTransformer, util"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": { "id": "model" },
"source": [
"model = SentenceTransformer('all-MiniLM-L6-v2')"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Anchors\n",
"A minimal 3-sentence anchor set for the **Buddhism** field (edit as you like)."
]
},
{
"cell_type": "code",
"metadata": { "id": "anchors" },
"source": [
"anchors = [\n",
" \"All compounded things are impermanent.\",\n",
" \"Suffering arises from attachment and craving.\",\n",
" \"The mind is everything; what you think you become.\"\n",
"]\n",
"anchor_vecs = model.encode(anchors, convert_to_tensor=True)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ✏️ Edit & run\n",
"Replace `prompt` / `answer`, then ▶️."
]
},
{
"cell_type": "code",
"metadata": { "id": "user" },
"source": [
"prompt = \"How can one reduce daily anxiety?\"\n",
"answer = \"By recognising thoughts as fleeting and practising mindful breathing.\"\n",
"\n",
"p_vec = model.encode(prompt, convert_to_tensor=True)\n",
"a_vec = model.encode(answer, convert_to_tensor=True)\n",
"\n",
"scores = util.cos_sim(p_vec, anchor_vecs)[0] * util.cos_sim(a_vec, anchor_vecs)[0]\n",
"e_res = scores.mean().item()\n",
"\n",
"print(f\"e_resonance with Buddhism anchors : {e_res:.3f}\\n\")\n",
"for s, txt in sorted(zip(scores, anchors), reverse=True):\n",
" print(f\" {s:.3f} | {txt}\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"### Next Steps\n",
"* Swap in your own anchor set: philosophy, physics, pop-culture, etc. \n",
"* Compare multiple answers — choose the highest **e_resonance**. \n",
"* For full failure taxonomy see **Problem Map 1.0 / 2.0**.\n"
]
}
],
"metadata": {
"kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" },
"language_info": { "name": "python" }
},
"nbformat": 4,
"nbformat_minor": 5
}