高频词随机抽取

高频词随机抽取

高频词一般是指文档中出现频率较高的且非无用的词.高频次提取其实就是自然语言处理中的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)
### 使用随机森林模型进行投资者情绪分析 #### 数据收集 为了构建有效的投资者情绪分析模型,需先获取高质量的数据集。这些数据应包括但不限于社交媒体帖子、新闻文章以及论坛讨论等内容。此外,还需准备一些标注好的样本作为监督学习的基础,即已知的情绪标签(正面、负面或中立)。这部分工作可能涉及到网络爬虫技术的应用和自然语言处理中的预处理操作[^3]。 #### 特征工程 在获得原始文本之后,下一步就是从中抽取有意义的信息用于机器学习算法输入。对于文字资料来说,常见的做法有词袋模型(Bag of Words),TF-IDF加权方案,或者是更先进的Word Embedding表示法如word2vec, GloVe等。除了传统的NLP手段外,在此场景下还可以考虑加入额外的时间序列特性,比如消息发布时间戳对应的股市指数变动情况;亦或是利用BERT之类的预训练语言模型直接得到句子级别的向量表达[^1]。 #### 模型选择与配置 选定随机森林(Random Forest)作为分类器是因为它具有良好的泛化能力和抗过拟合性质,并且能给出各属性的重要性评分以便于解释最终的结果。具体参数设定方面,则要依据实验效果灵活调整,例如树的数量(n_estimators),最大深度(max_depth)等等。 ```python from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=100, max_depth=None, random_state=42) ``` #### 训练过程 将之前整理出来的带标签语料库划分为训练集和测试集两部分,前者用来指导模型的学习过程而后者则服务于后期的效果评测环节。确保划分方式合理公平,最好采用k折交叉验证(K-fold Cross Validation)策略以提高估计准确性。 ```python from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Training the model clf.fit(X_train, y_train) ``` #### 性能评估 完成上述步骤后即可运用多种指标衡量所建模的好坏程度,像准确率(Accuracy),精确度(Precision),召回率(Recall),F1 Score都是不错的选择。同时也可以绘制混淆矩阵进一步直观展示各类别之间的误判状况。如果条件允许的话,不妨尝试回溯检验的方式看看实际应用环境下的表现如何。 ```python from sklearn.metrics import classification_report, confusion_matrix predictions = clf.predict(X_test) print(confusion_matrix(y_test,predictions)) print(classification_report(y_test,predictions)) ``` #### 结果解读与优化建议 最后一步是对整个流程做出总结并针对发现的问题提出改进建议。假如说某类别的识别精度特别低,那么就应当思考是不是因为该类别本身数量稀少造成的偏差?又或者是否存在某些高频词汇干扰到了正常判断等问题都需要深入探讨解决办法[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值