tahamajs/NLP / nlp-projects /Assignment-3 /Assignment_3_HANDIN_FINAL.ipynb
tahamajs's picture
download
raw
85 kB
{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "source": [ "# Assignment 3 - Transliteration" ], "metadata": { "id": "XSIPwHJdYR6E" } }, { "cell_type": "markdown", "source": [ "### Setup [do not change]" ], "metadata": { "id": "pcy6UafEX5hB" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "kN-iTMK8ScoR", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "2604eb69-0172-4a54-aa42-347d0b8ba9c0" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Cloning into 'eth-nlp-f22-hw3'...\n", "remote: Enumerating objects: 29, done.\u001b[K\n", "remote: Counting objects: 100% (29/29), done.\u001b[K\n", "remote: Compressing objects: 100% (25/25), done.\u001b[K\n", "remote: Total 29 (delta 6), reused 16 (delta 2), pack-reused 0\u001b[K\n", "Unpacking objects: 100% (29/29), 9.90 KiB | 921.00 KiB/s, done.\n", "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n", "Obtaining file:///content/eth-nlp-f22-hw3\n", " Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n", "Requirement already satisfied: numpy in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (1.21.6)\n", "Collecting frozendict\n", " Downloading frozendict-2.3.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (110 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m111.0/111.0 KB\u001b[0m \u001b[31m2.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hRequirement already satisfied: frozenlist in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (1.3.3)\n", "Collecting pyconll\n", " Downloading pyconll-3.1.0-py3-none-any.whl (26 kB)\n", "Requirement already satisfied: nltk in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (3.7)\n", "Requirement already satisfied: pytest in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (3.6.4)\n", "Requirement already satisfied: dill in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (0.3.6)\n", "Requirement already satisfied: click in /usr/local/lib/python3.8/dist-packages (from nltk->rayuela==0.1) (7.1.2)\n", "Requirement already satisfied: tqdm in /usr/local/lib/python3.8/dist-packages (from nltk->rayuela==0.1) (4.64.1)\n", "Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.8/dist-packages (from nltk->rayuela==0.1) (2022.6.2)\n", "Requirement already satisfied: joblib in /usr/local/lib/python3.8/dist-packages (from nltk->rayuela==0.1) (1.2.0)\n", "Requirement already satisfied: setuptools in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (57.4.0)\n", "Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (1.15.0)\n", "Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (1.11.0)\n", "Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (1.4.1)\n", "Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (9.0.0)\n", "Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (22.2.0)\n", "Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (0.7.1)\n", "Installing collected packages: pyconll, frozendict, rayuela\n", " Running setup.py develop for rayuela\n", "Successfully installed frozendict-2.3.4 pyconll-3.1.0 rayuela-0.1\n" ] } ], "source": [ "!git clone https://github.com/butoialexandra/eth-nlp-f22-hw3.git\n", "\n", "import os\n", "os.chdir('eth-nlp-f22-hw3')\n", "\n", "!pip install -e ." ] }, { "cell_type": "code", "source": [ "!wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1wlHbFChZFcBgEU8knAeaUIqE0W4EaJEC' -O 'test_cases.pkl'" ], "metadata": { "id": "-4p3GQ0u2iX4", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "3ce80dc4-ee91-4e34-92a4-6509e8435c0b" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "--2023-02-06 20:07:51-- https://docs.google.com/uc?export=download&id=1wlHbFChZFcBgEU8knAeaUIqE0W4EaJEC\n", "Resolving docs.google.com (docs.google.com)... 74.125.26.113, 74.125.26.101, 74.125.26.102, ...\n", "Connecting to docs.google.com (docs.google.com)|74.125.26.113|:443... connected.\n", "HTTP request sent, awaiting response... 303 See Other\n", "Location: https://doc-0s-50-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/8493dab293a4ddilsrqh6j9s1cnojj7p/1675714050000/03249710210786382974/*/1wlHbFChZFcBgEU8knAeaUIqE0W4EaJEC?e=download&uuid=4bcda39b-9a1c-403b-b2c0-21183ba8f4d3 [following]\n", "Warning: wildcards not supported in HTTP.\n", "--2023-02-06 20:07:51-- https://doc-0s-50-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/8493dab293a4ddilsrqh6j9s1cnojj7p/1675714050000/03249710210786382974/*/1wlHbFChZFcBgEU8knAeaUIqE0W4EaJEC?e=download&uuid=4bcda39b-9a1c-403b-b2c0-21183ba8f4d3\n", "Resolving doc-0s-50-docs.googleusercontent.com (doc-0s-50-docs.googleusercontent.com)... 172.217.203.132, 2607:f8b0:400c:c07::84\n", "Connecting to doc-0s-50-docs.googleusercontent.com (doc-0s-50-docs.googleusercontent.com)|172.217.203.132|:443... connected.\n", "HTTP request sent, awaiting response... 200 OK\n", "Length: 45349 (44K) [application/octet-stream]\n", "Saving to: ‘test_cases.pkl’\n", "\n", "test_cases.pkl 100%[===================>] 44.29K --.-KB/s in 0s \n", "\n", "2023-02-06 20:07:51 (93.3 MB/s) - ‘test_cases.pkl’ saved [45349/45349]\n", "\n" ] } ] }, { "cell_type": "code", "source": [ "from rayuela.base.semiring import Semiring, Real, Tropical\n", "from rayuela.base.symbol import Sym, ε, ε_1, ε_2\n", "from rayuela.base.misc import epsilon_filter\n", "\n", "from rayuela.fsa.fst import FST\n", "from rayuela.fsa.state import State, PairState\n", "\n", "import dill\n", "import numpy as np\n", "from math import exp, log\n", "\n", "from itertools import product\n", "\n", "from frozendict import frozendict\n" ], "metadata": { "id": "hsr_q831W8rN" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Subquestion a) - Log Semiring" ], "metadata": { "id": "wFL0YgNBYCf7" } }, { "cell_type": "code", "source": [ "class Log(Semiring):\n", " def __init__(self, score):\n", " self.score = score\n", "\n", " def star(self):\n", " # TODO: implement Kleene star\n", " if self.score>=0:\n", " return Log(np.inf)\n", " else:\n", " return Log(np.log(1/(1-np.exp(self.score))))\n", "\n", " def __float__(self):\n", " return float(self.score)\n", "\n", " def __add__(self, other):\n", " # TODO: implement log addition\n", " # For numerical stability you should use the using the log-sum-exp trick\n", " # https://en.wikipedia.org/wiki/LogSumExp\n", " return Log(np.logaddexp(self.score, other.score))\n", "\n", " def __mul__(self, other):\n", " # TODO: implement log multiplication\n", " return Log(self.score + other.score)\n", "\n", " def __repr__(self):\n", " return f\"{round(self.score, 15)}\"\n", "\n", " def __eq__(self, other):\n", " return np.allclose(float(self.score), float(other.score), atol=1e-3)\n", "\n", " def __hash__(self):\n", " return hash(self.score)\n", "\n", "# TODO: implement the log semiring one and zero\n", "Log.zero = Log(-np.inf)\n", "Log.one = Log(0)\n", "\n", "\n", "Log.idempotent = False\n", "Log.cancellative = True" ], "metadata": { "id": "ny9YFmJ8avns" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Before moving to the next subquestion, we give some examples of WFSTs to illustrate how to use the library `rayuela`." ], "metadata": { "id": "LH8LNXZpoCX6" } }, { "cell_type": "code", "source": [ "# A simple language model encoded by a WFST\n", "\n", "sem = Real # the Real semiring\n", "fst = FST(sem) # a WFST in the Real semiring\n", "\n", "# add transitions\n", "fst.add_arc(State(0), Sym('formal'), Sym('formal'), State(1), Real(0.2))\n", "fst.add_arc(State(0), Sym('natural'), Sym('natural'), State(1), Real(0.3))\n", "fst.add_arc(State(0), Sym('learning'), Sym('learning'), State(2), Real(0.2))\n", "fst.add_arc(State(0), Sym('data'), Sym('data'), State(3), Real(0.3))\n", "\n", "fst.add_arc(State(1), Sym('language'), Sym('language'), State(2), Real(0.6))\n", "fst.add_arc(State(1), Sym('languages'), Sym('languages'), State(4), Real(0.4))\n", "\n", "fst.add_arc(State(2), Sym('is'), Sym('is'), State(5), Real(1.0))\n", "\n", "fst.add_arc(State(5), Sym('fun'), Sym('fun'), State(6), Real(1.0))\n", "\n", "fst.add_arc(State(3), Sym('is'), Sym('is'), State(5), Real(0.5))\n", "fst.add_arc(State(3), Sym('are'), Sym('are'), State(5), Real(0.5))\n", "\n", "fst.add_arc(State(4), Sym('are'), Sym('are'), State(5), Real(1.0))\n", "\n", "# set initial weights\n", "# if not set, it defaults to semiring zero\n", "fst.set_I(State(0), Real(1.0))\n", "# set final weights\n", "fst.set_F(State(6), Real(1.0))\n", "\n", "# visualize\n", "fst" ], "metadata": { "id": "RJzHo7imoDb9", "colab": { "base_uri": "https://localhost:8080/", "height": 261 }, "outputId": "4a060de7-0935-4a1c-f3c7-05cd6677c8fa" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "WFSA(7 states, <class 'rayuela.base.semiring.Real'>)" ], "text/html": [ "\n", "\t\t<script>\n", "\t\ttry {\n", "\t\trequire.config({\n", "\t\tpaths: {\n", "\t\t\"d3\": \"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3\",\n", "\t\t\"dagreD3\": \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min\"\n", "\t\t}\n", "\t\t});\n", "\t\t} catch {\n", "\t\t [\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js\",\n", "\t\t \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js\"].forEach(function (src) {\n", "\t\t\tvar tag = document.createElement('script');\n", "\t\t\ttag.src = src;\n", "\t\t\tdocument.body.appendChild(tag);\n", "\t\t })\n", "\t\t}\n", "\t\ttry {\n", "\t\trequirejs(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\ttry {\n", "\t\trequire(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\t</script>\n", "\t\t<style>\n", "\t\t.node rect,\n", "\t\t.node circle,\n", "\t\t.node ellipse {\n", "\t\tstroke: #333;\n", "\t\tfill: #fff;\n", "\t\tstroke-width: 1px;\n", "\t\t}\n", "\n", "\t\t.edgePath path {\n", "\t\tstroke: #333;\n", "\t\tfill: #333;\n", "\t\tstroke-width: 1.5px;\n", "\t\t}\n", "\t\t</style>\n", "\t\t<center><svg width=\"850\" height=\"600\" id=\"fst_760d0ccc7588428cbd3361737fb8141a\"><g/></svg></center>\n", "\t\t<script>\n", "\t\t(function render_d3() {\n", "\t\tvar d3, dagreD3;\n", "\t\ttry { // requirejs is broken on external domains\n", "\t\t d3 = require('d3');\n", "\t\t dagreD3 = require('dagreD3');\n", "\t\t} catch (e) {\n", "\t\t // for google colab\n", "\t\t if(typeof window.d3 !== \"undefined\" && typeof window.dagreD3 !== \"undefined\") {\n", "\t\t\td3 = window.d3;\n", "\t\t\tdagreD3 = window.dagreD3;\n", "\t\t } else { // not loaded yet, so wait and try again\n", "\t\t\tsetTimeout(render_d3, 50);\n", "\t\t\treturn;\n", "\t\t }\n", "\t\t}\n", "\t\t//alert(\"loaded\");\n", "\t\tvar g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });\n", "\t\tg.setNode(\"0\", { label: \"0 / 1.0\" , shape: \"circle\" });\n", "g.node(\"0\").style = \"fill: #66c2a5\"; \n", "g.setNode(\"1\", { label: \"1\" , shape: \"circle\" });\n", "g.node(\"1\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"2\", { label: \"2\" , shape: \"circle\" });\n", "g.node(\"2\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"3\", { label: \"3\" , shape: \"circle\" });\n", "g.node(\"3\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"4\", { label: \"4\" , shape: \"circle\" });\n", "g.node(\"4\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"5\", { label: \"5\" , shape: \"circle\" });\n", "g.node(\"5\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"6\", { label: \"6 / 1.0\" , shape: \"circle\" });\n", "g.node(\"6\").style = \"fill: #fc8d62\"; \n", "g.setEdge(\"0\", \"1\", { arrowhead: \"vee\", label: \"(formal, formal) / 0.2\\n(natural, natural) / 0.3\" });\n", "g.setEdge(\"0\", \"2\", { arrowhead: \"vee\", label: \"(learning, learning) / 0.2\" });\n", "g.setEdge(\"0\", \"3\", { arrowhead: \"vee\", label: \"(data, data) / 0.3\" });\n", "g.setEdge(\"1\", \"2\", { arrowhead: \"vee\", label: \"(language, language) / 0.6\" });\n", "g.setEdge(\"1\", \"4\", { arrowhead: \"vee\", label: \"(languages, languages) / 0.4\" });\n", "g.setEdge(\"2\", \"5\", { arrowhead: \"vee\", label: \"(is, is) / 1.0\" });\n", "g.setEdge(\"3\", \"5\", { arrowhead: \"vee\", label: \"(is, is) / 0.5\\n(are, are) / 0.5\" });\n", "g.setEdge(\"4\", \"5\", { arrowhead: \"vee\", label: \"(are, are) / 1.0\" });\n", "g.setEdge(\"5\", \"6\", { arrowhead: \"vee\", label: \"(fun, fun) / 1.0\" });\n", "var svg = d3.select(\"#fst_760d0ccc7588428cbd3361737fb8141a\"); \n", "\n", "\t\tvar inner = svg.select(\"g\");\n", "\n", "\t\t// Set up zoom support\n", "\t\tvar zoom = d3.zoom().scaleExtent([0.3, 5]).on(\"zoom\", function() {\n", "\t\tinner.attr(\"transform\", d3.event.transform);\n", "\t\t});\n", "\t\tsvg.call(zoom);\n", "\n", "\t\t// Create the renderer\n", "\t\tvar render = new dagreD3.render();\n", "\n", "\t\t// Run the renderer. This is what draws the final graph.\n", "\t\trender(inner, g);\n", "\n", "\t\t// Center the graph\n", "\t\tvar initialScale = 0.75;\n", "\t\tsvg.call(zoom.transform, d3.zoomIdentity.translate(\n", "\t\t (svg.attr(\"width\") - g.graph().width * initialScale) / 2, 20).scale(initialScale));\n", "\n", "\t\tsvg.attr('height', g.graph().height * initialScale + 50);\n", "\t\t})();\n", "\n", "\t\t</script>\n", "\t\t" ] }, "metadata": {}, "execution_count": 35 } ] }, { "cell_type": "code", "source": [ "# A simple WFSA for transliteration\n", "\n", "sem = Real # semiring\n", "fst = FST(sem) # initialize WFST in the chosen semiring\n", "one, zero = sem.one, sem.zero # semiring one and zero\n", "\n", "# add transitions\n", "fst.add_arc(State(0), Sym('d'), Sym('data'), State(1), Real(0.5))\n", "fst.add_arc(State(0), Sym('d'), Sym('dew'), State(5), Real(0.5))\n", "\n", "fst.add_arc(State(1), Sym('ey'), Sym('ε'), State(2), Real(0.5))\n", "fst.add_arc(State(1), Sym('ae'), Sym('ε'), State(2), Real(0.5))\n", "\n", "fst.add_arc(State(2), Sym('t'), Sym('ε'), State(3), Real(0.7))\n", "fst.add_arc(State(2), Sym('dx'), Sym('ε'), State(3), Real(0.3))\n", "\n", "fst.add_arc(State(3), Sym('ax'), Sym('ε'), State(4), one)\n", "\n", "fst.add_arc(State(5), Sym('uw'), Sym('ε'), State(6), one)\n", "\n", "# initial and final weights\n", "fst.set_I(State(0), one)\n", "fst.set_F(State(4), one)\n", "fst.set_F(State(6), one)\n", "\n", "fst" ], "metadata": { "id": "6FpH94cRoGai", "colab": { "base_uri": "https://localhost:8080/", "height": 193 }, "outputId": "8a74e398-b7cb-4258-8771-8bb23aa8001f" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "WFSA(7 states, <class 'rayuela.base.semiring.Real'>)" ], "text/html": [ "\n", "\t\t<script>\n", "\t\ttry {\n", "\t\trequire.config({\n", "\t\tpaths: {\n", "\t\t\"d3\": \"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3\",\n", "\t\t\"dagreD3\": \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min\"\n", "\t\t}\n", "\t\t});\n", "\t\t} catch {\n", "\t\t [\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js\",\n", "\t\t \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js\"].forEach(function (src) {\n", "\t\t\tvar tag = document.createElement('script');\n", "\t\t\ttag.src = src;\n", "\t\t\tdocument.body.appendChild(tag);\n", "\t\t })\n", "\t\t}\n", "\t\ttry {\n", "\t\trequirejs(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\ttry {\n", "\t\trequire(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\t</script>\n", "\t\t<style>\n", "\t\t.node rect,\n", "\t\t.node circle,\n", "\t\t.node ellipse {\n", "\t\tstroke: #333;\n", "\t\tfill: #fff;\n", "\t\tstroke-width: 1px;\n", "\t\t}\n", "\n", "\t\t.edgePath path {\n", "\t\tstroke: #333;\n", "\t\tfill: #333;\n", "\t\tstroke-width: 1.5px;\n", "\t\t}\n", "\t\t</style>\n", "\t\t<center><svg width=\"850\" height=\"600\" id=\"fst_a11647f73cd347d9a912ce8a35ae4930\"><g/></svg></center>\n", "\t\t<script>\n", "\t\t(function render_d3() {\n", "\t\tvar d3, dagreD3;\n", "\t\ttry { // requirejs is broken on external domains\n", "\t\t d3 = require('d3');\n", "\t\t dagreD3 = require('dagreD3');\n", "\t\t} catch (e) {\n", "\t\t // for google colab\n", "\t\t if(typeof window.d3 !== \"undefined\" && typeof window.dagreD3 !== \"undefined\") {\n", "\t\t\td3 = window.d3;\n", "\t\t\tdagreD3 = window.dagreD3;\n", "\t\t } else { // not loaded yet, so wait and try again\n", "\t\t\tsetTimeout(render_d3, 50);\n", "\t\t\treturn;\n", "\t\t }\n", "\t\t}\n", "\t\t//alert(\"loaded\");\n", "\t\tvar g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });\n", "\t\tg.setNode(\"0\", { label: \"0 / 1.0\" , shape: \"circle\" });\n", "g.node(\"0\").style = \"fill: #66c2a5\"; \n", "g.setNode(\"1\", { label: \"1\" , shape: \"circle\" });\n", "g.node(\"1\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"2\", { label: \"2\" , shape: \"circle\" });\n", "g.node(\"2\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"3\", { label: \"3\" , shape: \"circle\" });\n", "g.node(\"3\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"5\", { label: \"5\" , shape: \"circle\" });\n", "g.node(\"5\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"4\", { label: \"4 / 1.0\" , shape: \"circle\" });\n", "g.node(\"4\").style = \"fill: #fc8d62\"; \n", "g.setNode(\"6\", { label: \"6 / 1.0\" , shape: \"circle\" });\n", "g.node(\"6\").style = \"fill: #fc8d62\"; \n", "g.setEdge(\"0\", \"1\", { arrowhead: \"vee\", label: \"(d, data) / 0.5\" });\n", "g.setEdge(\"0\", \"5\", { arrowhead: \"vee\", label: \"(d, dew) / 0.5\" });\n", "g.setEdge(\"1\", \"2\", { arrowhead: \"vee\", label: \"(ey, \\u00c3\\u017d\\u00c2\\u00b5) / 0.5\\n(ae, \\u00c3\\u017d\\u00c2\\u00b5) / 0.5\" });\n", "g.setEdge(\"2\", \"3\", { arrowhead: \"vee\", label: \"(t, \\u00c3\\u017d\\u00c2\\u00b5) / 0.7\\n(dx, \\u00c3\\u017d\\u00c2\\u00b5) / 0.3\" });\n", "g.setEdge(\"3\", \"4\", { arrowhead: \"vee\", label: \"(ax, \\u00c3\\u017d\\u00c2\\u00b5) / 1.0\" });\n", "g.setEdge(\"5\", \"6\", { arrowhead: \"vee\", label: \"(uw, \\u00c3\\u017d\\u00c2\\u00b5) / 1.0\" });\n", "var svg = d3.select(\"#fst_a11647f73cd347d9a912ce8a35ae4930\"); \n", "\n", "\t\tvar inner = svg.select(\"g\");\n", "\n", "\t\t// Set up zoom support\n", "\t\tvar zoom = d3.zoom().scaleExtent([0.3, 5]).on(\"zoom\", function() {\n", "\t\tinner.attr(\"transform\", d3.event.transform);\n", "\t\t});\n", "\t\tsvg.call(zoom);\n", "\n", "\t\t// Create the renderer\n", "\t\tvar render = new dagreD3.render();\n", "\n", "\t\t// Run the renderer. This is what draws the final graph.\n", "\t\trender(inner, g);\n", "\n", "\t\t// Center the graph\n", "\t\tvar initialScale = 0.75;\n", "\t\tsvg.call(zoom.transform, d3.zoomIdentity.translate(\n", "\t\t (svg.attr(\"width\") - g.graph().width * initialScale) / 2, 20).scale(initialScale));\n", "\n", "\t\tsvg.attr('height', g.graph().height * initialScale + 50);\n", "\t\t})();\n", "\n", "\t\t</script>\n", "\t\t" ] }, "metadata": {}, "execution_count": 36 } ] }, { "cell_type": "markdown", "source": [ "### Subquestion b) - String Transducer" ], "metadata": { "id": "9pioLluSYjJK" } }, { "cell_type": "code", "source": [ "def string_fst(s, semiring=Log):\n", " \"\"\" Takes a string as input and a semiring\n", " and returns a transducer encoding of the\n", " string\n", " \"\"\"\n", " fst = FST(semiring)\n", "\n", " # TODO: add arcs, initial and final weights\n", " # Arcs\n", " for i, char in enumerate(s):\n", " fst.set_arc(State(i), Sym(char), Sym(char), State(i+1), semiring(0.5))\n", "\n", " # Initial and final weights\n", " fst.set_I(State(0), semiring(0.5))\n", " fst.set_F(State(len(s)), semiring(0.5))\n", "\n", " return fst" ], "metadata": { "id": "bncEcn9mbiS9" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# you can visualise the transducer\n", "fst = string_fst(\"abcd\", semiring=Real)\n", "fst" ], "metadata": { "id": "xogIlSbTeuoU", "colab": { "base_uri": "https://localhost:8080/", "height": 115 }, "outputId": "d0398b66-3d26-46d6-e989-c3816ef67b72" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "WFSA(5 states, <class 'rayuela.base.semiring.Real'>)" ], "text/html": [ "\n", "\t\t<script>\n", "\t\ttry {\n", "\t\trequire.config({\n", "\t\tpaths: {\n", "\t\t\"d3\": \"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3\",\n", "\t\t\"dagreD3\": \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min\"\n", "\t\t}\n", "\t\t});\n", "\t\t} catch {\n", "\t\t [\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js\",\n", "\t\t \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js\"].forEach(function (src) {\n", "\t\t\tvar tag = document.createElement('script');\n", "\t\t\ttag.src = src;\n", "\t\t\tdocument.body.appendChild(tag);\n", "\t\t })\n", "\t\t}\n", "\t\ttry {\n", "\t\trequirejs(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\ttry {\n", "\t\trequire(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\t</script>\n", "\t\t<style>\n", "\t\t.node rect,\n", "\t\t.node circle,\n", "\t\t.node ellipse {\n", "\t\tstroke: #333;\n", "\t\tfill: #fff;\n", "\t\tstroke-width: 1px;\n", "\t\t}\n", "\n", "\t\t.edgePath path {\n", "\t\tstroke: #333;\n", "\t\tfill: #333;\n", "\t\tstroke-width: 1.5px;\n", "\t\t}\n", "\t\t</style>\n", "\t\t<center><svg width=\"850\" height=\"600\" id=\"fst_63d7ace7b1d840bebf2681770f20c84d\"><g/></svg></center>\n", "\t\t<script>\n", "\t\t(function render_d3() {\n", "\t\tvar d3, dagreD3;\n", "\t\ttry { // requirejs is broken on external domains\n", "\t\t d3 = require('d3');\n", "\t\t dagreD3 = require('dagreD3');\n", "\t\t} catch (e) {\n", "\t\t // for google colab\n", "\t\t if(typeof window.d3 !== \"undefined\" && typeof window.dagreD3 !== \"undefined\") {\n", "\t\t\td3 = window.d3;\n", "\t\t\tdagreD3 = window.dagreD3;\n", "\t\t } else { // not loaded yet, so wait and try again\n", "\t\t\tsetTimeout(render_d3, 50);\n", "\t\t\treturn;\n", "\t\t }\n", "\t\t}\n", "\t\t//alert(\"loaded\");\n", "\t\tvar g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });\n", "\t\tg.setNode(\"0\", { label: \"0 / 0.5\" , shape: \"circle\" });\n", "g.node(\"0\").style = \"fill: #66c2a5\"; \n", "g.setNode(\"1\", { label: \"1\" , shape: \"circle\" });\n", "g.node(\"1\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"2\", { label: \"2\" , shape: \"circle\" });\n", "g.node(\"2\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"3\", { label: \"3\" , shape: \"circle\" });\n", "g.node(\"3\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"4\", { label: \"4 / 0.5\" , shape: \"circle\" });\n", "g.node(\"4\").style = \"fill: #fc8d62\"; \n", "g.setEdge(\"0\", \"1\", { arrowhead: \"vee\", label: \"(a, a) / 0.5\" });\n", "g.setEdge(\"1\", \"2\", { arrowhead: \"vee\", label: \"(b, b) / 0.5\" });\n", "g.setEdge(\"2\", \"3\", { arrowhead: \"vee\", label: \"(c, c) / 0.5\" });\n", "g.setEdge(\"3\", \"4\", { arrowhead: \"vee\", label: \"(d, d) / 0.5\" });\n", "var svg = d3.select(\"#fst_63d7ace7b1d840bebf2681770f20c84d\"); \n", "\n", "\t\tvar inner = svg.select(\"g\");\n", "\n", "\t\t// Set up zoom support\n", "\t\tvar zoom = d3.zoom().scaleExtent([0.3, 5]).on(\"zoom\", function() {\n", "\t\tinner.attr(\"transform\", d3.event.transform);\n", "\t\t});\n", "\t\tsvg.call(zoom);\n", "\n", "\t\t// Create the renderer\n", "\t\tvar render = new dagreD3.render();\n", "\n", "\t\t// Run the renderer. This is what draws the final graph.\n", "\t\trender(inner, g);\n", "\n", "\t\t// Center the graph\n", "\t\tvar initialScale = 0.75;\n", "\t\tsvg.call(zoom.transform, d3.zoomIdentity.translate(\n", "\t\t (svg.attr(\"width\") - g.graph().width * initialScale) / 2, 20).scale(initialScale));\n", "\n", "\t\tsvg.attr('height', g.graph().height * initialScale + 50);\n", "\t\t})();\n", "\n", "\t\t</script>\n", "\t\t" ] }, "metadata": {}, "execution_count": 6 } ] }, { "cell_type": "markdown", "source": [ "### Subquestion c) - Edit Distance Transducer" ], "metadata": { "id": "We9mAj-SYrz3" } }, { "cell_type": "markdown", "source": [ "As we will not learn the weights on the arcs, you can set them to some pre-defined constants. You should choose the weights such that the pathsum that needs to be computed in e) does not diverge (this is caused by the weights of the self-loops in the transducer). " ], "metadata": { "id": "23AP7EiJrJ2B" } }, { "cell_type": "code", "source": [ "def edit_distance_fst(source_alphabet, target_alphabet, semiring=Log):\n", " \"\"\" Takes as input two sets of characters (source and target \n", " alphabets) and a semiring and returns an edit-distance transducer\n", " \"\"\"\n", " \n", " fst = FST(semiring)\n", " \n", " # TODO: add arcs, initial and final weights\n", "\n", " # Add arcs from each state to itself when output is epsilon (deletion):\n", " for target_char_in in source_alphabet:\n", " fst.set_arc(State(0), Sym(target_char_in), ε, State(0), semiring.one)\n", "\n", " for i, target_char in enumerate(target_alphabet, start=1): # state i for each char\n", " for source_char in source_alphabet:\n", " fst.set_arc(State(i), Sym(source_char), ε, State(i), semiring.one)\n", "\n", " # Add arcs from each state to all other states\n", " for j, target_char_target in enumerate(target_alphabet, start=1):\n", " for input_char in source_alphabet:\n", " fst.set_arc(State(0), Sym(input_char), Sym(target_char_target), State(j), semiring.one)\n", " fst.set_arc(State(0), ε, Sym(target_char_target), State(j), semiring.one)\n", "\n", " for i, target_char_source in enumerate(target_alphabet, start=1):\n", " for j, target_char_target in enumerate(target_alphabet, start=1):\n", " if i!=j:\n", " for input_char in source_alphabet:\n", " fst.set_arc(State(i), Sym(input_char), Sym(target_char_target), State(j), semiring.one)\n", " fst.set_arc(State(i), ε, Sym(target_char_target), State(j), semiring.one)\n", " \n", " # Initial and final weights\n", " fst.set_I(State(0), semiring.one)\n", " fst.set_F(State(0), semiring.one)\n", "\n", " for i, _ in enumerate(target_alphabet, start=1):\n", " fst.set_F(State(i), semiring.one)\n", " \n", " return fst" ], "metadata": { "id": "TG1G9JdUfEK_" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "fst = edit_distance_fst({'a', 'b', 'c'}, {'d', 'e'}, semiring=Real)\n", "fst" ], "metadata": { "id": "eB2rZ_7xhB8o", "colab": { "base_uri": "https://localhost:8080/", "height": 279 }, "outputId": "af29eaf1-cbe7-400e-9b5d-74287514d58d" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "WFSA(3 states, <class 'rayuela.base.semiring.Real'>)" ], "text/html": [ "\n", "\t\t<script>\n", "\t\ttry {\n", "\t\trequire.config({\n", "\t\tpaths: {\n", "\t\t\"d3\": \"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3\",\n", "\t\t\"dagreD3\": \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min\"\n", "\t\t}\n", "\t\t});\n", "\t\t} catch {\n", "\t\t [\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js\",\n", "\t\t \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js\"].forEach(function (src) {\n", "\t\t\tvar tag = document.createElement('script');\n", "\t\t\ttag.src = src;\n", "\t\t\tdocument.body.appendChild(tag);\n", "\t\t })\n", "\t\t}\n", "\t\ttry {\n", "\t\trequirejs(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\ttry {\n", "\t\trequire(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\t</script>\n", "\t\t<style>\n", "\t\t.node rect,\n", "\t\t.node circle,\n", "\t\t.node ellipse {\n", "\t\tstroke: #333;\n", "\t\tfill: #fff;\n", "\t\tstroke-width: 1px;\n", "\t\t}\n", "\n", "\t\t.edgePath path {\n", "\t\tstroke: #333;\n", "\t\tfill: #333;\n", "\t\tstroke-width: 1.5px;\n", "\t\t}\n", "\t\t</style>\n", "\t\t<center><svg width=\"850\" height=\"600\" id=\"fst_221dc595b57c4261b22064809baa8492\"><g/></svg></center>\n", "\t\t<script>\n", "\t\t(function render_d3() {\n", "\t\tvar d3, dagreD3;\n", "\t\ttry { // requirejs is broken on external domains\n", "\t\t d3 = require('d3');\n", "\t\t dagreD3 = require('dagreD3');\n", "\t\t} catch (e) {\n", "\t\t // for google colab\n", "\t\t if(typeof window.d3 !== \"undefined\" && typeof window.dagreD3 !== \"undefined\") {\n", "\t\t\td3 = window.d3;\n", "\t\t\tdagreD3 = window.dagreD3;\n", "\t\t } else { // not loaded yet, so wait and try again\n", "\t\t\tsetTimeout(render_d3, 50);\n", "\t\t\treturn;\n", "\t\t }\n", "\t\t}\n", "\t\t//alert(\"loaded\");\n", "\t\tvar g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });\n", "\t\tg.setNode(\"0\", { label: \"0 / [1.0 / 1.0]\" , shape: \"circle\" });\n", "g.node(\"0\").style = \"fill: #af8dc3\"; \n", "g.setNode(\"1\", { label: \"1 / 1.0\" , shape: \"circle\" });\n", "g.node(\"1\").style = \"fill: #fc8d62\"; \n", "g.setNode(\"2\", { label: \"2 / 1.0\" , shape: \"circle\" });\n", "g.node(\"2\").style = \"fill: #fc8d62\"; \n", "g.setEdge(\"0\", \"0\", { arrowhead: \"vee\", label: \"(c, \\u03b5) / 1.0\\n(b, \\u03b5) / 1.0\\n(a, \\u03b5) / 1.0\" });\n", "g.setEdge(\"0\", \"1\", { arrowhead: \"vee\", label: \"(c, d) / 1.0\\n(b, d) / 1.0\\n(a, d) / 1.0\\n(\\u03b5, d) / 1.0\" });\n", "g.setEdge(\"0\", \"2\", { arrowhead: \"vee\", label: \"(c, e) / 1.0\\n(b, e) / 1.0\\n(a, e) / 1.0\\n(\\u03b5, e) / 1.0\" });\n", "g.setEdge(\"1\", \"1\", { arrowhead: \"vee\", label: \"(c, \\u03b5) / 1.0\\n(b, \\u03b5) / 1.0\\n(a, \\u03b5) / 1.0\" });\n", "g.setEdge(\"1\", \"2\", { arrowhead: \"vee\", label: \"(c, e) / 1.0\\n(b, e) / 1.0\\n(a, e) / 1.0\\n(\\u03b5, e) / 1.0\" });\n", "g.setEdge(\"2\", \"2\", { arrowhead: \"vee\", label: \"(c, \\u03b5) / 1.0\\n(b, \\u03b5) / 1.0\\n(a, \\u03b5) / 1.0\" });\n", "g.setEdge(\"2\", \"1\", { arrowhead: \"vee\", label: \"(c, d) / 1.0\\n(b, d) / 1.0\\n(a, d) / 1.0\\n(\\u03b5, d) / 1.0\" });\n", "var svg = d3.select(\"#fst_221dc595b57c4261b22064809baa8492\"); \n", "\n", "\t\tvar inner = svg.select(\"g\");\n", "\n", "\t\t// Set up zoom support\n", "\t\tvar zoom = d3.zoom().scaleExtent([0.3, 5]).on(\"zoom\", function() {\n", "\t\tinner.attr(\"transform\", d3.event.transform);\n", "\t\t});\n", "\t\tsvg.call(zoom);\n", "\n", "\t\t// Create the renderer\n", "\t\tvar render = new dagreD3.render();\n", "\n", "\t\t// Run the renderer. This is what draws the final graph.\n", "\t\trender(inner, g);\n", "\n", "\t\t// Center the graph\n", "\t\tvar initialScale = 0.75;\n", "\t\tsvg.call(zoom.transform, d3.zoomIdentity.translate(\n", "\t\t (svg.attr(\"width\") - g.graph().width * initialScale) / 2, 20).scale(initialScale));\n", "\n", "\t\tsvg.attr('height', g.graph().height * initialScale + 50);\n", "\t\t})();\n", "\n", "\t\t</script>\n", "\t\t" ] }, "metadata": {}, "execution_count": 8 } ] }, { "cell_type": "markdown", "source": [ "### Subquestion d) - Composition" ], "metadata": { "id": "RCTCHqJLYwyh" } }, { "cell_type": "markdown", "source": [ "We provide some composition test cases for you to inspect." ], "metadata": { "id": "lzi_UzOx2yLt" } }, { "cell_type": "code", "source": [ "with open('test_cases.pkl', 'rb') as in_file:\n", " examples = dill.load(in_file)" ], "metadata": { "id": "INUf9u0626E7" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "def compose(fst1, fst2):\n", " \"\"\" Takes as input two transducers and returns\n", " their composition\n", " \"\"\"\n", " # The machines must be in the same semiring\n", " assert fst1.R == fst2.R\n", "\n", " comp_fst = FST(R=fst1.R)\n", "\n", " # TODO: implement composition\n", " fst1_copy = fst1.copy()\n", " fst2_copy = fst2.copy()\n", "\n", " # Add initial state pairs to the stack and the visited set\n", " stack = []\n", " visited = set()\n", " for init_pair_1 in fst1_copy.I:\n", " for init_pair_2 in fst2_copy.I:\n", " stack.append((init_pair_1[0], init_pair_2[0], State(0)))\n", " visited.add((init_pair_1[0], init_pair_2[0], State(0)))\n", "\n", " new_init_state = PairState(init_pair_1[0], init_pair_2[0])\n", " init_weight = fst1_copy.λ[init_pair_1[0]]*fst2_copy.λ[init_pair_2[0]]\n", " comp_fst.set_I(new_init_state, init_weight)\n", "\n", " # Rename epsilon edges in T2: \n", " for start_state in fst2_copy.δ.keys():\n", " temp = fst2_copy.δ[start_state].copy()\n", " for input_output in temp:\n", " if input_output[0] == ε:\n", " fst2_copy.δ[start_state][(ε_1, input_output[1])] = fst2_copy.δ[start_state][input_output]\n", " del fst2_copy.δ[start_state][input_output]\n", "\n", " # Rename epsilon edges in T1: \n", " for start_state in fst1_copy.δ.keys():\n", " temp = fst1_copy.δ[start_state].copy()\n", " for input_output in temp:\n", " if input_output[1] == ε:\n", " fst1_copy.δ[start_state][(input_output[0], ε_2)] = fst1_copy.δ[start_state][input_output]\n", " del fst1_copy.δ[start_state][input_output]\n", "\n", " # Augment the epsilon transitions\n", " for state in fst1_copy.Q:\n", " fst1_copy.set_arc(state, ε, ε_1, state, fst1_copy.R.one)\n", " \n", " for state in fst2_copy.Q:\n", " fst2_copy.set_arc(state, ε_2, ε, state, fst2_copy.R.one)\n", " \n", " # Main loop\n", " while stack:\n", " q1, q2, qf = stack.pop()\n", "\n", " q1_transitions = [(ab, neighbour,w) for (ab, neighbour, w) in fst1_copy.arcs(q1)]\n", " q2_transitions = [(ab, neighbour,w) for (ab, neighbour,w) in fst2_copy.arcs(q2)]\n", "\n", " val_trans = []\n", " for arc1 in q1_transitions:\n", " a, b = arc1[0]\n", " start = arc1[1]\n", " w1 = arc1[2]\n", " for arc2 in q2_transitions:\n", " c, d = arc2[0]\n", " end = arc2[1]\n", " w2 = arc2[2]\n", "\n", " if epsilon_filter(b, c, qf) != State(\"⊥\"):\n", " val_trans.append(((start, (a,b), w1), (end, (c,d) ,w2)))\n", "\n", " for (start, (a,b), w1), (end, (c,d), w2) in val_trans:\n", " comp_fst.set_arc(PairState(q1,q2), a, d, PairState(start,end), w1*w2)\n", " \n", " qfp = epsilon_filter(b, c, qf)\n", "\n", " if (start,end,qfp) not in visited:\n", " stack.append((start,end,qfp))\n", " visited.add((start,end,qfp))\n", "\n", " # Set final states\n", " for pair in comp_fst.Q:\n", " wf = fst1_copy.ρ[pair.state1] * fst2_copy.ρ[pair.state2]\n", " if wf != fst1_copy.R.zero:\n", " comp_fst.add_F(pair, wf)\n", "\n", " return comp_fst" ], "metadata": { "id": "M37nojb6jsxk" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "example_id = 4" ], "metadata": { "id": "uPCxdu7SeUfa" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# FST 1\n", "examples[example_id]['fst1']['fst']" ], "metadata": { "id": "tdDfLbCT3GSL", "colab": { "base_uri": "https://localhost:8080/", "height": 235 }, "outputId": "3326308d-3bd9-4a94-89a1-82ebd5fb70b2" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "WFSA(2 states, <class 'rayuela.base.semiring.Real'>)" ], "text/html": [ "\n", "\t\t<script>\n", "\t\ttry {\n", "\t\trequire.config({\n", "\t\tpaths: {\n", "\t\t\"d3\": \"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3\",\n", "\t\t\"dagreD3\": \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min\"\n", "\t\t}\n", "\t\t});\n", "\t\t} catch {\n", "\t\t [\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js\",\n", "\t\t \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js\"].forEach(function (src) {\n", "\t\t\tvar tag = document.createElement('script');\n", "\t\t\ttag.src = src;\n", "\t\t\tdocument.body.appendChild(tag);\n", "\t\t })\n", "\t\t}\n", "\t\ttry {\n", "\t\trequirejs(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\ttry {\n", "\t\trequire(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\t</script>\n", "\t\t<style>\n", "\t\t.node rect,\n", "\t\t.node circle,\n", "\t\t.node ellipse {\n", "\t\tstroke: #333;\n", "\t\tfill: #fff;\n", "\t\tstroke-width: 1px;\n", "\t\t}\n", "\n", "\t\t.edgePath path {\n", "\t\tstroke: #333;\n", "\t\tfill: #333;\n", "\t\tstroke-width: 1.5px;\n", "\t\t}\n", "\t\t</style>\n", "\t\t<center><svg width=\"850\" height=\"600\" id=\"fst_66997286964c4373becee73a9740c6b1\"><g/></svg></center>\n", "\t\t<script>\n", "\t\t(function render_d3() {\n", "\t\tvar d3, dagreD3;\n", "\t\ttry { // requirejs is broken on external domains\n", "\t\t d3 = require('d3');\n", "\t\t dagreD3 = require('dagreD3');\n", "\t\t} catch (e) {\n", "\t\t // for google colab\n", "\t\t if(typeof window.d3 !== \"undefined\" && typeof window.dagreD3 !== \"undefined\") {\n", "\t\t\td3 = window.d3;\n", "\t\t\tdagreD3 = window.dagreD3;\n", "\t\t } else { // not loaded yet, so wait and try again\n", "\t\t\tsetTimeout(render_d3, 50);\n", "\t\t\treturn;\n", "\t\t }\n", "\t\t}\n", "\t\t//alert(\"loaded\");\n", "\t\tvar g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });\n", "\t\tg.setNode(\"0\", { label: \"0 / 0.049\" , shape: \"circle\" });\n", "g.node(\"0\").style = \"fill: #66c2a5\"; \n", "g.setNode(\"1\", { label: \"1 / 0.113\" , shape: \"circle\" });\n", "g.node(\"1\").style = \"fill: #fc8d62\"; \n", "g.setEdge(\"0\", \"1\", { arrowhead: \"vee\", label: \"(a, b) / 0.054\\n(\\u03b5, a) / 0.164\" });\n", "g.setEdge(\"1\", \"1\", { arrowhead: \"vee\", label: \"(b, \\u03b5) / 0.092\\n(a, a) / 0.036\" });\n", "var svg = d3.select(\"#fst_66997286964c4373becee73a9740c6b1\"); \n", "\n", "\t\tvar inner = svg.select(\"g\");\n", "\n", "\t\t// Set up zoom support\n", "\t\tvar zoom = d3.zoom().scaleExtent([0.3, 5]).on(\"zoom\", function() {\n", "\t\tinner.attr(\"transform\", d3.event.transform);\n", "\t\t});\n", "\t\tsvg.call(zoom);\n", "\n", "\t\t// Create the renderer\n", "\t\tvar render = new dagreD3.render();\n", "\n", "\t\t// Run the renderer. This is what draws the final graph.\n", "\t\trender(inner, g);\n", "\n", "\t\t// Center the graph\n", "\t\tvar initialScale = 0.75;\n", "\t\tsvg.call(zoom.transform, d3.zoomIdentity.translate(\n", "\t\t (svg.attr(\"width\") - g.graph().width * initialScale) / 2, 20).scale(initialScale));\n", "\n", "\t\tsvg.attr('height', g.graph().height * initialScale + 50);\n", "\t\t})();\n", "\n", "\t\t</script>\n", "\t\t" ] }, "metadata": {}, "execution_count": 44 } ] }, { "cell_type": "code", "source": [ "# FST 2\n", "examples[example_id]['fst2']['fst']" ], "metadata": { "id": "08ShFifD3Lhm", "colab": { "base_uri": "https://localhost:8080/", "height": 235 }, "outputId": "eb0bd23c-bea9-49bc-f792-59a0cbf4af3e" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "WFSA(2 states, <class 'rayuela.base.semiring.Real'>)" ], "text/html": [ "\n", "\t\t<script>\n", "\t\ttry {\n", "\t\trequire.config({\n", "\t\tpaths: {\n", "\t\t\"d3\": \"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3\",\n", "\t\t\"dagreD3\": \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min\"\n", "\t\t}\n", "\t\t});\n", "\t\t} catch {\n", "\t\t [\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js\",\n", "\t\t \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js\"].forEach(function (src) {\n", "\t\t\tvar tag = document.createElement('script');\n", "\t\t\ttag.src = src;\n", "\t\t\tdocument.body.appendChild(tag);\n", "\t\t })\n", "\t\t}\n", "\t\ttry {\n", "\t\trequirejs(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\ttry {\n", "\t\trequire(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\t</script>\n", "\t\t<style>\n", "\t\t.node rect,\n", "\t\t.node circle,\n", "\t\t.node ellipse {\n", "\t\tstroke: #333;\n", "\t\tfill: #fff;\n", "\t\tstroke-width: 1px;\n", "\t\t}\n", "\n", "\t\t.edgePath path {\n", "\t\tstroke: #333;\n", "\t\tfill: #333;\n", "\t\tstroke-width: 1.5px;\n", "\t\t}\n", "\t\t</style>\n", "\t\t<center><svg width=\"850\" height=\"600\" id=\"fst_78dae57071e044e5ab08974378f60cfc\"><g/></svg></center>\n", "\t\t<script>\n", "\t\t(function render_d3() {\n", "\t\tvar d3, dagreD3;\n", "\t\ttry { // requirejs is broken on external domains\n", "\t\t d3 = require('d3');\n", "\t\t dagreD3 = require('dagreD3');\n", "\t\t} catch (e) {\n", "\t\t // for google colab\n", "\t\t if(typeof window.d3 !== \"undefined\" && typeof window.dagreD3 !== \"undefined\") {\n", "\t\t\td3 = window.d3;\n", "\t\t\tdagreD3 = window.dagreD3;\n", "\t\t } else { // not loaded yet, so wait and try again\n", "\t\t\tsetTimeout(render_d3, 50);\n", "\t\t\treturn;\n", "\t\t }\n", "\t\t}\n", "\t\t//alert(\"loaded\");\n", "\t\tvar g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });\n", "\t\tg.setNode(\"0\", { label: \"0 / 0.086\" , shape: \"circle\" });\n", "g.node(\"0\").style = \"fill: #66c2a5\"; \n", "g.setNode(\"1\", { label: \"1 / 0.077\" , shape: \"circle\" });\n", "g.node(\"1\").style = \"fill: #fc8d62\"; \n", "g.setEdge(\"0\", \"1\", { arrowhead: \"vee\", label: \"(b, a) / 0.032\\n(a, \\u03b5) / 0.096\" });\n", "g.setEdge(\"1\", \"1\", { arrowhead: \"vee\", label: \"(b, a) / 0.091\\n(a, a) / 0.059\" });\n", "var svg = d3.select(\"#fst_78dae57071e044e5ab08974378f60cfc\"); \n", "\n", "\t\tvar inner = svg.select(\"g\");\n", "\n", "\t\t// Set up zoom support\n", "\t\tvar zoom = d3.zoom().scaleExtent([0.3, 5]).on(\"zoom\", function() {\n", "\t\tinner.attr(\"transform\", d3.event.transform);\n", "\t\t});\n", "\t\tsvg.call(zoom);\n", "\n", "\t\t// Create the renderer\n", "\t\tvar render = new dagreD3.render();\n", "\n", "\t\t// Run the renderer. This is what draws the final graph.\n", "\t\trender(inner, g);\n", "\n", "\t\t// Center the graph\n", "\t\tvar initialScale = 0.75;\n", "\t\tsvg.call(zoom.transform, d3.zoomIdentity.translate(\n", "\t\t (svg.attr(\"width\") - g.graph().width * initialScale) / 2, 20).scale(initialScale));\n", "\n", "\t\tsvg.attr('height', g.graph().height * initialScale + 50);\n", "\t\t})();\n", "\n", "\t\t</script>\n", "\t\t" ] }, "metadata": {}, "execution_count": 45 } ] }, { "cell_type": "code", "source": [ "# composition\n", "examples[example_id]['composition']['fst']" ], "metadata": { "id": "0Ma7QG983NBc", "colab": { "base_uri": "https://localhost:8080/", "height": 285 }, "outputId": "b52103c7-df79-4ea6-84e7-5f5d443679cc" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "WFSA(4 states, <class 'rayuela.base.semiring.Boolean'>)" ], "text/html": [ "\n", "\t\t<script>\n", "\t\ttry {\n", "\t\trequire.config({\n", "\t\tpaths: {\n", "\t\t\"d3\": \"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3\",\n", "\t\t\"dagreD3\": \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min\"\n", "\t\t}\n", "\t\t});\n", "\t\t} catch {\n", "\t\t [\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js\",\n", "\t\t \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js\"].forEach(function (src) {\n", "\t\t\tvar tag = document.createElement('script');\n", "\t\t\ttag.src = src;\n", "\t\t\tdocument.body.appendChild(tag);\n", "\t\t })\n", "\t\t}\n", "\t\ttry {\n", "\t\trequirejs(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\ttry {\n", "\t\trequire(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\t</script>\n", "\t\t<style>\n", "\t\t.node rect,\n", "\t\t.node circle,\n", "\t\t.node ellipse {\n", "\t\tstroke: #333;\n", "\t\tfill: #fff;\n", "\t\tstroke-width: 1px;\n", "\t\t}\n", "\n", "\t\t.edgePath path {\n", "\t\tstroke: #333;\n", "\t\tfill: #333;\n", "\t\tstroke-width: 1.5px;\n", "\t\t}\n", "\t\t</style>\n", "\t\t<center><svg width=\"850\" height=\"600\" id=\"fst_da6ea591c1d54b908651bc75fb601148\"><g/></svg></center>\n", "\t\t<script>\n", "\t\t(function render_d3() {\n", "\t\tvar d3, dagreD3;\n", "\t\ttry { // requirejs is broken on external domains\n", "\t\t d3 = require('d3');\n", "\t\t dagreD3 = require('dagreD3');\n", "\t\t} catch (e) {\n", "\t\t // for google colab\n", "\t\t if(typeof window.d3 !== \"undefined\" && typeof window.dagreD3 !== \"undefined\") {\n", "\t\t\td3 = window.d3;\n", "\t\t\tdagreD3 = window.dagreD3;\n", "\t\t } else { // not loaded yet, so wait and try again\n", "\t\t\tsetTimeout(render_d3, 50);\n", "\t\t\treturn;\n", "\t\t }\n", "\t\t}\n", "\t\t//alert(\"loaded\");\n", "\t\tvar g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });\n", "\t\tg.setNode(\"( 0, 0 )\", { label: \"( 0, 0 ) / True\" , shape: \"circle\" });\n", "g.node(\"( 0, 0 )\").style = \"fill: #66c2a5\"; \n", "g.setNode(\"( 0, 1 )\", { label: \"( 0, 1 )\" , shape: \"circle\" });\n", "g.node(\"( 0, 1 )\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"( 1, 0 )\", { label: \"( 1, 0 )\" , shape: \"circle\" });\n", "g.node(\"( 1, 0 )\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"( 1, 1 )\", { label: \"( 1, 1 ) / True\" , shape: \"circle\" });\n", "g.node(\"( 1, 1 )\").style = \"fill: #fc8d62\"; \n", "g.setEdge(\"( 0, 1 )\", \"( 0, 0 )\", { arrowhead: \"vee\", label: \"(b, \\u03b5) / True\\n(a, b) / True\" });\n", "g.setEdge(\"( 0, 1 )\", \"( 1, 0 )\", { arrowhead: \"vee\", label: \"(\\u03b5, \\u03b5) / True\" });\n", "g.setEdge(\"( 1, 0 )\", \"( 1, 1 )\", { arrowhead: \"vee\", label: \"(\\u03b5, a) / True\\n(\\u03b5, b) / True\\n(b, b) / True\\n(a, a) / True\" });\n", "g.setEdge(\"( 1, 0 )\", \"( 1, 0 )\", { arrowhead: \"vee\", label: \"(a, \\u03b5) / True\" });\n", "g.setEdge(\"( 1, 1 )\", \"( 1, 0 )\", { arrowhead: \"vee\", label: \"(\\u03b5, \\u03b5) / True\\n(b, \\u03b5) / True\" });\n", "g.setEdge(\"( 1, 1 )\", \"( 1, 1 )\", { arrowhead: \"vee\", label: \"(a, \\u03b5) / True\" });\n", "g.setEdge(\"( 0, 0 )\", \"( 0, 1 )\", { arrowhead: \"vee\", label: \"(\\u03b5, a) / True\\n(b, b) / True\\n(a, \\u03b5) / True\" });\n", "g.setEdge(\"( 0, 0 )\", \"( 1, 1 )\", { arrowhead: \"vee\", label: \"(\\u03b5, b) / True\" });\n", "var svg = d3.select(\"#fst_da6ea591c1d54b908651bc75fb601148\"); \n", "\n", "\t\tvar inner = svg.select(\"g\");\n", "\n", "\t\t// Set up zoom support\n", "\t\tvar zoom = d3.zoom().scaleExtent([0.3, 5]).on(\"zoom\", function() {\n", "\t\tinner.attr(\"transform\", d3.event.transform);\n", "\t\t});\n", "\t\tsvg.call(zoom);\n", "\n", "\t\t// Create the renderer\n", "\t\tvar render = new dagreD3.render();\n", "\n", "\t\t// Run the renderer. This is what draws the final graph.\n", "\t\trender(inner, g);\n", "\n", "\t\t// Center the graph\n", "\t\tvar initialScale = 0.75;\n", "\t\tsvg.call(zoom.transform, d3.zoomIdentity.translate(\n", "\t\t (svg.attr(\"width\") - g.graph().width * initialScale) / 2, 20).scale(initialScale));\n", "\n", "\t\tsvg.attr('height', g.graph().height * initialScale + 50);\n", "\t\t})();\n", "\n", "\t\t</script>\n", "\t\t" ] }, "metadata": {}, "execution_count": 24 } ] }, { "cell_type": "code", "source": [ "comp_fst = compose(examples[example_id]['fst1']['fst'], examples[example_id]['fst2']['fst'])\n", "comp_fst" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 285 }, "id": "2Q3h9CUJl1A0", "outputId": "455f59c9-a519-40b8-83b7-b8e0027eb263" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "WFSA(4 states, <class 'rayuela.base.semiring.Boolean'>)" ], "text/html": [ "\n", "\t\t<script>\n", "\t\ttry {\n", "\t\trequire.config({\n", "\t\tpaths: {\n", "\t\t\"d3\": \"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3\",\n", "\t\t\"dagreD3\": \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min\"\n", "\t\t}\n", "\t\t});\n", "\t\t} catch {\n", "\t\t [\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js\",\n", "\t\t \"https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js\"].forEach(function (src) {\n", "\t\t\tvar tag = document.createElement('script');\n", "\t\t\ttag.src = src;\n", "\t\t\tdocument.body.appendChild(tag);\n", "\t\t })\n", "\t\t}\n", "\t\ttry {\n", "\t\trequirejs(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\ttry {\n", "\t\trequire(['d3', 'dagreD3'], function() {});\n", "\t\t} catch (e) {}\n", "\t\t</script>\n", "\t\t<style>\n", "\t\t.node rect,\n", "\t\t.node circle,\n", "\t\t.node ellipse {\n", "\t\tstroke: #333;\n", "\t\tfill: #fff;\n", "\t\tstroke-width: 1px;\n", "\t\t}\n", "\n", "\t\t.edgePath path {\n", "\t\tstroke: #333;\n", "\t\tfill: #333;\n", "\t\tstroke-width: 1.5px;\n", "\t\t}\n", "\t\t</style>\n", "\t\t<center><svg width=\"850\" height=\"600\" id=\"fst_a81bc62a74a140e48d44aa517929b67e\"><g/></svg></center>\n", "\t\t<script>\n", "\t\t(function render_d3() {\n", "\t\tvar d3, dagreD3;\n", "\t\ttry { // requirejs is broken on external domains\n", "\t\t d3 = require('d3');\n", "\t\t dagreD3 = require('dagreD3');\n", "\t\t} catch (e) {\n", "\t\t // for google colab\n", "\t\t if(typeof window.d3 !== \"undefined\" && typeof window.dagreD3 !== \"undefined\") {\n", "\t\t\td3 = window.d3;\n", "\t\t\tdagreD3 = window.dagreD3;\n", "\t\t } else { // not loaded yet, so wait and try again\n", "\t\t\tsetTimeout(render_d3, 50);\n", "\t\t\treturn;\n", "\t\t }\n", "\t\t}\n", "\t\t//alert(\"loaded\");\n", "\t\tvar g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });\n", "\t\tg.setNode(\"( 0, 0 )\", { label: \"( 0, 0 ) / True\" , shape: \"circle\" });\n", "g.node(\"( 0, 0 )\").style = \"fill: #66c2a5\"; \n", "g.setNode(\"( 0, 1 )\", { label: \"( 0, 1 )\" , shape: \"circle\" });\n", "g.node(\"( 0, 1 )\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"( 1, 0 )\", { label: \"( 1, 0 )\" , shape: \"circle\" });\n", "g.node(\"( 1, 0 )\").style = \"fill: #8da0cb\"; \n", "g.setNode(\"( 1, 1 )\", { label: \"( 1, 1 ) / True\" , shape: \"circle\" });\n", "g.node(\"( 1, 1 )\").style = \"fill: #fc8d62\"; \n", "g.setEdge(\"( 0, 1 )\", \"( 0, 0 )\", { arrowhead: \"vee\", label: \"(b, \\u03b5) / True\\n(a, b) / True\" });\n", "g.setEdge(\"( 0, 1 )\", \"( 1, 0 )\", { arrowhead: \"vee\", label: \"(\\u03b5, \\u03b5) / True\" });\n", "g.setEdge(\"( 1, 0 )\", \"( 1, 1 )\", { arrowhead: \"vee\", label: \"(\\u03b5, b) / True\\n(b, b) / True\\n(a, a) / True\\n(\\u03b5, a) / True\" });\n", "g.setEdge(\"( 1, 0 )\", \"( 1, 0 )\", { arrowhead: \"vee\", label: \"(a, \\u03b5) / True\" });\n", "g.setEdge(\"( 1, 1 )\", \"( 1, 0 )\", { arrowhead: \"vee\", label: \"(\\u03b5, \\u03b5) / True\\n(b, \\u03b5) / True\" });\n", "g.setEdge(\"( 1, 1 )\", \"( 1, 1 )\", { arrowhead: \"vee\", label: \"(a, \\u03b5) / True\" });\n", "g.setEdge(\"( 0, 0 )\", \"( 0, 1 )\", { arrowhead: \"vee\", label: \"(b, b) / True\\n(a, \\u03b5) / True\\n(\\u03b5, a) / True\" });\n", "g.setEdge(\"( 0, 0 )\", \"( 1, 1 )\", { arrowhead: \"vee\", label: \"(\\u03b5, b) / True\" });\n", "var svg = d3.select(\"#fst_a81bc62a74a140e48d44aa517929b67e\"); \n", "\n", "\t\tvar inner = svg.select(\"g\");\n", "\n", "\t\t// Set up zoom support\n", "\t\tvar zoom = d3.zoom().scaleExtent([0.3, 5]).on(\"zoom\", function() {\n", "\t\tinner.attr(\"transform\", d3.event.transform);\n", "\t\t});\n", "\t\tsvg.call(zoom);\n", "\n", "\t\t// Create the renderer\n", "\t\tvar render = new dagreD3.render();\n", "\n", "\t\t// Run the renderer. This is what draws the final graph.\n", "\t\trender(inner, g);\n", "\n", "\t\t// Center the graph\n", "\t\tvar initialScale = 0.75;\n", "\t\tsvg.call(zoom.transform, d3.zoomIdentity.translate(\n", "\t\t (svg.attr(\"width\") - g.graph().width * initialScale) / 2, 20).scale(initialScale));\n", "\n", "\t\tsvg.attr('height', g.graph().height * initialScale + 50);\n", "\t\t})();\n", "\n", "\t\t</script>\n", "\t\t" ] }, "metadata": {}, "execution_count": 25 } ] }, { "cell_type": "code", "source": [ "# semiring\n", "examples[example_id]['semiring']" ], "metadata": { "id": "A20SmaPN3Ux3", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "2b363654-6912-48a1-fbdb-7a080aeaec4d" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "rayuela.base.semiring.Real" ] }, "metadata": {}, "execution_count": 48 } ] }, { "cell_type": "markdown", "source": [ "### Subquestion e) - Lehmann's Algorithm" ], "metadata": { "id": "_iBUgq4vY8Th" } }, { "cell_type": "code", "source": [ "class Pathsum:\n", " def __init__(self, fsa):\n", "\n", " # basic FSA stuff\n", " self.fsa = fsa\n", " self.R = fsa.R\n", " self.N = self.fsa.num_states\n", "\n", " # state dictionary\n", " self.I = {}\n", " for n, q in enumerate(self.fsa.Q):\n", " self.I[q] = n\n", "\n", " # lift into the semiring\n", " self.W, self.W_dict, self.alpha, self.beta = self.lift()\n", "\n", " \n", " def lift(self):\n", " \"\"\" creates the weight matrix, initial weight vector,\n", " final weight vector from the automaton \"\"\"\n", " W = self.R.zeros((self.N, self.N))\n", " W_dict = {a: {} for a in self.fsa.Sigma}\n", " alpha = self.R.zeros((self.N,))\n", " beta = self.R.zeros((self.N,))\n", " for a in self.fsa.Sigma:\n", " for b in self.fsa.Delta:\n", " W_dict[a][b] = self.R.zeros((self.N, self.N))\n", " for p in self.fsa.Q:\n", " alpha[self.I[p]] += self.fsa.λ[p]\n", " beta[self.I[p]] += self.fsa.ρ[p]\n", " for (a, b), q, w in self.fsa.arcs(p):\n", " W[self.I[p], self.I[q]] += w\n", " W_dict[a][b][self.I[p], self.I[q]] = w\n", " return W, W_dict, alpha, beta\n", " \n", " def lehmann(self):\n", " \"\"\"\n", " Lehmann's (1977) algorithm.\n", " \"\"\"\n", " # TODO: implement\n", " \n", " # Initialize R:\n", " R = self.W\n", "\n", " # Main loop:\n", " for j in range(self.N):\n", " for i in range(self.N):\n", " for k in range(self.N):\n", " R[i,k] = R[i,k] + R[i,j]*R[j,j].star()*R[j,k]\n", "\n", " # Add I to R:\n", " for i in range(self.N):\n", " R[i,i] = R[i,i] + self.R.one\n", "\n", " return R \n", "\n", " # raise NotImplementedError\n", "\n", " def _iterate(self, K):\n", " P = self.R.diag(self.N)\n", " for n in range(K):\n", " P += self.W @ P\n", " return P\n", "\n", " def _fixpoint(self, K=200):\n", " if self.fsa.R.idempotent:\n", " return self._iterate(self.fsa.num_states)\n", "\n", " diag = self.R.zeros((self.fsa.num_states, self.fsa.num_states))\n", " for n in range(self.fsa.num_states):\n", " diag[n, n] = self.fsa.R.one\n", " P_old = diag\n", "\n", " for _ in range(K):\n", " P_new = diag + self.W @ P_old\n", " P_old = P_new\n", "\n", " return P_old\n", "\n", " def fixpoint(self):\n", "\n", " P = self._fixpoint()\n", " W = {}\n", "\n", " for p in self.fsa.Q:\n", " for q in self.fsa.Q:\n", " if p in self.I and q in self.I:\n", " W[p, q] = P[self.I[p], self.I[q]]\n", " elif p == q:\n", " W[p, q] = self.R.one\n", " else:\n", " W[p, q] = self.R.zero\n", "\n", " return frozendict(W)" ], "metadata": { "id": "JdoPOG8ug-z1" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "pathsum = Pathsum(examples[3]['fst1']['fst'])\n", "print(pathsum.fixpoint())\n", "print(pathsum.lehmann())" ], "metadata": { "id": "cVSgt6AyIKvL", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "a013bbb2-e2cb-454a-9da0-d8a6d24b1970" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "frozendict.frozendict({(0, 0): 1.204687055617909, (0, 1): 0.049703748026656, (0, 2): 0.238528037012346, (1, 0): 0.423848011191222, (1, 1): 1.064607810824038, (1, 2): 0.083921906215862, (2, 0): 0.297575363071423, (2, 1): 0.220654517754702, (2, 2): 1.058919921888142})\n", "[[1.210030479232752 0.052036796373853 0.249169852930657]\n", " [0.442313809320239 1.071795077141898 0.118150643517558]\n", " [0.315208576189901 0.226634327641494 1.085202126621377]]\n" ] } ] }, { "cell_type": "markdown", "source": [ "### Subquestion f) - Normalizer" ], "metadata": { "id": "j3yMKALJZE23" } }, { "cell_type": "markdown", "source": [ "We provide some test cases for you to inspect." ], "metadata": { "id": "HWYq69zqZBym" } }, { "cell_type": "code", "source": [ "examples[0]['fst1']['Z'], examples[0]['fst2']['Z'], examples[0]['composition']['Z']" ], "metadata": { "id": "2CfkrNj9ZCXj", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "b414a8e9-f937-497a-c245-5327f49d81af" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "(0.00138425, 0.000997195294118, 7.07192371e-07)" ] }, "metadata": {}, "execution_count": 51 } ] }, { "cell_type": "code", "source": [ "def normalizer(fst):\n", " \"\"\" Takes as input a finite-state transducer and\n", " returns its normalizer\n", " \"\"\"\n", " \n", " pathsum = Pathsum(fst)\n", " # TODO: implement normalizer\n", "\n", " Z = fst.R.zero\n", " R = pathsum.lehmann()\n", "\n", " for i, qi in enumerate(fst.Q):\n", " for k, qk in enumerate(fst.Q):\n", " Z = Z + fst.λ[qi]*R[i,k]*fst.ρ[qk]\n", "\n", " return Z\n", " # raise NotImplementedError" ], "metadata": { "id": "pEwB-REPhvQ_" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "print((normalizer(examples[0]['fst1']['fst']),\\\n", " normalizer(examples[0]['fst2']['fst']),\\\n", " normalizer(examples[0]['composition']['fst'])))" ], "metadata": { "id": "YJZx6br9sCag", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ebf6356e-793d-4c7d-c02b-c43ed1b35154" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "(0.00138425, 0.000997195294118, 7.14910552e-07)\n" ] } ] }, { "cell_type": "markdown", "source": [ "### Subquestion g) - Log-likelihood" ], "metadata": { "id": "Cn7vgvpSZPwQ" } }, { "cell_type": "code", "source": [ "def log_likelihood(source_alphabet, target_alphabet, source_str, target_str):\n", " \"\"\" Takes as input the source and target alphabets (sets of characters)\n", " and a pair of source and target strings and returns the log-likelihood\n", " \"\"\"\n", "\n", " # TODO: implement log-likelihood\n", "\n", " # Representing strings with WFSTs and edit distance WFST:\n", " source_fst = string_fst(source_str)\n", " target_fst = string_fst(target_str)\n", " edit_fst = edit_distance_fst(source_alphabet, target_alphabet)\n", "\n", " print('norm_source=',normalizer(source_fst))\n", " print('norm_target=',normalizer(target_fst))\n", " print('norm_edit=',normalizer(edit_fst))\n", "\n", " # Composing the WFSTs:\n", " TxTedit = compose(source_fst, edit_fst)\n", " TxTeditTy = compose(TxTedit, target_fst)\n", "\n", " # Computing the log likelihood as logp(y|x) = score(y,x) - log(Z)\n", " score = np.log(normalizer(TxTeditTy).score)\n", " logZ = np.log(normalizer(TxTedit).score)\n", "\n", " print('score=',score)\n", " print('logZ=', logZ)\n", " \n", " return score-logZ\n", " \n", " # raise NotImplementedError" ], "metadata": { "id": "MLZJLsx3iYUq" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "### Subquestion h) - Decoding" ], "metadata": { "id": "4ookC1XyZVCT" } }, { "cell_type": "code", "source": [ "class Arctic(Semiring):\n", " def __init__(self, score):\n", " self.score = score\n", "\n", " def star(self):\n", " return self.one\n", "\n", " def __float__(self):\n", " return float(self.score)\n", "\n", " def __int__(self):\n", " return int(self.score)\n", "\n", " def __add__(self, other):\n", " return Arctic(max(self.score, other.score))\n", "\n", " def __mul__(self, other):\n", " if other is self.one:\n", " return self\n", " if self is self.one:\n", " return other\n", " if other is self.zero:\n", " return self.zero\n", " if self is self.zero:\n", " return self.zero\n", " return Arctic(self.score + other.score)\n", "\n", " def __invert__(self):\n", " return Arctic(-self.score)\n", "\n", " def __truediv__(self, other):\n", " return Arctic(self.score - other.score)\n", "\n", " def __lt__(self, other):\n", " return self.score < other.score\n", "\n", " def __repr__(self):\n", " return f\"Arctic({self.score})\"\n", "\n", " def __str__(self):\n", " return str(self.score)\n", "\n", "\n", "Arctic.zero = Arctic(-float(\"inf\"))\n", "Arctic.one = Arctic(0.0)\n", "Arctic.idempotent = True\n", "Arctic.superior = True\n", "Arctic.cancellative = True" ], "metadata": { "id": "mBq76GyHgfq0" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "def to_semiring(fst, semiring):\n", " \"\"\" Lifts an WFST into a different semiring\n", " \"\"\"\n", " oone, one = fst.R.one, semiring.one\n", " nfst = FST(semiring)\n", "\n", " # initial weights\n", " for q, w in fst.I:\n", " if w == oone:\n", " nfst.set_I(q, one)\n", " else:\n", " nfst.set_I(q, semiring(w.score))\n", "\n", " # final weights\n", " for q, w in fst.F:\n", " if w == oone:\n", " nfst.set_F(q, one)\n", " else:\n", " nfst.set_F(q, semiring(w.score))\n", "\n", " # arcs\n", " for p in fst.Q:\n", " for (a, b), q, w in fst.arcs(p):\n", " if w == oone:\n", " nfst.add_arc(p, a, b, q, one)\n", " else:\n", " nfst.add_arc(p, a, b, q, semiring(w.score))\n", "\n", " return nfst" ], "metadata": { "id": "Q6UXHrpMZcrV" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "def decode(in_str, edit_distance_fst):\n", " \"\"\" Gets as input a source string and an\n", " edit-distance transducer and returns the weight of the most\n", " probable target string\n", " \"\"\"\n", " # TODO: implement\n", " \n", " # Compose transducers\n", " str_fst = string_fst(in_str)\n", " comp_fst = compose(str_fst, edit_distance_fst)\n", " \n", " # Lift to arctic semiring\n", " comp_nfst = to_semiring(comp_fst, Arctic)\n", "\n", " # Run Lehmann -> Least probable string -> Arctic semiring\n", " output = normalizer(comp_nfst)\n", " \n", " return output\n", " # raise NotImplementedError" ], "metadata": { "id": "YCImTl323bbd" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "fst = edit_distance_fst({'a', 'b', 'c'}, {'d', 'e'}, semiring=Log)\n", "decode('aabcc', fst)" ], "metadata": { "id": "06Be-8N-orTv", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "39049389-645a-4b59-d6f3-af5c116536bc" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "Arctic(3.5)" ] }, "metadata": {}, "execution_count": 58 } ] } ] }
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"source": [
"# Assignment 3 - Transliteration"
],
"metadata": {
"id": "XSIPwHJdYR6E"
}
},
{
"cell_type": "markdown",
"source": [
"### Setup [do not change]"
],
"metadata": {
"id": "pcy6UafEX5hB"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kN-iTMK8ScoR",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "2604eb69-0172-4a54-aa42-347d0b8ba9c0"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Cloning into 'eth-nlp-f22-hw3'...\n",
"remote: Enumerating objects: 29, done.\u001b[K\n",
"remote: Counting objects: 100% (29/29), done.\u001b[K\n",
"remote: Compressing objects: 100% (25/25), done.\u001b[K\n",
"remote: Total 29 (delta 6), reused 16 (delta 2), pack-reused 0\u001b[K\n",
"Unpacking objects: 100% (29/29), 9.90 KiB | 921.00 KiB/s, done.\n",
"Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
"Obtaining file:///content/eth-nlp-f22-hw3\n",
" Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
"Requirement already satisfied: numpy in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (1.21.6)\n",
"Collecting frozendict\n",
" Downloading frozendict-2.3.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (110 kB)\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m111.0/111.0 KB\u001b[0m \u001b[31m2.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25hRequirement already satisfied: frozenlist in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (1.3.3)\n",
"Collecting pyconll\n",
" Downloading pyconll-3.1.0-py3-none-any.whl (26 kB)\n",
"Requirement already satisfied: nltk in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (3.7)\n",
"Requirement already satisfied: pytest in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (3.6.4)\n",
"Requirement already satisfied: dill in /usr/local/lib/python3.8/dist-packages (from rayuela==0.1) (0.3.6)\n",
"Requirement already satisfied: click in /usr/local/lib/python3.8/dist-packages (from nltk->rayuela==0.1) (7.1.2)\n",
"Requirement already satisfied: tqdm in /usr/local/lib/python3.8/dist-packages (from nltk->rayuela==0.1) (4.64.1)\n",
"Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.8/dist-packages (from nltk->rayuela==0.1) (2022.6.2)\n",
"Requirement already satisfied: joblib in /usr/local/lib/python3.8/dist-packages (from nltk->rayuela==0.1) (1.2.0)\n",
"Requirement already satisfied: setuptools in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (57.4.0)\n",
"Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (1.15.0)\n",
"Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (1.11.0)\n",
"Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (1.4.1)\n",
"Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (9.0.0)\n",
"Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (22.2.0)\n",
"Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.8/dist-packages (from pytest->rayuela==0.1) (0.7.1)\n",
"Installing collected packages: pyconll, frozendict, rayuela\n",
" Running setup.py develop for rayuela\n",
"Successfully installed frozendict-2.3.4 pyconll-3.1.0 rayuela-0.1\n"
]
}
],
"source": [
"!git clone https://github.com/butoialexandra/eth-nlp-f22-hw3.git\n",
"\n",
"import os\n",
"os.chdir('eth-nlp-f22-hw3')\n",
"\n",
"!pip install -e ."
]
},
{
"cell_type": "code",
"source": [
"!wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1wlHbFChZFcBgEU8knAeaUIqE0W4EaJEC' -O 'test_cases.pkl'"
],
"metadata": {

Xet Storage Details

Size:
85 kB
·
Xet hash:
552d5a47f4777cdfd3064aa93ace8a3dd2252d50f023ef10670e7ff3f12185c4

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.