Pytorch网课学习——词向量以及论文的复现

关于词向量

复现的论文为:《Distributed Representations of Words and Phrases and their Compositionality》
论文传送门

实现的编译器为:Jupyter Notebook

第一步:首先导入实验需要用的包,以及设置一些超参数:

# Word2Vec:Skip_Gram用中心词预测周围的词
#pan.baidu.com/s/1tFeK3mXuVXEy3EMy3EMarfeWvg
import torch.nn as nn
import torch
import torch.nn.functional as F
import torch.utils.data as tud

from collections import Counter
import numpy as np
import random
import math

import pandas as pd
import scipy
import sklearn
from sklearn.metrics.pairwise import cosine_similarity

USE_CUDA=torch.cuda.is_available()
random.seed(1)
np.random.seed(1)
torch.manual_seed(1)
if USE_CUDA:
    torch.cuda.manual_seed(1)

# set hyper parameters设置一些超参数
C=3 # content window周围的单词数量
K=100 # number of negative samples 每出现一个正确单词,就要出现K个错误单词
NUM_EPOCH=2
MAX_VOCAB_SIZE=30000
BATCH_SIZE=128
EMBEDDING_SIZE=100
LEARNING_RATE=0.2
def word_tokenize(text):
    return text.split()

第二步:打开数据集,创建高频词词典——编号->单词,单词->编号

with open("E:/科研训练/7月/学习资料Pytorch/最好的网课资料/text8/text8.train.txt","r") as fin:
    text=fin.read()
    
text=text.split()
vocab=dict(Counter(text).most_common(MAX_VOCAB_SIZE-1))
vocab['unk']=len(text)-np.sum(list(vocab.values()))#所有不常见的单词出现的频次
#vocab表示每个单词出现了多少次

这里注意路径的标准写法(当然大家的路径记得改嗷):“E:/科研训练/7月/学习资料Pytorch/最好的网课资料/text8/text8.train.txt”

idx_to_word=[word for word in vocab.keys()]#就直接把词典当中的词按顺序加进去就好
word_to_idx={word:i for i,word in enumerate(idx_to_word)}#词典
#展现前100个
idx_to_word[:100]
list(word_to_idx.items())[:100]

接下来需要记录:

  • 每个单词出现的频次
  • 每个单词的频率(按论文中的进行转换)
  • 词典大小
word_counts=np.array([count for count in vocab.values()],dtype=np.float32)#记录此表中每个单词的频次
word_feqs=word_counts/np.sum(word_counts)#每个单词的频率
word_feqs=word_feqs**(3./4.)
word_feqs=word_feqs/np.sum(word_feqs)
VOCAB_SIZE=len(idx_to_word)
VOCAB_SIZE
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值