代码实现词向量模型

时间: 2023-08-03 13:18:55 浏览: 44
以下是一个基于Skip-gram模型实现的词向量代码示例: ```python import numpy as np import random from collections import Counter class SkipGram: def __init__(self, corpus, embedding_size=100, window_size=2, min_count=5, num_negative_samples=5, learning_rate=0.01): self.vocab = self.build_vocab(corpus, min_count) self.word2idx = {w: i for i, w in enumerate(self.vocab)} self.idx2word = {i: w for i, w in enumerate(self.vocab)} self.embedding_size = embedding_size self.window_size = window_size self.min_count = min_count self.num_negative_samples = num_negative_samples self.learning_rate = learning_rate self.W1 = np.random.rand(len(self.vocab), embedding_size) self.W2 = np.random.rand(embedding_size, len(self.vocab)) def build_vocab(self, corpus, min_count): word_counts = Counter(corpus) vocab = [word for word, count in word_counts.items() if count >= min_count] return vocab def generate_training_data(self, corpus): training_data = [] for i, word in enumerate(corpus): word_index = self.word2idx[word] context_indices = [self.word2idx[context] for context in corpus[max(i - self.window_size, 0): min(i + self.window_size, len(corpus))]] for context_index in context_indices: if context_index != word_index: training_data.append((word_index, context_index)) return training_data def sigmoid(self, x): return 1 / (1 + np.exp(-x)) def train(self, corpus, epochs): training_data = self.generate_training_data(corpus) for epoch in range(epochs): random.shuffle(training_data) for word_index, context_index in training_data: context_vector = self.W1[context_index] z = np.dot(self.W2.T, context_vector) sigmoid_z = self.sigmoid(z) negative_samples = random.sample(self.vocab, self.num_negative_samples) negative_indices = [self.word2idx[negative_sample] for negative_sample in negative_samples] negative_vectors = self.W1[negative_indices] negative_z = np.dot(negative_vectors, self.W2.T) negative_sigmoid_z = self.sigmoid(-negative_z) error = sigmoid_z - 1 negative_error = negative_sigmoid_z self.W2[:, word_index] -= self.learning_rate * error * context_vector self.W1[context_index] -= self.learning_rate * error * self.W2[:, word_index] for negative_index, negative_vector in zip(negative_indices, negative_vectors): self.W2[:, negative_index] -= self.learning_rate * negative_error * negative_vector self.W1[negative_index] -= self.learning_rate * negative_error * self.W2[:, negative_index] print(f"Epoch {epoch + 1}/{epochs} completed.") def get_word_vector(self, word): try: word_index = self.word2idx[word] except KeyError: raise KeyError(f"'{word}' not in vocabulary") return self.W1[word_index] ``` 在上述代码中,我们定义了一个SkipGram类,它包含了以下几个主要方法: - `build_vocab`:从语料中建立词汇表。 - `generate_training_data`:生成训练数据,即单词和上下文单词的对。 - `sigmoid`:sigmoid函数。 - `train`:训练模型。 - `get_word_vector`:获取单词的词向量。 我们可以使用以下代码进行训练和获取单词的词向量: ```python corpus = ["i", "am", "a", "boy", "you", "are", "a", "girl"] skip_gram = SkipGram(corpus) skip_gram.train(corpus, epochs=100) print(skip_gram.get_word_vector("boy")) ``` 以上代码会输出“boy”这个单词的词向量。

相关推荐

最新推荐

recommend-type

在python下实现word2vec词向量训练与加载实例

word2vec的原理就不描述了,word2vec词向量工具是由google开发的,输入为文本文档,输出为基于这个文本文档的语料库训练得到的词向量模型。 通过该模型可以对单词的相似度进行量化分析。 word2vec的训练方法有2种,...
recommend-type

基于Selenium的Java爬虫实战(内含谷歌浏览器Chrom和Chromedriver版本116.0.5808.0)

资源包括: 1.Java爬虫实战代码 2.selenium学习笔记 3.代码演示视频 4.谷歌浏览器chrom116.0.5808.0 chrome-linux64.zip chrome-mac-arm64.zip chrome-mac-x64.zip chrome-win32.zip chrome-win64.zip 5.谷歌浏览器驱动器Chromedriver116.0.5808.0 chromedriver-linux64.zip chromedriver-mac-arm64.zip chromedriver-mac-x64.zip chromedriver-win32.zip chromedriver-win64.zip 特别说明:Chrome 为测试版(不会自动更新) 仅适用于自动测试。若要进行常规浏览,请使用可自动更新的标准版 Chrome。)
recommend-type

2024消费趋势报告.pdf

2024消费趋势报告.pdf
recommend-type

PCB的电磁兼容设计+电子设计领域

1、EMC由EMI和EMS组成 2、EMS常见的整改措施 3、干扰=共模干扰+差模干扰 4、元器件的摆放 5、缝隙影响
recommend-type

给排水施工图全套.xdw.pdf

给排水施工图全套.xdw
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

确保MATLAB回归分析模型的可靠性:诊断与评估的全面指南

![确保MATLAB回归分析模型的可靠性:诊断与评估的全面指南](https://img-blog.csdnimg.cn/img_convert/4b823f2c5b14c1129df0b0031a02ba9b.png) # 1. 回归分析模型的基础** **1.1 回归分析的基本原理** 回归分析是一种统计建模技术,用于确定一个或多个自变量与一个因变量之间的关系。其基本原理是拟合一条曲线或超平面,以最小化因变量与自变量之间的误差平方和。 **1.2 线性回归和非线性回归** 线性回归是一种回归分析模型,其中因变量与自变量之间的关系是线性的。非线性回归模型则用于拟合因变量与自变量之间非
recommend-type

引发C++软件异常的常见原因

1. 内存错误:内存溢出、野指针、内存泄漏等; 2. 数组越界:程序访问了超出数组边界的元素; 3. 逻辑错误:程序设计错误或算法错误; 4. 文件读写错误:文件不存在或无法打开、读写权限不足等; 5. 系统调用错误:系统调用返回异常或调用参数错误; 6. 硬件故障:例如硬盘损坏、内存损坏等; 7. 网络异常:网络连接中断、网络传输中断、网络超时等; 8. 程序异常终止:例如由于未知原因导致程序崩溃等。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。