word2vector训练数据集整理(代码实现)

news2024/9/27 10:36:31

import math
import os
import random
import torch
import dltools
from matplotlib import pyplot as plt
#读取数据集
def read_ptb():
    """将PTB数据集加载到文本行的列表中"""
    with open('./ptb/ptb.train.txt') as f:
        raw_text = f.read()
    return [line.split() for line in raw_text.split('\n')]

sentences = read_ptb()
print(f'# sentences数:{len(sentences)}')
# sentences数:42069
#构建词表,并把频次低于10的词元替换为<unk>
vocab = dltools.Vocab(sentences, min_freq=10)
print(f'# vocab_size: {len(vocab)}')
#向下采样
def subsample(sentences, vocab):
    #排除未知词元‘<unk>’,对sentences进行处理
    sentences = [[token for token in line if vocab[token] != vocab.unk] for line in sentences]
    #对排除unk的sentences进行tokens计数  (未去重)
    counter = dltools.count_corpus(sentences)
    #聚合
    num_tokens = sum(counter.values())
    
    #若在下采样期间保留词元, 则返回True    
    def keep(token):
        return (random.uniform(0, 1) < math.sqrt(1e-4 / (counter[token] / num_tokens)))
    
    #降低冠词等无意义词的频次,  词频低越容易保留
    return ([[token for token in line if keep(token)] for line in sentences], counter)  

subsampled, counter = subsample(sentences, vocab)
#画出下采样之后的图, 采取下采样前后的20条数据
before = [len(x) for x in sentences[:20]]
after = [len(x) for x in subsampled[:20]]
x = range(len(before))
plt.bar(x, height=before, width=0.4, alpha=0.8, color='red', label='before')
#[i + 0.4 for i in x] 是X轴刻度
plt.bar([i + 0.4 for i in x], height=after, width=0.4, color='green', label='after')
plt.xlabel('tokens per sentences')
plt.ylabel('count')
plt.legend(['before', 'after'])
plt.show()

def compare_counts(token):
    return (f'"{token}"的数量:' f'之前={sum([l.count(token) for l in sentences])}, ' 
            f'之后={sum([l.count(token) for l in subsampled])}')

compare_counts('the')
'"the"的数量:之前=50770, 之后=2000' 
compare_counts('publishing')

 '"publishing"的数量:之前=64, 之后=64'

#将词元映射到他们在语料库中的索引
corpus = [vocab[line] for line in subsampled]
corpus[:3]

 [[], [71, 2115], [5277, 3054, 1580, 95]] 

#中心词和上下文词的提取
def get_centers_and_contetxs(corpus, max_window_size):
    """返回skip_gram模型中的中心词和上下文词"""
    centers, contexts = [], []
    for line in corpus:
        #要形成“中心词——上下文词对”, 每个句子至少需要有2个词
        if len(line) < 2:
            continue
        centers += line #把满足条件的line放于中心词列表中
        for idx, i in enumerate(range(len(line))):   #上下文窗口的中间token的索引为i
            window_size = random.randint(1, max_window_size)
            print('中心词 {} 的窗口大小:{}'.format(idx, window_size))
            indices = list(range(max(0, i - window_size), min(len(line), i + window_size + 1)))
            #从上下文词中排除中心词
            indices.remove(i)
            contexts.append([line[x] for x in indices])
    return centers, contexts
#假设数据
tiny_dataset = [list(range(7)), list(range(7,10))]
print('数据集', tiny_dataset)
#表示解压函数,用于将打包的元组解压回原来的序列
for center, context in zip(*get_centers_and_contetxs(tiny_dataset, 2)):
    print('中心词:',center, '的上下文词是:', context)

数据集 [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9]]
中心词 0 的窗口大小:1
中心词 1 的窗口大小:2
中心词 2 的窗口大小:2
中心词 3 的窗口大小:1
中心词 4 的窗口大小:2
中心词 5 的窗口大小:2
中心词 6 的窗口大小:2
中心词 0 的窗口大小:2
中心词 1 的窗口大小:1
中心词 2 的窗口大小:1
中心词 0 的上下文词是 [1]
中心词 1 的上下文词是 [0, 2, 3]
中心词 2 的上下文词是 [0, 1, 3, 4]
中心词 3 的上下文词是 [2, 4]
中心词 4 的上下文词是 [2, 3, 5, 6]
中心词 5 的上下文词是 [3, 4, 6]
中心词 6 的上下文词是 [4, 5]
中心词 7 的上下文词是 [8, 9]
中心词 8 的上下文词是 [7, 9]
中心词 9 的上下文词是 [8]
#在PTB上进行中心词和背景词提取
#max_window_size=5  业界常用到的数值,效果比较好
all_centers, all_contexts = get_centers_and_contetxs(corpus, 5)
'“中心词-上下文词对”的数量:{}'.format( sum([len(contexts) for contexts in all_contexts]))

 '“中心词-上下文词对”的数量:1499666'

#负采样_按权重抽取
class RandomGenerator:
    """根据n个采样权重在{1,2,,3,...n}中随机抽取"""
    def __init__(self, sampling_weights):
        #Exclude 排除
        self.population = list(range(1, len(sampling_weights) + 1))  #对采样数据的编号
        self.sampling_weights = sampling_weights
        self.candidates = []  #采样结果
        self.i = 0
        
    def draw(self):
        if self.i == len(self.candidates):
            #缓存k个随机采样的结果    # population:集群。 weights:相对权重。 cum_weights:累加权重。 k:选取次数
            self.candidates = random.choices(self.population, self.sampling_weights, k=10000)  #k最大值=10000(采样数量)
            self.i = 0
        self.i += 1
        return self.candidates[self.i - 1]
#假设数据验证
generator = RandomGenerator([2, 3, 4])
[generator.draw() for _ in range(10)]

 [2, 1, 1, 2, 1, 1, 3, 2, 3, 2]

#返回负采样中的噪声词
def get_negatives(all_contetxs, vocab, counter, K):
    #索引为1,2,....(索引0是此表中排除的未知标记)
    sampling_weights = [counter[vocab.to_tokens(i)]**0.75 for i in range(1, len(vocab))]
    all_negatives, generator = [], RandomGenerator(sampling_weights)
    for contexts in all_contetxs:  #遍历背景词
        negatives = []
        while len(negatives) < len(contexts) * K:
            neg = generator.draw()
            #噪声词不能是上下文词
            if neg not in contexts:
                negatives.append(neg)
        all_negatives.append(negatives)
    return all_negatives

all_negatives = get_negatives(all_contexts, vocab, counter, 5)
        
# 小批量操作
def batchify(data):
    """返回带有负采样的跳元模型的小批量样本"""
    max_len = max(len(c) + len(n) for _, c, n in data)
    centers, contexts_negatives, masks, labels = [], [], [], []
    for center, context, negative in data:
        cur_len = len(context) + len(negative)
        centers += [center]
        contexts_negatives += \
            [context + negative + [0] * (max_len - cur_len)]
        masks += [[1] * cur_len + [0] * (max_len - cur_len)]
        labels += [[1] * len(context) + [0] * (max_len - len(context))]
    return (torch.tensor(centers).reshape((-1, 1)), torch.tensor(
        contexts_negatives), torch.tensor(masks), torch.tensor(labels))
#小批量的例子
x_1 = (1, [2, 2], [3, 3, 3, 3])
x_2 = (1, [2, 2, 2], [3, 3])
batch = batchify((x_1, x_2))

names = ['centers', 'contexts_negative', 'masks', 'labels']
for name, data in zip(names, batch):
    print(name, '=', data)

centers = tensor([[1],
        [1]])
contexts_negative = tensor([[2, 2, 3, 3, 3, 3],
        [2, 2, 2, 3, 3, 0]])
masks = tensor([[1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 0]])
labels = tensor([[1, 1, 0, 0, 0, 0],
        [1, 1, 1, 0, 0, 0]])
#整合后的数据加载处理模块
def load_data_ptb(batch_size, max_window_size, num_noise_words):
    """下载PTB数据集, 然后将其加载到内存中"""
    #加载PTB数据集
    sentences = read_ptb()
    #获取词汇表
    vocab = dltools.Vocab(sentences, min_freq=10)
    #下采样
    subsampled, counter = subsample(sentences, vocab)
    #语料库
    corpus = [vocab[line] for line in subsampled]
    #获取中心词与背景词
    all_centers, all_contexts = get_centers_and_contetxs(corpus, max_window_size)
    #获取噪声词
    get_negatives(all_contetxs, vocab, counter, num_noise_words)
    
    class PTBDataset(torch.utils.data.Dataset):
        def __init__(self, centers, contexts, negatives):
            assert len(centers) == len(contexts) == len(negatives)
            self.centers = centers
            self.contexts = contexts
            self.negatives = negatives
            
        def __getitem__(self, index):
            return (self.centers[index], self.contexts[index],
                    self.negatives[index])
        
        def __len__(self):
            return len(self.centers)

        
    dataset = PTBDataset(all_centers, all_contexts, all_negatives)
    
    data_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True, collate_fn = batchify)
    return data_iter, vocab
data_iter, vocab = load_data_ptb(5, 5, 5)
for batch in data_iter:
    for name, data in zip(names, batch):
        print(name, 'shape:', data.shape)
    break
centers shape: torch.Size([5, 1])
contexts_negatives shape: torch.Size([5, 48])
masks shape: torch.Size([5, 48])
labels shape: torch.Size([5, 48])
batch

(tensor([[1259],
         [ 627],
         [5679],
         [   3],
         [ 960]]),
 tensor([[1983, 1136, 1186,   15, 3216, 5351,  512,  321, 2208, 1396,   60,  782,
            63,  929,  149,  105,  305,    7,   74,   11, 1530,    1, 5893, 2668,
             0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
             0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0],
         [ 298, 1960, 1098, 1288,    6, 1689, 4808,  981, 2040, 3887,  385,   59,
          2167, 4424,   91, 4159,   65, 1271, 3621, 6020,  585, 1426, 5097,  335,
            18,  770, 5317, 1408, 5828, 3321,  836,  529, 1772,  365, 6718,  269,
           101,  209, 1450,    1,   47,  834,    8,    2,  979,   28, 4029,  471],
         [6034,    2, 4028,  829, 1042, 5340,    0,    0,    0,    0,    0,    0,
             0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
             0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
             0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0],
         [ 678,  582, 5033, 4220,  959,  280,  124,  397,  211,  787, 2795,  383,
            18,   16, 1293, 1212, 2149, 2627,  623,    8, 4467,  155, 3932, 1447,
          5595,   27,   15,   81,  283, 2631,  410,  938,    4,  344, 5204,  233,
           149,    2, 4933, 5675,   62,  182,   18, 1186,  227, 2429, 2349,   31],
         [ 128, 1332, 3790, 1370,  950,  119, 1369, 1328, 1007, 2831,  782,  374,
           723,   13,   14,   76,  618,    1,  821,  143, 2317, 5730,  978,  753,
           839, 2055,  160,   12,  377,    4,    0,    0,    0,    0,    0,    0,
             0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,    0]]),
 tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
         [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
         [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
          1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]),
 tensor([[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
         [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2169706.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【深度学习基础模型】双向循环神经网络(Bidirectional Recurrent Neural Networks, BiRNN)详细理解并附实现代码。

【深度学习基础模型】双向循环神经网络&#xff08;Bidirectional Recurrent Neural Networks, BiRNN&#xff09; 【深度学习基础模型】双向循环神经网络&#xff08;Bidirectional Recurrent Neural Networks, BiRNN&#xff09;详细理解并附实现代码。 文章目录 【深度学习…

使用 Llama 3.1 和 Qdrant 构建多语言医疗保健聊天机器人的步骤

长话短说&#xff1a; 准备好深入研究&#xff1a; 矢量存储的复杂性以及如何利用 Qdrant 进行高效数据摄取。掌握 Qdrant 中的集合管理以获得最佳性能。释放上下文感知响应的相似性搜索的潜力。精心设计复杂的 LangChain 工作流程以增强聊天机器人的功能。将革命性的 Llama …

虚幻蓝图Ai随机点移动

主要函数: AI MoveTo 想要AI移动必须要有 导航网格体边界体积 (Nav Mesh Bounds Volume) , 放到地上放大 , 然后按P键 , 可以查看范围 然后创建一个character类 这样连上 AI就会随机运动了 为了AI移动更自然 , 取消使用控制器旋转Yaw 取消角色移动组件 的 使用控制器所需的…

风扇模块(直流5V STM32)

目录 一、介绍 二、传感器原理 1.原理图 2.引脚描述 三、程序设计 main.c文件 fan.h文件 fan.c文件 四、实验效果 五、资料获取 项目分享 一、介绍 直流风扇(Fan)&#xff0c;具有高转速、大风量、低噪音、低能耗和低震动的特点&#xff0c;有DC5V和12V两种型号可供…

【HarmonyOS】Web组件同步与异步数据获取

Web组件交互同步与异步获取数据的方式示例 【html测试文件】src/main/resources/rawfile/Page04.html <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><script>let isEnvSupported CSS in window &&…

云上攻防 | AWS中的常见 Cognito 配置错误

引言 AWS Cognito 是由亚马逊网络服务&#xff08;AWS&#xff09;提供的全托管服务&#xff0c;旨在简化 Web 和移动应用程序的用户认证和授权过程。它提供了一整套功能来处理用户注册、登录和用户管理&#xff0c;免去了开发人员从头构建这些功能的需求。 尽管本文讨论的攻…

8.11 矢量图层线要素单一符号使用二(箭头)

8.11 矢量图层线要素单一符号使用二(箭头)_qgis箭头-CSDN博客 目录 前言 箭头&#xff08;Arrow&#xff09; QGis设置线符号为箭头(Arrow) 二次开发代码实现 总结 前言 本章介绍矢量图层线要素单一符号中箭头&#xff08;Arrow&#xff09;的使用说明&#xff1a;文章中…

等保2.0数据库测评之达梦数据库测评

一、达梦数据库介绍 达梦数据库管理系统属于新一代大型通用关系型数据库&#xff0c;全面支持 ANSI SQL 标准和主流编程语言接口/开发框架。行列融合存储技术&#xff0c;在兼顾 OLAP 和 OLTP 的同时&#xff0c;满足 HTAP 混合应用场景。 本次安装环境为Windows10专业版操作…

华夏ERP3.1权限绕过代码审计

POC: /jshERP-boot/user/getAllList;.ico 调试分析poc: 这是poc很明显就是绕过权限&#xff0c;我们分析filter里面的代码。 Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {Htt…

基于Spring Boot的校园管理系统

目录 前言 功能设计 系统实现 获取源码 博主主页&#xff1a;百成Java 往期系列&#xff1a;Spring Boot、SSM、JavaWeb、python、小程序 前言 随着科学技术的飞速发展&#xff0c;社会的方方面面、各行各业都在努力与现代的先进技术接轨&#xff0c;通过科技手段来提高自…

使用API有效率地管理Dynadot域名,设置域名服务器(NS)

前言 Dynadot是通过ICANN认证的域名注册商&#xff0c;自2002年成立以来&#xff0c;服务于全球108个国家和地区的客户&#xff0c;为数以万计的客户提供简洁&#xff0c;优惠&#xff0c;安全的域名注册以及管理服务。 Dynadot平台操作教程索引&#xff08;包括域名邮箱&…

SQL Server的文本和图像函数

新书速览|SQL Server 2022从入门到精通&#xff1a;视频教学超值版_sql server 2022 出版社-CSDN博客 《SQL Server 2022从入门到精通&#xff08;视频教学超值版&#xff09;&#xff08;数据库技术丛书&#xff09;》(王英英)【摘要 书评 试读】- 京东图书 (jd.com) SQL Se…

【Python】Ajenti:轻量级、强大的服务器管理面板

在现代服务器管理中&#xff0c;管理员们经常需要通过命令行执行各种任务&#xff0c;这不仅耗时&#xff0c;而且对不熟悉 Linux 系统的用户来说并不友好。为了更高效地管理服务器、网站和应用&#xff0c;借助一个功能强大的管理面板是非常有必要的。Ajenti 就是这样一款轻量…

MySql数据库---判断函数,和窗口结合的函数,窗口函数

思维导图 判断函数 if(expr,v1,v2): 表达式结果为true返回v1,否则返回v2 ifnull(列名,dv): 列值为null返回dv,否则返回列值. nullif(expr1,expr2): 表达式1表达式2返回null,不等于返回表达式1的值. 窗口函数 作用: 可以为表新增一列,新增的列是什么取决于over()函数前面的函…

Spring Boot入门到精通:网上购物商城系统

第3章 系统分析 3.1 可行性分析 在系统开发之初要进行系统可行分析&#xff0c;这样做的目的就是使用最小成本解决最大问题&#xff0c;一旦程序开发满足用户需要&#xff0c;带来的好处也是很多的。下面我们将从技术上、操作上、经济上等方面来考虑这个系统到底值不值得开发。…

Cisco Secure Firewall Management Center Virtual 7.6.0 发布下载,新增功能概览

Cisco Secure Firewall Management Center Virtual 7.6.0 - 思科 Firepower 管理中心软件 Firepower Management Center Software for ESXi & KVM 请访问原文链接&#xff1a;https://sysin.org/blog/cisco-fmc-7/&#xff0c;查看最新版。原创作品&#xff0c;转载请保留…

WPS中让两列数据合并的方法

有这样一个需求&#xff0c;就是把A列数据和B列数据进行合并&#xff08;空单元格略过&#xff09;具体实现效果如图下&#xff1a; 该如何操作呢&#xff1f; 首先在新的一列第一个单元格中输入公式"A1&B1" 然后回车&#xff0c;就出现了两列单元格数据合并的效…

人员个体检测、PID行人检测、行人检测算法样本

人员个体检测算法主要用于视频监控、安全防范、人流统计、行为分析等领域&#xff0c;通过图像识别技术来检测和识别视频或图像中的人员个体。这种技术可以帮助管理者实时监控人员活动&#xff0c;确保安全和秩序&#xff0c;提高管理效率。 一、技术实现 人员个体检测算法通常…

光耦——连接半导体创新的桥梁

半导体技术作为现代科技的重要支柱之一&#xff0c;在电子、通信、能源等领域都有着广泛的应用。而在半导体领域&#xff0c;光耦作为一种重要的光电器件&#xff0c;正以其独特的优势和广泛的应用领域&#xff0c;为半导体创新注入新的活力&#xff0c;成为连接半导体创新的桥…

IMX6UL开发板中断实验(三)

在上一节我们编写完成了中断驱动文件和中断驱动头文件&#xff0c;那么这一讲我们将继续中断实验 下面就是GPIO的中断设置&#xff0c;第一步要设置中断GPIO的触发方式&#xff0c;首先我们先看到寄存器&#xff0c;一共有GPIOx_ICR1和ICR2&#xff0c; 图如上&#xff0c;ICR1…