nlp文章相似度

1. 基于词袋模型(Bag of Words)

方法
  • 将文本表示为词频向量(如TF-IDF),通过余弦相似度计算相似性。

  • 优点:简单快速,适合短文本或主题明显的场景。

  • 缺点:忽略词序和语义信息。

实现步骤
python 复制代码
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

texts = ["文章1内容", "文章2内容", "文章3内容"]
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(texts)
similarity = cosine_similarity(tfidf_matrix[0], tfidf_matrix[1])
print(similarity[0][0])  # 输出两篇文章的相似度
复制代码

2. 基于词向量(Word Embedding)

方法
  • 使用预训练的词向量(如Word2Vec、GloVe)表示文本,通过词向量平均或加权平均(如TF-IDF权重)生成文本向量,再计算相似度。

  • 优点:捕捉词汇语义。

  • 缺点:无法处理词序和复杂语义。

实现步骤
python 复制代码
import numpy as np
from gensim.models import KeyedVectors

# 加载预训练词向量(示例)
model = KeyedVectors.load_word2vec_format("word2vec.bin", binary=True)

def text_to_vector(text):
    words = text.split()
    vectors = [model[word] for word in words if word in model]
    return np.mean(vectors, axis=0) if vectors else np.zeros(model.vector_size)

vec1 = text_to_vector("文章1内容")
vec2 = text_to_vector("文章2内容")
similarity = np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
print(similarity)
复制代码

3. 基于句向量(Sentence Embedding)

方法
  • 使用预训练模型(如BERT、Sentence-BERT)直接生成句向量,计算余弦相似度。

  • 优点:捕捉上下文和深层语义。

  • 缺点:计算成本较高。

实现步骤(使用Sentence-BERT)
python 复制代码
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity

model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
sentences = ["文章1内容", "文章2内容"]
embeddings = model.encode(sentences)
similarity = cosine_similarity([embeddings[0]], [embeddings[1]])[0][0]
print(similarity)
复制代码

4. 基于文本匹配模型

方法
  • 使用深度学习模型(如Siamese Network、BERT)直接输出相似度分数。

  • 优点:端到端建模,精度高。

  • 缺点:需要训练数据,计算资源要求高。

python 复制代码
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased")

text1 = "文章1内容"
text2 = "文章2内容"
inputs = tokenizer(text1, text2, return_tensors="pt", padding=True, truncation=True)
outputs = model(**inputs)
similarity = torch.sigmoid(outputs.logits).item()  # 假设模型输出为相似度概率
print(similarity)
复制代码

5. 其他方法

  • Jaccard相似度:基于词集合的重合度。

  • BM25:基于词频和文档长度的改进相似度算法(常用于搜索引擎)。

  • 主题模型(LDA):通过主题分布计算相似度。


选择建议

  • 简单场景:TF-IDF + 余弦相似度。

  • 语义相似度:Sentence-BERT或BERT。

  • 大规模应用:BM25或Faiss加速向量检索。


注意事项

  1. 预处理文本(分词、去停用词、标准化)。

  2. 长文本需分段或截断处理。

  3. 多语言场景需选择对应预训练模型。

相关推荐
拾光向日葵4 小时前
2026考研:南京林业大学接受理学调剂的专业有哪些
大数据·人工智能·物联网
云边云科技_云网融合4 小时前
详解Token经济:智能时代的价值标尺与产业全链路重构
人工智能·aigc·token
LDG_AGI4 小时前
【搜索引擎】Elasticsearch(二):基于function_score的搜索排序
数据库·人工智能·深度学习·elasticsearch·机器学习·搜索引擎·推荐算法
AI攻城狮4 小时前
Anthropic 开源了 Claude 的 Agent Skills 仓库:文档技能的底层实现全公开了
人工智能·云原生·aigc
XM_jhxx4 小时前
从“自动化”到“自主化”:工业AI正在改变什么?
大数据·人工智能
CodeCraft Studio4 小时前
高性能图表库SciChart助力机器人实现实时AI驱动的性能提升
人工智能·信息可视化·机器人·数据可视化·scichart·高性能图表库·wpf图表库
这张生成的图像能检测吗4 小时前
(论文速读)UWDET:基于物联网的资源有限水下目标探测训练增强
人工智能·深度学习·物联网·目标检测·计算机视觉·水下目标检测
Nova_AI4 小时前
009、AI安全与可信:合规、治理与新兴市场
人工智能·安全
小超同学你好4 小时前
Transformer 24. Gemma 2 架构详解:交替局部/全局注意力、GQA、双层 RMSNorm 与 Logit Soft-Capping
人工智能·深度学习·transformer
Oflycomm4 小时前
从硬件到智能:AI摄像头平台驱动安防与自动驾驶融合升级
人工智能·iot·qualcomm·qogrisys·ai摄像头