首页 > 其他分享 >机器学习日志 新闻标题分类

机器学习日志 新闻标题分类

时间:2023-09-08 23:11:23浏览次数:238  
标签:word sentence text list feature 新闻标题 words 机器 日志

根据标题内容,分类有 财经、彩票、房产、股票、家居、教育、科技、社会、时尚、时政、体育、星座、游戏、娱乐

#导入必要的包
import random
import jieba  # 处理中文
from sklearn import model_selection
from sklearn.naive_bayes import MultinomialNB
import joblib
import re,string
def text_to_words(file_path):#将文本拆分成 词语 和 标签
    sentences_arr = []
    lab_arr = []
    with open(file_path,'r',encoding='utf8') as f:#读文件
        for line in f.readlines():#一行一行的读入
            lab_arr.append(line.split('	')[0])
            sentence = line.split('	')[-1].strip()#得到句子
            sentence = re.sub("[\s+\.\!\/_,$%^*(+\"\')]+|[+——()?【】“”!,。?、~@#¥%……&*()《》:]+", "",sentence) #去除标点符号
            sentence = jieba.lcut(sentence, cut_all=False)#将句子分成词语
            sentences_arr.append(sentence)
    return sentences_arr, lab_arr
def load_stopwords(file_path):#创建停用词表
    stopwords = [line.strip() for line in open(file_path, encoding='UTF-8').readlines()]#line.strip()用于去除两端空格
    return stopwords
def get_dict(sentences_arr,stopswords):#生成词典
    word_dic = {}
    for sentence in sentences_arr:
        for word in sentence:
            if word != ' ' and word.isalpha():#isalpha函数用于判断字符串是否全部由字母组成
                if word not in stopswords:
                    word_dic[word] = word_dic.get(word,1) + 1
    word_dic=sorted(word_dic.items(),key=lambda x:x[1],reverse=True) #按词频序排列

    return word_dic

def get_feature_words(word_dic,word_num):#选取出现次数最多的前 word_num 个单词作为特征词
    n = 0
    feature_words = []
    for word in word_dic:
        if n < word_num:
            feature_words.append(word[0])
        n += 1
    return feature_words

# 文本特征
def get_text_features(train_data_list, test_data_list, feature_words):#根据特征词,将 训练集 和 测试集 中的句子转化为特征向量
    def text_features(text, feature_words):
        text_words = set(text)
        features = [1 if word in text_words else 0 for word in feature_words] # 形成特征向量
        return features
    train_feature_list = [text_features(text, feature_words) for text in train_data_list]
    test_feature_list = [text_features(text, feature_words) for text in test_data_list]
    return train_feature_list, test_feature_list


sentences_arr, lab_arr = text_to_words('Train.txt')#获取分词后的数据及标签
print(sentences_arr[0])
stopwords = load_stopwords('stopwords_cn.txt')#加载停用词
word_dic = get_dict(sentences_arr,stopwords)#生成词典
train_data_list, test_data_list, train_class_list, test_class_list = model_selection.train_test_split(sentences_arr,lab_arr,test_size=0.1)#数据集划分
feature_words =  get_feature_words(word_dic,10000)#生成特征词列表
'''
train_feature_list,test_feature_list = get_text_features(train_data_list,test_data_list,feature_words)#生成特征向量


from sklearn.metrics import accuracy_score,classification_report

#获取朴素贝叶斯分类器
classifier = MultinomialNB(alpha=1.0,  # 拉普拉斯平滑
                          fit_prior=True,  #否要考虑先验概率
                          class_prior=None)


classifier.fit(train_feature_list, train_class_list)#进行训练

predict = classifier.predict(test_feature_list)# 在验证集上进行验证
test_accuracy = accuracy_score(predict,test_class_list)
print("准确率 accuracy_score: %.4lf"%(test_accuracy))
print("模型评估报告 Classification report for classifier:\n",classification_report(test_class_list, predict))


joblib.dump(classifier, "NewsClassification.model")
'''
myModel = joblib.load("NewsClassification.model")

def load_sentence(sentence):
    sentence = re.sub("[\s+\.\!\/_,$%^*(+\"\')]+|[+——()?【】“”!,。?、~@#¥%……&*()《》:]+", "",sentence) #去除标点符号
    sentence = jieba.lcut(sentence, cut_all=False)
    return sentence


lab = [ '财经', '彩票', '房产', '股票', '家居', '教育', '科技', '社会', '时尚', '时政', '体育', '星座', '游戏', '娱乐']


p_data = '合肥一“讲座名师”宣扬“功利性内容”,被高中生当面抢话筒反呛'
sentence = load_sentence(p_data)
sentence= [sentence]
print('分词结果:', sentence)
p_words = get_text_features(sentence,sentence,feature_words)#形成特征向量
res = myModel.predict(p_words[0])
print("所属类型:",lab[int(res)])


cnt=0

file = open("result.txt", 'w',encoding='utf-8')
with open("Test.txt",'r',encoding='utf8') as f:#读文件
    for line in f.readlines():#一行一行的读入
        p_data = line.split('	')[-1].strip()
        sentence = load_sentence(p_data)
        sentence = [sentence]
        p_words = get_text_features(sentence, sentence, feature_words)  # 形成特征向量
        res = myModel.predict(p_words[0])
        file.write(lab[int(res)])
        file.write('\n')

        cnt=cnt+1
        if cnt%1000 ==0:
            print(cnt)
file.close()

标签:word,sentence,text,list,feature,新闻标题,words,机器,日志
From: https://www.cnblogs.com/wljss/p/17688730.html

相关文章

  • JAVA日志技术 & Logback
    前言为什么需要记录日志?我们不可能实时的24小时对系统进行人工监控,那么如果程序出现异常错误时要如何排查呢?并且系统在运行时做了哪些事情我们又从何得知呢?这个时候日志这个概念就出现了,日志的出现对系统监控和异常分析起着至关重要的作用一、日志概括1.了解日志框架JAVA在早期的日......
  • 项目八股[日志系统]
    日志系统涉及到的C++特性语法用了一个锁+两个条件变量,跟线程池不一样只用了一个锁一个条件变量C++11提供的condition_variable类是一个同步原语,它能够阻塞一个或者多个线程,直到另一线程修改共享变量并通知condition_variable。对比POSIX的pthread_cond,pthread移植性好,condi......
  • 机器学习之分类
    分类任务和回归任务的不同之处在于,分类任务需要做出离散的预测。对于多分类任务的神经网络模型,其输出目标通常会用one-hot编码来表示,在输出层中使用softmax函数,同时使用分类交叉熵损失函数进行训练。在本博客中,我们将使用TensorFlow的底层API实现一个基于全连接层的神经网络来进行......
  • java开发之个微机器人的二次开发
    简要描述:修改我在某群的昵称请求URL:http://域名/updateIInChatRoomNickName请求方式:POST请求头Headers:Content-Type:application/jsonAuthorization:login接口返回参数:参数名必选类型说明wId是String登录实例标识请求参数示例{"wId":"4941c159-48dc-4271-b0d0-f94adea39127",......
  • Discourse 的系统日志
    Discourse提供了较为完善的日志查看方式。用得最多的可能就是Logster的基于Web的UI了。LogsterDiscourse的错误日志面板用的是logster,采集的是Rails/Rack的日志,正常应该用Rails::Logger但是discourse做了封装。正常的访问地址为你的域名后面添加logs。例如,可以访问......
  • 机器学习算法原理实现——使用梯度下降求解Lasso回归和岭回归
    本文本质上是在线性回归的基础上进行扩展,加入了正则化而已!机器学习算法原理实现——使用梯度下降求解线性回归 正则化在机器学习中是一种防止过拟合的技术,它通过在损失函数中添加一个惩罚项来限制模型的复杂度。举一个实际的例子,假设你正在训练一个机器学习模型来预测房价。你......
  • 利用时间戳切割Nginx日志
    worker_processes2;events{worker_connections1024;}http{includemime.types;default_typeapplication/octet-stream;log_formataka_logs'{"@timestamp":"$time_iso8601",''&q......
  • 线程池拒接测试添加日志
    /***当线程池耗尽时,由调用者负责执行任务,并打印相关日志*/@Slf4jpublicclassCallerRunsWithLogPolicyimplementsRejectedExecutionHandler{publicvoidrejectedExecution(Runnabler,ThreadPoolExecutore){//shutdown():不会立即终止线程池,而是要......
  • 请大家一定不要像我们公司这样打印log日志
    前言最近接手了公司另一个项目,熟悉业务和代码苦不堪言。我接手一个新项目,有个习惯,就是看结构,看数据库,搜代码。其中搜代码是我个人这些年不知不觉形成的癖好,我下面给大家展示下这个小癖好。正文我面对一个到手的新项目,会主动去搜索一些关键词,让我对这个项目有个整体健......
  • 智能问答系统机器人-知识库搭建使用步骤
    我们都使用过ChatGPT,也能感受得到他的大模型能力。但是,它并不能知道我们企业或个人的私有知识信息。现在,智能客服系统已经搭配了智能知识库AI,基于ChatGPT和私有数据构建智能知识库,智能辅助客服回复用户消息。可以做到全自动回复,或者辅助客服人工回复。现在网站注册账号:https://go......