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. 多语言场景需选择对应预训练模型。

相关推荐
冬奇Lab9 小时前
Workflow 系列(03):状态管理——持久化、幂等性与版本绑定
人工智能·工作流引擎
冬奇Lab9 小时前
每日一个开源项目(第146篇):openpilot - 开源自动驾驶辅助系统,曾在 Consumer Reports 评测中超过特斯拉 Autopilot
人工智能·开源·自动驾驶
吴佳浩10 小时前
AI 工程师知识地图:模型格式、框架、部署工具一次讲明白
人工智能·aigc·ai编程
IT_陈寒11 小时前
Java的Date类又坑了我一次,改用时间戳真香
前端·人工智能·后端
码农胖大海11 小时前
AI额度不够用的解决方案
人工智能
后端小肥肠11 小时前
小红书虚拟商品怎么做?我先用 Skill 跑通了壁纸品类
人工智能·aigc·agent
feiyu_gao11 小时前
从零搭建个人 AI 工作台:一个管理者的 3 个月实验
人工智能·aigc·团队管理
程序员cxuan12 小时前
一句话,让你用上 GPT-5.6
人工智能·后端·程序员
机器之心13 小时前
AI圈刚开始谈Loop Engineering,两位95后博士已经盯上了人类闭环数据
人工智能·openai