首页 > 其他分享 >评论智能分类

评论智能分类

时间:2022-12-24 12:22:05浏览次数:61  
标签:分类 print label content 智能 train 评论 test model

评论智能分类

一、选题的背景

如今网络购物越来越发达,人们在挑选东西的时候往往会看一下商品的评价信息,信息的量是十分巨大的,因此人工分类已经不能满足需求了,所以就需要计算机来辅助人们对评论进行智能分类

 

二、深度学习的设计方案

  1. 本题选用的数据来自腾讯的开源数据
  2. 本次采用深度框架是 Tensorflow , keras

Tensorflow:TensorFlow™是一个基于数据流编程(dataflow programming)的符号数学系统,被广泛应用于各类机器学习(machine learning)算法的编程实现,其前身是谷歌的神经网络算法库DistBelief [1]  。

Tensorflow拥有多层级结构,可部署于各类服务器、PC终端和网页并支持GPUTPU高性能数值计算,被广泛应用于谷歌内部的产品开发和各领域的科学研究 [1-2]  。

TensorFlow由谷歌人工智能团队谷歌大脑(Google Brain)开发和维护,拥有包括TensorFlow Hub、TensorFlow Lite、TensorFlow Research Cloud在内的多个项目以及各类应用程序接口(Application Programming Interface, API) [2]  。自2015年11月9日起,TensorFlow依据阿帕奇授权协议(Apache 2.0 open source license)开放源代码 [2]  。

Kears:Keras是一个由Python编写的开源人工神经网络库,可以作为Tensorflow、Microsoft-CNTK和Theano的高阶应用程序接口,进行深度学习模型的设计、调试、评估、应用和可视化 [1]  。

Keras在代码结构上由面向对象方法编写,完全模块化并具有可扩展性,其运行机制和说明文档有将用户体验和使用难度纳入考虑,并试图简化复杂算法的实现难度 [1]  。Keras支持现代人工智能领域的主流算法,包括前馈结构和递归结构的神经网络,也可以通过封装参与构建统计学习模型 [2]  。在硬件和开发环境方面,Keras支持多操作系统下的多GPU并行计算,可以根据后台设置转化为Tensorflow、Microsoft-CNTK等系统下的组件 [3]  。

Keras的主要开发者是谷歌工程师François Chollet,此外其GitHub项目页面包含6名主要维护者和超过800名直接贡献者 [4]  。Keras在其正式版本公开后,除部分预编译模型外,按MIT许可证开放源代码 [1]  。

 

  1. 本次采用的NLP(自然语言处理)技术

处理自然语言的关键是要让计算机“理解”自然语言,所以自然语言处理又叫做自

然语言理解(NLU,NaturalLanguage Understanding),也称为计算语言学(Computational     Linguistics)。一方面它是语言信息处理的一个分支,另一方面它是人工智能(AI, Artificial                                  

Intelligence)的核心课题之一。

难点在于计算机不像人们的大脑一样可以进行上下文联系阅读,计算机看不懂文字

解决的思路就是搭建类似人的循环神经网络,在计算机模拟上下文的阅读来进行解决问题

 

 

 

三、深度学习的实现步骤

目的:让计算机智能分类评论

数据的处理:用jieba进行分词

 

 

建立循环神经网络模型:

 

 

 

 

 

训练模型:经过训练模型的准确率可以达到85%

四、总结

  1. 通过本次的学习,感受到深度学习的强大,但也知道计算机无论再强大终究是没能像人一样拥有情感,计算机能做的不过是用词来记住感情的情景
  2. 改进:数据集还是太少了,计算机的算力还是太小了,以后有机会要是用云计算

 

五、代码

import jieba

 

test1 = jieba.cut("杭州西湖风景很好,是旅游胜地!每年吸引很多游客!",cut_all=True)

print("全模式: " + "| " .join(test1))

 

test2 = jieba.cut("杭州西湖风景很好,是旅游胜地!每年吸引很多游客!",cut_all=False)

print("精准模式: " + "| " .join(test2))

 

test3 = jieba.cut("杭州西湖风景很好,是旅游胜地!每年吸引很多游客!")

print("搜索引擎模式: " + "| " .join(test3))

 

 

import jieba

import codecs

import numpy as np

from keras.utils import np_utils

from keras.models import Sequential

from keras.layers import Dense, Dropout

from keras.layers.embeddings import Embedding

from keras.layers.recurrent import LSTM

from keras.preprocessing import sequence

from keras.preprocessing.text import Tokenizer

import tensorflow as tf

import keras.backend as K

from keras.callbacks import LearningRateScheduler

 

def fencil(s):

    cut=jieba.cut(s)

    text=" ".join(cut)

    return text

 

# 导入数据对数据进行切割,做成训练集,测试集,训练标签,测试标签

def makeTrainTestSets():

    commentstype={"中立":0, "正面":1, "负面":2}

    train_label=[]

    train_content=[]

    test_label=[]

    test_content=[]

    fp=codecs.open("sentiment.train.txt", "r", "utf-8")

    n = 0

    # 将一部分数据做成训练集--train_content

    while True:

        cur_text = fp.readline()

        if cur_text=="":

            break

        item=cur_text.split("||")

        train_label.append(commentstype[item[0]])

        tmp="".join(item[1:])

        text=fencil(tmp)

        train_content.append(text)

        n=n+1

    fp.close()

    print("the number of train datasets is:"+str(n))

    fp=codecs.open("sentiment.test.txt", "r", "utf-8")

    n = 0

    # 将一部分数据做成测试集--test_content

    while True:

        cur_text = fp.readline()

        if cur_text == "":

            break

        item = cur_text.split("||")

        test_label.append(commentstype[item[0]])

        tmp = "".join(item[1:])

        text = fencil(tmp)

        test_content.append(text)

        n = n + 1

    fp.close()

    print("the number of test datasets is:" + str(n))

    # 将各个数据用 numpy 以 .npy 文件的形式来保存

    np.save("nlp_train_content.npy",train_content)

    np.save("nlp_train_label.npy",train_label)

    np.save("nlp_test_content.npy",test_content)

    np.save("nlp_test_label.npy",test_label)

    return (train_content,train_label),(test_content,test_label)

# 检查是否生成所需要的数据集,如果没有生成的话就调用 makeTrainTestSets 函数生成所需要的数据

try:

    train_content=np.load("nlp_train_content.npy")

    test_content=np.load("nlp_test_content.npy")

    train_label=np.load("nlp_train_label.npy")

    test_label=np.load("nlp_test_label_npy")

except:

    (train_content,train_label), (test_content,test_label) = makeTrainTestSets()

print("***********succes to finish fenci make train and test data**********")

print(train_label[0])

print(train_content[0])

print(test_content[0])

# 创建字典

token = Tokenizer(num_words=3000)   # num_words 这个参数是规定这个字典的最大长度是3000

token.fit_on_texts(train_content)   # 将 train_content 加在字典中

print(token.document_count)

 

# 数据预处理

trainSqe=token.texts_to_sequences(train_content)

testSqe=token.texts_to_sequences(test_content)

trainPadSqe=sequence.pad_sequences(trainSqe,maxlen=30)           # maxlen 这个参数是规定每一个 train 和 test 数据集的长度为30

testPadSqe=sequence.pad_sequences(testSqe,maxlen=30)             # maxlen 这个参数是规定每一个 train 和 test 数据集的长度为30

 

print(len(trainSqe))

print(len(testSqe))

print(trainPadSqe[0])

print(trainPadSqe.shape)

 

# 进行 one_hot 编码

train_label_ohe=np_utils.to_categorical(train_label)

test_label_ohe=np_utils.to_categorical(test_label)

print(test_label_ohe[0])

 

# 创建模型     本次模型采用的是 < 循环神经网络 (RNN) >

model = Sequential()

model.add(Embedding(output_dim=50, input_dim=3000, input_length=30))              # output_dim 这个参数是把文字转换成50个维度

model.add(Dropout(0.25))

model.add(LSTM(64))                                       # 长短期记忆网络( LSTM ) 是一种 RNN 的特殊的类型,可以学习长期依赖信息

model.add(Dropout(0.3))                                   # 随机丢弃30%的神经元

model.add(Dense(units=3,activation='relu'))               # relu是一个激活函数

model.add(Dropout(0.4))

model.add(Dense(units=3,activation='softmax'))

print(model.summary())

 

# 加载权重文件

try:

    model.load_weights("./sentimenttype.h5")

    print("准备好了!")

except:

    print("还没准备好")

 

model.compile(loss="categorical_crossentropy",optimizer='adam',metrics=['accuracy'])

results=model.evaluate(testPadSqe, test_label_ohe)

print('accuracy=',results[1])

 

import jieba

import codecs

import numpy as np

from keras.utils import np_utils

from keras.models import Sequential

from keras.layers import Dense, Dropout

from keras.layers.embeddings import Embedding

from keras.layers.recurrent import LSTM

from keras.preprocessing import sequence

from keras.preprocessing.text import Tokenizer

import tensorflow as tf

 

def fencil(s):

    cut=jieba.cut(s)

    text=" ".join(cut)

    return text

 

# 导入数据对数据进行切割,做成训练集,测试集,训练标签,测试标签

def makeTrainTestSets():

    commentstype={"中立":0, "正面":1, "负面":2}

    train_label=[]

    train_content=[]

    test_label=[]

    test_content=[]

    fp=codecs.open("sentiment.train.txt", "r", "utf-8")

    n = 0

 

    # 将一部分数据做成训练集--train_content

    while True:

        cur_text = fp.readline()

        if cur_text=="":

            break

        item=cur_text.split("||")

        train_label.append(commentstype[item[0]])

        tmp="".join(item[1:])

        text=fencil(tmp)

        train_content.append(text)

        n=n+1

 

    fp.close()

 

    print("the number of train datasets is:"+str(n))

 

    fp=codecs.open("sentiment.test.txt", "r", "utf-8")

 

    n = 0

 

    # 将一部分数据做成测试集--test_content

    while True:

        cur_text = fp.readline()

        if cur_text == "":

            break

        item = cur_text.split("||")

        test_label.append(commentstype[item[0]])

        tmp = "".join(item[1:])

        text = fencil(tmp)

        test_content.append(text)

        n = n + 1

 

    fp.close()

 

    print("the number of test datasets is:" + str(n))

 

    # 将各个数据用 numpy 以 .npy 文件的形式来保存

    np.save("nlp_train_content.npy",train_content)

 

    np.save("nlp_train_label.npy",train_label)

 

    np.save("nlp_test_content.npy",test_content)

 

    np.save("nlp_test_label.npy",test_label)

 

    return (train_content,train_label),(test_content,test_label)

 

# 检查是否生成所需要的数据集,如果没有生成的话就调用 makeTrainTestSets 函数生成所需要的数据

try:

    train_content=np.load("nlp_train_content.npy")

    test_content=np.load("nlp_test_content.npy")

    train_label=np.load("nlp_train_label.npy")

    test_label=np.load("nlp_test_label_npy")

except:

    (train_content,train_label), (test_content,test_label) = makeTrainTestSets()

 

print("***********succes to finish fenci make train and test data**********")

 

print(train_label[0])

 

print(train_content[0])

 

print(test_content[0])

 

# 创建字典

token = Tokenizer(num_words=3000)   # num_words 这个参数是规定这个字典的最大长度是3000

 

token.fit_on_texts(train_content)   # 将 train_content 加在字典中

 

print(token.document_count)

 

# 数据预处理

trainSqe=token.texts_to_sequences(train_content)

 

testSqe=token.texts_to_sequences(test_content)

 

trainPadSqe=sequence.pad_sequences(trainSqe,maxlen=30)           # maxlen 这个参数是规定每一个 train 和 test 数据集的长度为30

 

testPadSqe=sequence.pad_sequences(testSqe,maxlen=30)             # maxlen 这个参数是规定每一个 train 和 test 数据集的长度为30

 

print(len(trainSqe))

 

print(len(testSqe))

 

print(trainPadSqe[0])

 

print(trainPadSqe.shape)

 

 

# 进行 one_hot 编码

train_label_ohe=np_utils.to_categorical(train_label)

 

test_label_ohe=np_utils.to_categorical(test_label)

 

print(test_label_ohe[0])

 

 

# 创建模型     本次模型采用的是 < 循环神经网络 (RNN) >

 

model = Sequential()                                      #

 

model.add(Embedding(output_dim=50, input_dim=3000, input_length=30))                       # output_dim 这个参数是把文字转换成50个维度

 

model.add(Dropout(0.25))

 

model.add(LSTM(64))                                       # 长短期记忆网络( LSTM ) 是一种 RNN 的特殊的类型,可以学习长期依赖信息

 

model.add(Dropout(0.3))

 

model.add(Dense(units=3,activation='relu'))

 

model.add(Dropout(0.4))

 

model.add(Dense(units=3,activation='softmax'))

 

print(model.summary())

 

 

# 加载权重文件

try:

    model.load_weights("sentimenttype.h5")

 

    print("准备好了!")

 

except:

    print("还没准备好")

 

 

'''

def scheduler(epoch):

    if epoch % 100 == 0 and epoch != 0:

        lr = K.get_value(model.optimizer.lr)

        K.set_value(model.optimizer.lr, lr * 0.01)

        print("lr changed to {}".format(lr * 0.01))

    return K.get_value(model.optimizer.lr)

 

reduce_lr = LearningRateScheduler(scheduler)

'''

 

# 对模型进行训练,对参数的调优

model.compile(loss="categorical_crossentropy",optimizer='adam',metrics=['accuracy'])

 

results=model.evaluate(testPadSqe, test_label_ohe)

 

x  = results[1]

 

for i in range(10000):

    model.compile(tf.keras.optimizers.Adam(lr=0.00001),

 

                  loss="categorical_crossentropy",

 

                  metrics=['acc'])

    train_history = model.fit(x=trainPadSqe,

                              y=train_label_ohe,

                              validation_split=0.2,

                              epochs=10,

                              batch_size=128,

                              verbose=1,

                              )

    results = model.evaluate(testPadSqe, test_label_ohe)

    print('accuracy=', results[1])

    if results[1] >= x :

        x = results[1]

        model.save_weights("sentimenttype.h5")

        print("Save the newly trained model")

    elif results[1] >= 0.85:

        model.save_weights("sentimenttype.h5")

        print("Save the newly trained model")

        break

 

 

'''

# 检验模型的准确率

model.compile(loss="categorical_crossentropy",optimizer='adam',metrics=['accuracy'])

results=model.evaluate(testPadSqe, test_label_ohe)

'''

 

 

标签:分类,print,label,content,智能,train,评论,test,model
From: https://www.cnblogs.com/wyz2541550821/p/17002741.html

相关文章

  • udemy课程和评论的大数据分析
    一、选题的背景Udemy是一个面向学生和专业人士的在线学习平台。Udemy拥有超过5000万学生和57,000名教师,他们以超过65种语言教授课程。与其他在线教育平台不同的是,Udemy不......
  • PHP通过数据库的方式递归查询当前分类ID的所有子分类ID
    /***通过数据库的方式递归查询当前分类ID的所有子分类ID*@param$id*@returnarray*@throwsDataNotFoundException*@throwsDbExcep......
  • PHP通过数据库递归的方式查找当前分类ID的所有上级ID
    /***通过数据库递归的方式查找当前分类ID的所有上级ID*@throwsModelNotFoundException*@throwsDbException*@throwsDataNotFoundExceptio......
  • 机器学习-----心律失常分类
    Python机器学习--------心率失常分类一、选题的背景介绍因为随着我国逐渐步入老龄化社会还有年轻人喜欢熬夜玩游戏,心血管疾病患者持续增加,使得心脏监护系统需求也在不断......
  • java开发的环保网站垃圾分类系统源码
    本项目是基于springboot开发的小区垃圾分类的监管系统。为了更好的督促小区业主更好的进行垃圾分类和垃圾投放,本系统设计了一套积分奖罚机制,如果业主此次投放垃圾符合分类......
  • 数字化智能工厂
    1数字化智能工厂解决方案在工业4.0和中国制造2025的大背景下,智能制造的整体解决方案,解决方案全景如下: 解决方案全景整体解决方案由智能化生产、智能化管理和产业链......
  • 佛萨奇智能合约开发Web3.0元宇宙技术
     Web3就是一个去中心化的互联网,旨在打造出一个全新的合约系统,并颠覆个人和机构达成协议的方式。Web3复刻了第一版互联网(即Web1.0)的去中心化基础架构,Web1.0的特色是用户......
  • SecXOps安全智能分析技术白皮书​ 附下载地址
    模型更新定义内涵本节的模型更新是指在模型训练完成并正式上线后,由运维人员采集并提供新的数据对原有模型进行再训练、更新参数的过程。技术背景随着时间的推移,由于周期性......
  • MobPush智能多通道推送系统,电商APP必不可少的“运营神器”
    当下,电商APP的拉新促活成本高居不下,作为国内移动推送领域的破局者,为了帮助开发者高效开拓用户市场,MobTech袤博科技推出了MobPush智能多通道消息推送系统。作为电商平台最重......
  • 算力,让人工智能不断破圈
    将自己的照片导入软件,你就能看到虚拟世界中的自己;只需在软件中输入几个关键词,绘画小白也能得到一幅色彩绚丽、笔触细腻的作品;无需驾驶员主动操作,车辆就能自动安全操作机动......