高频词随机抽取

高频词随机抽取

高频词一般是指文档中出现频率较高的且非无用的词.高频次提取其实就是自然语言处理中的TF(Term Frequence)策略,其主要有一下两个干扰项:
(1)标签符号,一般情况下无实际价值
(2)停用词:诸如“是”、‘哈’等无实意词
需要剔除上述两个干扰项。

随机抽取一定数量的高频词

#将语料转成普通文本(这部分不是必须的)
import codecs
def document_scratch(input_file,output_file):
    input_data = codecs.open(input_file,'r','utf-8') 
    output_data = codecs.open(output_file, 'w', 'utf-8')
    line = input_data.readline()  # 以行的形式进行读取文件
    while line:
        a = line.split()
        b = a[0]
        line= input_data.readline()
        output_data.write(b)#每个句子之间以[sep]分隔
    input_data.close()
    output_data.close()
document_scratch('detailResult10.txt','0010.txt')
#随机抽取代码
#========================正式代码===========================
import codecs
import glob
import random
import jieba
import re
​#对数据进行读取
def get_content(path):
    with open(path,'r',encoding='utf-8',errors='ignore') as f:
        content = ''
        for l in f:
            l = l.strip()
            content += l
        return content
#定义高频词统计函数
def get_TF(words,topK):
    tf_dic = {}
    for w in words:
        tf_dic[w] = tf_dic.get(w,0)+1
    return sorted(tf_dic.items(),key=lambda x: x[1],reverse=True)[:topK]
#滤除停止词
def stop_words(path):
    with open(path,'r',encoding='utf-8',errors='ignore') as f:
        return [l.strip() for l in f]
#剔除纯数字
def find_shuzi(split_shuzi):
    topk_word=[]
    for i in split_shuzi:
        topk_word.append(i[0])
    shuzi = re.findall(r'\d+',''.join(topk_word))
    return shuzi
#查看高频词
def main_with_stop_words():
    files = glob.glob('0010.txt')#读取文件
    corpus = [get_content(x) for x in files]#->list
    corpus = ''.join(corpus)#->str
    split_words = []
    for x in jieba.cut(corpus):
        if x not in stop_words('cn_stopwords.txt'):
            if len(x)> 1:
                split_words.append(x) 
    #split_words = [x for x in jieba.cut(corpus) if x not in stop_words('cn_stopwords.txt')and len(x)> 1]
    length = len(split_words)
    print('分词长度:',length)
    #print(len(split_words))
    fenci_result = '/ '.join(split_words)
    split_words = []
    for x in jieba.cut(corpus):
        if x not in stop_words('cn_stopwords.txt'):
            if len(x)> 1:
                split_words.append(x) 
    #split_words = [x for x in jieba.cut(corpus) if x not in stop_words('cn_stopwords.txt')]#->generator
    split_words=list(split_words)#->list
    split_num = []
    for word in split_words:
        if not word.isdigit():
            split_num.append(word)
    split_words = split_num
    topK_result = get_TF(split_words,topK=length)
    return split_words,topK_result
fenci_result,topK_result = main_with_stop_words()
print(fenci_result)
#随机选取rand_value词并写入文档中
def write_file(rand_value):
    topK_length = len(topK_result)
    high_freq = int(topK_length*0.7)
    common_freq = int(topK_length*0.9)
    topK_list = []
    for word in topK_result:
        topK_list.append(word[0])
    a = topK_list[0:high_freq]#高频子集
    b = topK_list[high_freq:common_freq]#中频子集
    c = topK_list[common_freq:]#低频子集
    rand_value = rand_value#选取子集个数
    rand_a = int(rand_value*0.7)
    rand_b = int(rand_value*0.2)
    rand_c = int(rand_value*0.1)
    a_choice = random.sample(a,rand_a)#各个子集随机抽取
    b_choice = random.sample(b,rand_b)
    c_choice = random.sample(c,rand_c)
    result_merge = a_choice+b_choice+c_choice#合并选取子集
    output_data = codecs.open('a10.txt', 'w+', 'utf-8')#写入文档
    for word in result_merge:
        output_data.write(word+'\n')
write_file(500)
### 负采样的原理与实现 在词嵌入模型中,负采样是一种优化技术,用于减少计算复杂度并提高训练效率。它通过引入负样本的方式简化了原本复杂的 softmax 计算过程。 #### 什么是负采样? 负采样是指在训练过程中,除了正样本外,还随机选取一定数量的负样本参与损失函数的计算。这种方法的核心在于仅更新部分权重而不是整个词汇表中的所有权重,从而显著降低计算成本[^3]。 #### 负采样的具体实现 1. **构建训练样本** 在 Skip-gram 模型中,每一对 (中心词, 上下文词) 构成一个正样本。例如,在给定语句 "the cat sat on the mat" 中,当上下文窗口大小为 1 时,可以生成如下正样本: - ("the", "cat") - ("cat", "the"), ("cat", "sat") - ... 2. **选择负样本** 随机从词汇表中抽取若干个单词作为负样本。这些负样本的选择通常遵循某种分布策略,比如均匀分布、词频分布或自定义分布[^4]。常见的做法是按照词频分布进行调整,使得高频词更有可能被选作负样本。 3. **损失函数的设计** 使用 sigmoid 函数来衡量正样本和负样本的概率得分。对于每一个正样本 $(w_i, c_j)$ 和 $k$ 个负样本 $\{n_1, n_2, ..., n_k\}$,损失函数可表示为: \[ J(\theta) = -\log \sigma(u_{c_j}^\top v_{w_i}) - \sum_{l=1}^{k}\log(1-\sigma(u_{n_l}^\top v_{w_i})) \] 其中,$\sigma(x)=\frac{1}{1+\exp(-x)}$ 是 sigmoid 函数;$v_{w_i}$ 表示中心词 $w_i$ 的向量;$u_{c_j}, u_{n_l}$ 分别代表上下文词 $c_j$ 和第 $l$ 个负样本 $n_l$ 的向量。 4. **梯度下降法更新参数** 利用反向传播算法以及选定的学习率逐步调整各词向量直至收敛到最优解位置附近为止。 ```python import numpy as np def sample_negative_samples(vocab_size, num_negatives, word_frequencies): """ 根据词频分布样负样本 """ probabilities = word_frequencies / sum(word_frequencies) negatives = np.random.choice( range(vocab_size), size=num_negatives, replace=False, p=probabilities ) return negatives # 示例调用 vocab_size = 10000 num_negatives = 5 word_frequencies = [...] # 假设已知词汇表及其对应频率列表 negatives = sample_negative_samples(vocab_size, num_negatives, word_frequencies) print(negatives) ``` 上述代码片段展示了如何依据指定的词频分布来进行负样本的随机样操作。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值