pytorch基于FastText实现词嵌入

server/2025/2/8 3:38:56/

FastText 是 Facebook AI Research 提出的 改进版 Word2Vec,可以: ✅ 利用 n-grams 处理未登录词
比 Word2Vec 更快、更准确
适用于中文等形态丰富的语言

完整的 PyTorch FastText 代码(基于中文语料),包含:

  • 数据预处理(分词 + n-grams)
  • 模型定义
  • 训练
  • 测试
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import jieba
from collections import Counter
import random# ========== 1. 数据预处理 ==========
corpus = ["我们 喜欢 深度 学习","自然 语言 处理 是 有趣 的","人工智能 改变 了 世界","深度 学习 是 人工智能 的 重要 组成部分"
]# 分词
tokenized_corpus = [list(jieba.cut(sentence)) for sentence in corpus]# 构建 n-grams
def generate_ngrams(words, n=3):ngrams = []for word in words:ngrams += [word[i:i + n] for i in range(len(word) - n + 1)]return ngrams# 生成 n-grams 词表
all_ngrams = set()
for sentence in tokenized_corpus:for word in sentence:all_ngrams.update(generate_ngrams(word))# 构建词汇表
vocab = set(word for sentence in tokenized_corpus for word in sentence) | all_ngrams
word2idx = {word: idx for idx, word in enumerate(vocab)}
idx2word = {idx: word for word, idx in word2idx.items()}# 构建训练数据(CBOW 方式)
window_size = 2
data = []for sentence in tokenized_corpus:indices = [word2idx[word] for word in sentence]for center_idx in range(len(indices)):context = []for offset in range(-window_size, window_size + 1):context_idx = center_idx + offsetif 0 <= context_idx < len(indices) and context_idx != center_idx:context.append(indices[context_idx])if context:data.append((context, indices[center_idx]))  # (上下文, 目标词)# ========== 2. 定义 FastText 模型 ==========
class FastText(nn.Module):def __init__(self, vocab_size, embedding_dim):super(FastText, self).__init__()self.embeddings = nn.Embedding(vocab_size, embedding_dim)self.linear = nn.Linear(embedding_dim, vocab_size)def forward(self, context):context_vec = self.embeddings(context).mean(dim=1)  # 平均上下文向量output = self.linear(context_vec)return output# 初始化模型
embedding_dim = 10
model = FastText(len(vocab), embedding_dim)# ========== 3. 训练 FastText ==========
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
num_epochs = 100for epoch in range(num_epochs):total_loss = 0random.shuffle(data)for context, target in data:context = torch.tensor([context], dtype=torch.long)target = torch.tensor([target], dtype=torch.long)optimizer.zero_grad()output = model(context)loss = criterion(output, target)loss.backward()optimizer.step()total_loss += loss.item()if (epoch + 1) % 10 == 0:print(f"Epoch [{epoch + 1}/{num_epochs}], Loss: {total_loss:.4f}")# ========== 4. 获取词向量 ==========
word_vectors = model.embeddings.weight.data.numpy()# ========== 5. 计算相似度 ==========
def most_similar(word, top_n=3):if word not in word2idx:return "单词不在词汇表中"word_vec = word_vectors[word2idx[word]].reshape(1, -1)similarities = np.dot(word_vectors, word_vec.T).squeeze()similar_idx = similarities.argsort()[::-1][1:top_n + 1]return [(idx2word[idx], similarities[idx]) for idx in similar_idx]# 测试
test_words = ["深度", "学习", "人工智能"]
for word in test_words:print(f"【{word}】的相似单词:", most_similar(word))

1. 生成 n-grams

  • FastText 处理单词的 子词单元(n-grams)
  • 例如 "学习" 会生成 ["学习", "习学", "学"]
  • 这样即使遇到未登录词也能拆分为 n-grams 计算

2. 训练数据

  • 使用 CBOW(上下文预测中心词)
  • 窗口大小 = 2,即:
    句子: ["深度", "学习", "是", "人工智能"]
    示例: (["深度", "是"], "学习")
    

3. FastText 模型

  • 词向量是 n-grams 词向量的平均值
  • 计算公式: 
  • 这样,即使单词没见过,也能用它的 n-grams 计算词向量!

 4. 计算相似度

  • cosine similarity 找出最相似的单词
  • FastText 比 Word2Vec 更准确,因为它能利用 n-grams 捕捉词的语义信息
特性FastTextWord2VecGloVe
原理预测中心词 + n-grams预测中心词或上下文统计词共现信息
未登录词处理可处理无法处理无法处理
训练速度 快
适合领域中文、罕见词传统 NLP大规模数据

http://www.ppmy.cn/server/165839.html

相关文章

windows phpstudy python cgi配置

修改apache配置文件:httpd.conf 搜索’Define SRVROOT’&#xff0c; 查看cgi根目录&#xff0c;python脚本需要放在该 Define SRVROOT "D:/Program/phpstudy_pro/Extensions/Apache2.4.39解决中文乱码 文件最后添加AddDefaultCharset gbk 重启apache python脚本: #!py…

云上考场微信小程序的设计与实现(LW+源码+讲解)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

网络安全--边界安全

现在人们生活依赖互联网程度越来越高&#xff0c;网络安全也逐步进入人们日常视野&#xff0c;信用卡信息泄漏、开房记录被查询、商业机密泄漏等等&#xff1b;无不牵动着一个人、一个公司、甚至一个国家的神经。随着技术的发展&#xff0c;网络边界变得也越来越复杂&#xff0…

【自学笔记】GitHub的重点知识点-持续更新

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 GitHub使用指南详细知识点一、GitHub基础与账户管理1. GitHub简介2. 创建与管理GitHub账户3. 创建与配置仓库&#xff08;Repository&#xff09; 二、Git基础与Git…

DeePseek结合PS!批量处理图片的方法教程

​ ​ 今天我们来聊聊如何利用deepseek和Photoshop&#xff08;PS&#xff09;实现图片的批量处理。 传统上&#xff0c;批量修改图片尺寸、分辨率等任务往往需要编写脚本或手动处理&#xff0c;而现在有了AI的辅助&#xff0c;我们可以轻松生成PS脚本&#xff0c;实现自动化处…

iOS 老项目适配 #Preview 预览功能

前言 iOS 开发者 最憋屈的就是UI 布局慢,一直以来没有实时预览功能,虽然swiftUI 早就支持了,但是目前主流还是使用UIKit在布局,iOS 17 苹果推出了 #Preview 可以支持UIKit 实时预览,但是仅仅是 iOS 17,老项目怎么办呢?于是就有了这篇 老项目适配 #Preview 预览 的文章,…

【实战篇】巧用 DeepSeek,让 Excel 数据处理更高效

一、为何选择用 DeepSeek 处理 Excel 在日常工作与生活里,Excel 是我们频繁使用的工具。不管是统计公司销售数据、分析学生成绩,还是梳理个人财务状况,Excel 凭借其强大的功能,如数据排序、筛选和简单公式计算,为我们提供了诸多便利。但当面对复杂的数据处理任务,比如从…

【centOS】安装docker环境,替换国内镜像

1. 更新系统 确保系统是最新的&#xff1a; sudo yum update -y2. 安装依赖包 安装Docker所需的依赖&#xff1a; sudo yum install -y yum-utils device-mapper-persistent-data lvm23. 添加Docker官方仓库 添加Docker的官方YUM仓库&#xff1a; sudo yum-config-manage…