AI 如何知道猫像狗:Word Embeddings 直观指南

发布: (2025年12月22日 GMT+8 16:53)
3 min read
原文: Dev.to

Source: Dev.to

词嵌入背后的直觉

想象一下对概念进行数学运算。一个经典例子:

King - Man + Woman ≈ Queen

这展示了 静态嵌入(如 GloVe——全局词向量)的强大之处。GloVe 会扫描海量语料库,统计词语相互出现的频率,并为每个词分配一个固定的数值向量。由于这些向量捕捉了“意义”,语义相近的词会被映射到相近的位置。

多义性问题

静态模型在处理 多义词——即具有多重含义的词——时会遇到困难。

  • I need to go to the bank to deposit some money.(金融机构)
  • We sat on the bank of the river.(河岸)

在像 GloVe 这样的静态模型中,“bank”只有一个向量,它是所有上下文的平均值,因而无法区分这些不同的含义。

动态(上下文)嵌入

上下文嵌入(例如 BERT——双向编码器表示的转换器)会根据整句话为每次出现的词生成唯一的向量。当 BERT 处理上述两句包含 “bank” 的句子时,会产生不同的向量,因为周围的词(如 “river”、 “deposit”)指引了它的解释。

使用 PyTorch 的简单 BERT 示例

import torch
from transformers import BertTokenizer, BertModel

# Load tokenizer and model
tokenizer = BertTokenizer.from_pretrained('./bert_model')
model_bert = BertModel.from_pretrained('./bert_model')
model_bert.eval()  # Prevent training

def print_token_embeddings(sentence: str, label: str):
    """
    Tokenizes a sentence, runs it through BERT,
    and prints the first 5 values of each token's embedding.
    """
    inputs = tokenizer(sentence, return_tensors="pt")
    with torch.no_grad():
        outputs = model_bert(**inputs)
    embeddings = outputs.last_hidden_state[0]
    tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])

    print(f"\n--- {label} ---")
    for token, vector in zip(tokens, embeddings):
        print(f"{token}: {vector[:5].tolist()}")

讨论提示: 如果你今天要从头训练一个模型,你希望它首先学习哪些特定词汇或细分主题?请在评论中分享你的想法。

本文所有插图均使用 DALL·E 3 生成。

参考文献

  • Devlin, J. 等人 (2018). BERT: 预训练深度双向转换器用于语言理解
  • Stanford NLP Group. GloVe: 全局词向量
  • Spot Intelligence. GloVe 嵌入解释
Back to Blog

相关文章

阅读更多 »