Open interactive version of the notebook

Mapping public opinion with embeddings

  • Real comments from York's 2024 consultation on its draft taxi licensing policy
  • 573 consultation respondents
  • 331 respondents who supplied at least one comment
  • 1,291 comments covering ten policy questions
  • Public data published by City of York Council under the UK Open Government Licence
  • Respondent identifiers and demographic attributes are excluded
  • Public comments may contain offensive or discriminatory views
comments = pl.DataFrame(
    json.loads(gzip.decompress(base64.b64decode(DATA_PAYLOAD)))
)
comments

Data

def split_into_opinions(frame: pl.DataFrame) -> pl.DataFrame:
    rows = []
    for _record in frame.iter_rows(named=True):
        for _text in re.split(r"[.!?\n;]+", _record["text"]):
            _text = _text.strip()
            if len(_text) > 10:
                rows.append(
                    {
                        "answer_id": _record["answer_id"],
                        "topic": _record["topic"],
                        "text": _text,
                        "length": len(_text),
                    }
                )
    return pl.DataFrame(rows).with_row_index("id")
opinions = split_into_opinions(comments)
mo.md(
    f"""
    ## Opinions

    - `{len(comments):,}` comments
    - `{len(opinions):,}` atomic opinions after splitting on sentence boundaries
    - `{opinions['answer_id'].n_unique():,}` respondents represented
    - A respondent can contribute to more than one opinion region
    """
)

Opinions

  • 1,291 comments
  • 2,077 atomic opinions after splitting on sentence boundaries
  • 326 respondents represented
  • A respondent can contribute to more than one opinion region
class OpenRouterClient:
    def __init__(
        self,
        api_key: str,
        embedding_model: str,
        generation_model: str,
        workers: int = 5,
    ):
        self.api_key = api_key
        self.embedding_model = embedding_model
        self.generation_model = generation_model
        self.workers = workers
        self.base_url = "https://openrouter.ai/api/v1"
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "X-OpenRouter-Title": "Mapping public opinion with embeddings",
        }
        self._embedding_cache = {}
        self._generation_cache = {}

    def _post(self, endpoint: str, payload: dict) -> dict:
        for _attempt in range(5):
            try:
                _response = requests.post(
                    f"{self.base_url}/{endpoint}",
                    headers=self.headers,
                    json=payload,
                    timeout=120,
                )
                _response.raise_for_status()
                return _response.json()
            except (requests.RequestException, ValueError):
                if _attempt == 4:
                    raise
                time.sleep(2**_attempt)
        raise AssertionError("unreachable")

    def embed(self, texts, title="Embedding opinions") -> np.ndarray:
        _texts = list(texts)
        _batches = [tuple(_texts[i : i + 100]) for i in range(0, len(_texts), 100)]
        _results = []
        for _batch in mo.status.progress_bar(_batches, title=title):
            if _batch not in self._embedding_cache:
                _response = self._post(
                    "embeddings",
                    {
                        "model": self.embedding_model,
                        "input": list(_batch),
                        "encoding_format": "float",
                    },
                )
                self._embedding_cache[_batch] = np.asarray(
                    [_item["embedding"] for _item in _response["data"]],
                    dtype=np.float64,
                )
            _results.append(self._embedding_cache[_batch])
        return np.vstack(_results)

    def chat_json(self, prompt: str) -> dict:
        if prompt not in self._generation_cache:
            _response = self._post(
                "chat/completions",
                {
                    "model": self.generation_model,
                    "messages": [
                        {
                            "role": "system",
                            "content": "Return only valid JSON matching the requested format.",
                        },
                        {"role": "user", "content": prompt},
                    ],
                    "temperature": 0.3,
                    "response_format": {"type": "json_object"},
                },
            )
            _content = _response["choices"][0]["message"]["content"]
            self._generation_cache[prompt] = json.loads(_content)
        return self._generation_cache[prompt]

    def chat_json_many(self, prompts, title: str):
        _prompts = list(prompts)
        _results = []
        for _start in mo.status.progress_bar(
            range(0, len(_prompts), self.workers),
            total=len(_prompts),
            title=title,
        ):
            _batch = _prompts[_start : _start + self.workers]
            with ThreadPoolExecutor(max_workers=self.workers) as _executor:
                _results.extend(_executor.map(self.chat_json, _batch))
        return _results
api_key = os.environ.get("OPENROUTER_API_KEY", "")
embedding_model = "qwen/qwen3-embedding-8b"
generation_model = "mistralai/mistral-small-3.2-24b-instruct"
llm = OpenRouterClient(api_key, embedding_model, generation_model)
start = mo.ui.run_button(label="Run the analysis")
mo.vstack(
    [
        mo.md(
            f"""
            ## Models

            - Embeddings: `{embedding_model}`
            - Generation: `{generation_model}`
            - Authentication: `OPENROUTER_API_KEY`
            - API key available: `{bool(api_key)}`
            """
        ),
        start,
    ]
)

Models

  • Embeddings: qwen/qwen3-embedding-8b
  • Generation: mistralai/mistral-small-3.2-24b-instruct
  • Authentication: OPENROUTER_API_KEY
  • API key available: True
mo.stop(not start.value, mo.md("- Select **Run the analysis** to call OpenRouter."))
assert api_key, "Set OPENROUTER_API_KEY before running the analysis"
short_opinions = opinions.filter(pl.col("length") < 100)
assert len(short_opinions) >= 200
calibration_sample = short_opinions.sample(200, seed=42)
_prompts = [
    f"""
    - Survey: City of York consultation on its draft taxi licensing policy
    - Policy topic: {_row['topic']}
    - Original opinion: {_row['text']}

    Write two opinions that clearly express the same idea as the original.

    - Change style and register.
    - Vary their length.
    - Preserve meaning.

    Return JSON: {{"opinions": ["first", "second"]}}
    """
    for _row in calibration_sample.iter_rows(named=True)
]
_outputs = llm.chat_json_many(_prompts, "Generating paraphrases")
_rows = []
for _source, _output in zip(calibration_sample.iter_rows(named=True), _outputs):
    for _paraphrase in _output["opinions"]:
        _rows.append(
            {
                "topic": _source["topic"],
                "original": _source["text"],
                "paraphrase": _paraphrase,
            }
        )
paraphrases = pl.DataFrame(_rows)
_template = (
    "Survey: City of York consultation on its draft taxi licensing policy\n"
    "Policy topic: {topic}\nOpinion: {text}"
)
_original_inputs = [
    _template.format(topic=_row["topic"], text=_row["original"])
    for _row in paraphrases.iter_rows(named=True)
]
_paraphrase_inputs = [
    _template.format(topic=_row["topic"], text=_row["paraphrase"])
    for _row in paraphrases.iter_rows(named=True)
]
original_embeddings = llm.embed(_original_inputs, "Embedding original opinions")
paraphrase_embeddings = llm.embed(_paraphrase_inputs, "Embedding paraphrases")
_pca = decomposition.PCA(n_components=20, random_state=42)
_pca.fit(original_embeddings - paraphrase_embeddings)
rewording_axes = _pca.components_
rewording_variance = float(_pca.explained_variance_ratio_.sum())
_prompts = [
    f"""
    - Survey: City of York consultation on its draft taxi licensing policy
    - Policy topic: {_row['topic']}
    - Survey response: {_row['text']}

    Write two short opinions:

    - One clearly supporting the response's position.
    - One clearly opposing the response's position.
    - Use at most 20 words for each.
    - Preserve the original register.

    Return JSON: {{"supporting": "...", "opposing": "..."}}
    """
    for _row in calibration_sample.iter_rows(named=True)
]
_outputs = llm.chat_json_many(_prompts, "Generating opposing opinions")
oppositions = pl.DataFrame(
    [
        {
            "topic": _source["topic"],
            "supporting": _output["supporting"],
            "opposing": _output["opposing"],
        }
        for _source, _output in zip(
            calibration_sample.iter_rows(named=True), _outputs
        )
    ]
)
_template = (
    "Survey: City of York consultation on its draft taxi licensing policy\n"
    "Policy topic: {topic}\nOpinion: {text}"
)
_supporting = llm.embed(
    [
        _template.format(topic=_row["topic"], text=_row["supporting"])
        for _row in oppositions.iter_rows(named=True)
    ],
    "Embedding supporting opinions",
)
_opposing = llm.embed(
    [
        _template.format(topic=_row["topic"], text=_row["opposing"])
        for _row in oppositions.iter_rows(named=True)
    ],
    "Embedding opposing opinions",
)
_differences = _supporting - _opposing
_differences -= (_differences @ rewording_axes.T) @ rewording_axes
_pca = decomposition.PCA(n_components=15, random_state=42)
_pca.fit(_differences)
opinion_axes = _pca.components_
opinion_variance = float(_pca.explained_variance_ratio_.sum())
embedding_template = (
    "Survey: City of York consultation on its draft taxi licensing policy\n"
    "Policy topic: {topic}\nOpinion: {text}"
)
_inputs = [
    embedding_template.format(topic=_row["topic"], text=_row["text"])
    for _row in opinions.iter_rows(named=True)
]
_raw = llm.embed(_inputs, "Embedding all opinions")
_empty = llm.embed(
    [
        embedding_template.format(topic="General", text=_text)
        for _text in ["", ".", "-", "N/A", "\n"]
    ],
    "Embedding empty responses",
).mean(axis=0)
_reworded = _raw - _empty
_reworded -= (_reworded @ rewording_axes.T) @ rewording_axes
_clean = _reworded + (_reworded @ opinion_axes.T) @ opinion_axes
_median_norm = np.median(np.linalg.norm(_clean, axis=1))
embeddings = _clean / _median_norm

Calibration

  • Paraphrase pairs: 400
  • Rewording directions removed: 20
  • Rewording variance represented: 52.8%
  • Opposition pairs: 200
  • Opinion directions amplified: 15
  • Opposition variance represented: 43.0%
def dendrogram_to_tree(children) -> pl.DataFrame:
    _n = len(children) + 1
    _parent = list(np.argsort(children.ravel()) // 2 + _n) + [None]
    return pl.DataFrame(
        {"id": range(2 * _n - 1), "parent": _parent, "root": 2 * _n - 2}
    )

def compute_hierarchy(tree: pl.DataFrame) -> pl.DataFrame:
    _children = tree.select("parent", "id").rows_by_key("parent")
    _root = tree.filter(pl.col("parent").is_null())["id"].item()
    _ancestors = {_node: [] for _node in tree["id"]}
    _ancestors[_root] = [_root]
    _stack = [_root]
    while _stack:
        _node = _stack.pop()
        for (_child,) in _children.get(_node, []):
            _ancestors[_child] = [_child, *_ancestors[_node]]
            _stack.append(_child)
    return (
        tree.select("id")
        .with_columns(
            pl.col("id")
            .replace_strict(_ancestors, return_dtype=pl.List(pl.Int64))
            .alias("ancestor")
        )
        .explode("ancestor")
    )

def cut_tree(tree: pl.DataFrame, roots) -> tuple[pl.DataFrame, pl.DataFrame]:
    _children = tree.select("parent", "id").rows_by_key("parent")
    _root = tree.filter(pl.col("parent").is_null())["id"].item()
    _groups = {_node: _root for _node in tree["id"]}
    _parents = dict(tree.select("id", "parent").iter_rows())
    _nodes = []
    for _new_root in roots:
        _stack = [_new_root]
        while _stack:
            _node = _stack.pop()
            _nodes.append(_node)
            _groups[_node] = _new_root
            _stack.extend(_child for (_child,) in _children.get(_node, []))
    _subtrees = pl.DataFrame({"id": _nodes}).select(
        "id",
        root=pl.col("id").replace_strict(_groups),
        parent=pl.col("id").replace_strict(_parents, default=None),
    )
    _trunk = tree.filter(
        pl.col("id")
        .replace_strict(_parents, default=_root)
        .replace_strict(_groups, default=_root)
        .eq(_root)
    )
    return _subtrees, _trunk

def compute_depth(tree: pl.DataFrame) -> pl.DataFrame:
    _root = tree.filter(pl.col("parent").is_null())["id"].item()
    _children = tree.select("parent", "id").rows_by_key("parent")
    _depth = {_root: 0}
    _stack = [_root]
    while _stack:
        _node = _stack.pop()
        for (_child,) in _children.get(_node, []):
            _depth[_child] = _depth[_node] + 1
            _stack.append(_child)
    return tree.select("id").with_columns(
        pl.col("id").replace_strict(_depth).alias("depth")
    )

def compute_layout(tree: pl.DataFrame) -> pl.DataFrame:
    _root = tree.filter(pl.col("parent").is_null())["id"].item()
    _children = tree.select("parent", "id").rows_by_key("parent")
    _x = {_root: 0}
    _y = {}
    _stack = [_root]
    _previous_leaf = False
    _vertical = 0.0
    while _stack:
        _node = _stack.pop()
        if _previous_leaf:
            _vertical += 5 + 10 * (0.8 ** _x[_node])
        _y[_node] = _vertical
        for (_child,) in _children.get(_node, []):
            _x[_child] = _x[_node] + 1
            _stack.append(_child)
        _previous_leaf = not _children.get(_node, [])
    return tree.select("id").with_columns(
        x=pl.col("id").replace_strict(_x),
        y=pl.col("id").replace_strict(_y),
    )

def nested_tree(tree: pl.DataFrame, info: pl.DataFrame) -> dict:
    _root = tree.filter(pl.col("parent").is_null())["id"].item()
    _children = tree.select("parent", "id").rows_by_key("parent")
    _records = info.rows_by_key("id", unique=True, named=True)
    _stack = [_root]
    while _stack:
        _node = _stack.pop()
        _records[_node]["children"] = []
        for (_child,) in _children.get(_node, []):
            _records[_node]["children"].append(_records[_child])
            _stack.append(_child)
    return _records[_root]
clustering = cluster.AgglomerativeClustering(
    distance_threshold=0,
    n_clusters=None,
).fit(embeddings)
tree = dendrogram_to_tree(clustering.children_)
ancestry = compute_hierarchy(tree).join(opinions.select("id"), on="id")
_answer_by_opinion = dict(opinions.select("id", "answer_id").iter_rows())
_stats = []
for (_ancestor,), _group in ancestry.group_by("ancestor"):
    _ids = _group["id"].to_numpy()
    _mean = embeddings[_ids].mean(axis=0)
    _stats.append(
        {
            "id": _ancestor,
            "cardinality": len({_answer_by_opinion[int(_id)] for _id in _ids}),
            "mean": _mean.tolist(),
            "spread": float(np.linalg.norm(embeddings[_ids] - _mean)),
        }
    )
stats = pl.DataFrame(_stats)
tree_with_stats = tree.join(stats, on="id")
_proposed = int(
    tree_with_stats.select(pl.col("spread").ge(10).sum().clip(10, 21)).item()
)
region_count = mo.ui.slider(
    10,
    21,
    value=_proposed,
    show_value=True,
    debounce=True,
    label="Opinion regions",
)
region_count
n_regions = region_count.value
threshold = tree_with_stats["spread"].sort(descending=True)[n_regions - 2]
regions = (
    tree_with_stats.join(
        tree_with_stats,
        left_on="parent",
        right_on="id",
        suffix="_parent",
    )
    .filter(pl.col("spread_parent") >= threshold, pl.col("spread") < threshold)
    .select("id", region=pl.col("id"))
)
subtrees, taxonomy = cut_tree(tree, regions["region"])
_samples = (
    ancestry.join(taxonomy, left_on="ancestor", right_on="id")
    .join(opinions, on="id")
    .group_by(id="ancestor")
    .agg(
        pl.struct("topic", "text")
        .sample(10, with_replacement=True, seed=42)
        .alias("samples")
    )
)
_prompts = []
for _row in _samples.iter_rows(named=True):
    _examples = "\n".join(
        f"- [{_sample['topic']}] {_sample['text']}"
        for _sample in _row["samples"]
    )
    _prompts.append(
        f"""
        The following opinions come from one cluster in York's taxi licensing consultation:

        {_examples}

        - Write two representative opinion statements.
        - Use no more than five words per statement.
        - Do not claim that every respondent agrees.

        Return JSON: {{"statements": ["first", "second"]}}
        """
    )
_outputs = llm.chat_json_many(_prompts, "Labelling opinion regions")
topics = pl.DataFrame(
    {
        "id": _samples["id"],
        "topic": ["\n".join(_output["statements"]) for _output in _outputs],
    }
)
def coordinates_2d(matrix: np.ndarray) -> pl.DataFrame:
    _model = manifold.TSNE(
        n_components=2,
        early_exaggeration=20,
        init="pca",
        random_state=42,
    )
    _coords = _model.fit_transform(matrix)
    return pl.DataFrame(
        {"x": _coords[:, 0], "y": _coords[:, 1], "id": range(len(matrix))}
    )

def matrix_frame(matrix: np.ndarray) -> pl.DataFrame:
    _i, _j = np.indices(matrix.shape)
    return pl.DataFrame(
        {"i": _i.ravel(), "j": _j.ravel(), "value": matrix.ravel()}
    )
alt.theme.enable("carbong10")
_layout = compute_layout(taxonomy)
_taxonomy_topics = (
    taxonomy.join(topics, on="id")
    .join(tree.select("id", "parent"), on="id")
    .join(regions, on="id", how="left")
    .join(stats, on="id")
    .select(
        "topic",
        "id",
        "region",
        "cardinality",
        topic_text=pl.format("{}: {}", pl.col("id"), pl.col("topic").fill_null("")),
        parent=pl.col("parent"),
        is_region=pl.col("region").is_not_null(),
    )
)
_selection = alt.selection_point(fields=["region"])
_opinion_data = (
    coordinates_2d(embeddings)
    .join(opinions, on="id")
    .join(ancestry, on="id")
    .rename({"ancestor": "region"})
    .join(_taxonomy_topics, on="region")
    .join(compute_depth(tree), on="id")
    .with_columns(size=1 / pl.col("depth"))
)
_cloud = (
    alt.Chart(_opinion_data)
    .mark_point(strokeWidth=1)
    .encode(
        alt.X("x", axis=None),
        alt.Y("y", axis=None),
        alt.Tooltip(["text", "topic", "topic_text"]),
        alt.Size("size", legend=None),
        alt.Shape("region:N"),
        alt.Color("region:N"),
        opacity=alt.condition(_selection, alt.value(1), alt.value(0.25)),
    )
    .add_params(_selection)
)
_tree_data = _taxonomy_topics.join(_layout, on="id")
_paths = (
    taxonomy.filter(pl.col("parent").is_not_null())
    .with_columns(_endpoint=pl.lit([0, 1]))
    .explode("_endpoint")
    .with_columns(
        _join_id=pl.when(pl.col("_endpoint") == 0).then("id").otherwise("parent")
    )
    .join(_layout, left_on="_join_id", right_on="id")
)
_x_max = float(_layout["x"].max())
_y_max = float(_layout["y"].max())
_categories = alt.layer(
    alt.Chart(_paths)
    .mark_line(interpolate="step-before", color="black")
    .encode(alt.X("x", axis=None), alt.Y("y", axis=None), alt.Detail("id")),
    alt.Chart(_tree_data)
    .mark_point(size=200, strokeWidth=3)
    .encode(
        alt.X("x:Q", axis=None, scale=alt.Scale(domain=[-1, _x_max * 2])),
        alt.Y("y:Q", axis=None, scale=alt.Scale(reverse=True, domain=[-0.5, _y_max])),
        alt.Tooltip(["topic_text:N", "cardinality:Q"]),
        opacity=alt.condition(_selection, alt.value(1), alt.value(0.25)),
        color="region:N",
        shape=alt.condition(alt.datum.is_region, "region:N", alt.value("square")),
    )
    .add_params(_selection),
    alt.Chart(_tree_data)
    .mark_text(dx=15, align="left", lineBreak="\n", baseline="middle")
    .encode(
        alt.X("x"),
        alt.Y("y"),
        text=alt.condition(alt.datum.is_region, "topic_text", alt.value("")),
        opacity=alt.condition(_selection, alt.value(1), alt.value(0.25)),
    ),
)
_topic_data = (
    regions.join(_layout, on="id")
    .join(topics, on="id")
    .join(stats, on="id")
    .sort("y")
    .with_row_index("idx")
)
_means = np.vstack(_topic_data["mean"].to_numpy())
_means /= np.linalg.norm(_means, axis=1, keepdims=True)
_heatmap_data = (
    matrix_frame(1 - _means @ _means.T)
    .join(_topic_data.select("idx", "topic", "region"), left_on="i", right_on="idx")
    .join(
        _topic_data.select("idx", "topic", "region"),
        left_on="j",
        right_on="idx",
        suffix="_other",
    )
    .with_columns(
        horizontal=pl.format("{}: {}", pl.col("region"), pl.col("topic")),
        vertical=pl.format("{}: {}", pl.col("region_other"), pl.col("topic_other")),
    )
)
_heatmap = (
    alt.Chart(_heatmap_data)
    .mark_rect()
    .encode(
        alt.X("horizontal:N", sort=alt.EncodingSortField("i"), axis=alt.Axis(labelAngle=-45)),
        alt.Y("vertical:N", sort=alt.EncodingSortField("j")),
        alt.Color("value:Q"),
        alt.Tooltip(["topic", "topic_other", "value"]),
    )
)
visualization = alt.vconcat(
    _cloud.properties(
        width=800,
        height=600,
        title="Opinion space — select a point to highlight its region",
    ),
    _categories.properties(
        width=800,
        height=int(40 * n_regions),
        title="Opinion taxonomy",
    ),
    _heatmap.properties(
        width=500,
        height=500,
        title="Distance between opinion regions",
    ),
).resolve_legend(color="shared", fill="shared")
visualization
_samples = (
    ancestry.join(
        taxonomy.select(pl.col("id").alias("ancestor")),
        on="ancestor",
    )
    .join(opinions, on="id")
    .group_by(region="ancestor")
    .agg(pl.col("text").sample(5, with_replacement=True, seed=42))
)
_info = (
    topics.join(taxonomy, on="id")
    .join(stats, on="id")
    .join(_samples, left_on="id", right_on="region", how="left")
    .select(
        "id",
        typical_opinion=pl.when(pl.col("spread") < 1.5 * threshold).then("topic"),
        respondents="cardinality",
        samples="text",
    )
)
report_data = nested_tree(taxonomy, _info)
_prompt = f"""
Create a concise report from this automated analysis of York's taxi licensing consultation.

- Return JSON with one field named "bullets" containing a list of strings.
- Use bullets only, not paragraphs.
- Cover major themes, consensus, and disagreement.
- Mention approximate respondent counts.
- Include short examples grounded in the supplied samples.
- Treat cluster labels and counts as approximate.

Data:
{json.dumps(report_data, ensure_ascii=False)}
"""
report_bullets = llm.chat_json(_prompt)["bullets"]
mo.md("## Findings\n\n" + "\n".join(f"- {_item}" for _item in report_bullets))

Findings

  • 326 respondents in total.
  • Major themes: wheelchair-accessible vehicles (WAVs), vehicle age and standards, taxi identification, and out-of-town taxis.
  • Approx. 118 respondents believe there are enough WAVs in York, while others mention difficulties in accessing them.
  • Approx. 177 respondents argue for higher investment recovery for WAVs and electrifying the taxi fleet.
  • Approx. 137 respondents suggest extending licenses for existing vehicles and enforcing stricter rules for non-York taxis.
  • Approx. 116 respondents support drivers in replacing vehicles and linking vehicle age to mileage.
  • Approx. 131 respondents believe factory tinted windows should be allowed, while others argue for clear identification of taxis.
  • Approx. 150 respondents think black taxis are unnecessary and lights suffice for identification.
  • Approx. 95 respondents emphasize the importance of clearly identifying private hire vehicles.
  • Approx. 143 respondents believe cameras improve passenger safety but may add cost for drivers.
  • Approx. 129 respondents think drivers must know the area and out-of-town taxis are concerning.
  • Approx. 92 respondents consider subcontracting unsafe and prefer York taxis to stay York-based.
  • Approx. 125 respondents advocate for enforcing York-registered taxis only and stopping taxis from other areas.
  • Disagreement exists on vehicle age limits, with some finding 36 months too long and others too lenient.
  • Consensus on the need for clear identification of taxis and addressing out-of-town taxis working in York.