百度AI──自然语言处理使用教程 |
您所在的位置:网站首页 › 百度carli使用教程 › 百度AI──自然语言处理使用教程 |
百度AI──自然语言处理使用教程(情感倾向分析)
创建自己的应用python方式调用安装Python SDK创建一个 Python SDK客户端配置AipNlp调用接口情感倾向分析需要注意的几个点
完整代码
参考
创建自己的应用
百度研发的预训练模型ERNIE在处理中文任务上自称超越了Bert模型,本次教程以文本的情感分类作为例子,首先在控制台找到nlp模块
接口调用支持以下语言: NLP-Java-SDK (Java)NLP-PHP-SDK (PHH)NLP-Cpp-SDK (C)NLP-Node-SDK (nodejs)NLP-Python-SDK (python)NLP-C#-SDK (C#)本人实验了python和Java两种方式,使用python比较方便,在数据预处理中可以使用其他的包,但是接口链接时的配置官方给出的不是很全面,而Java相反,可以配置很多调用接口的客户端的一些链接参数,但是数据预处理不方便。 python方式调用 安装Python SDK pip install baidu-aip 创建一个 Python SDK客户端 from aip import AipNlp """ 你的 APPID AK SK """ APP_ID = '你的 App ID' API_KEY = '你的 Api Key' SECRET_KEY = '你的 Secret Key' client = AipNlp(APP_ID, API_KEY, SECRET_KEY) 配置AipNlp如果用户需要配置AipNlp的网络请求参数(一般不需要配置),可以在构造AipNlp之后调用接口设置参数,目前只支持以下参数: 接口说明setConnectionTimeoutInMillis建立连接的超时时间(单位:毫秒)setSocketTimeoutInMillis通过打开的连接传输数据的超时时间(单位:毫秒) 调用接口 情感倾向分析对包含主观观点信息的文本进行情感极性类别(积极、消极、中性)的判断,并给出相应的置信度。 text = "苹果是一家伟大的公司" """ 调用情感倾向分析 """ client.sentimentClassify(text);返回参数 { "text":"苹果是一家伟大的公司", "items":[ { "sentiment":2, //表示情感极性分类结果 "confidence":0.40, //表示分类的置信度 "positive_prob":0.73, //表示属于积极类别的概率 "negative_prob":0.27 //表示属于消极类别的概率 } ] } 需要注意的几个点 单次接口调用的并发量是2,会员是5,意思就是每秒钟只能调用2次。文本的编码方式必须是gbk格式,在传入之前可以自行编码 text = text.encode(encoding='gbk', errors='ignore').decode(encoding='gbk', errors='ignore') 长文本无法处理,特定任务支持的最大长度不一样,可以参考API文档其他接口nlp任务接口可自行查看客户端的源码或者是官方API文档点击查看 完整代码 pymysql 1.0.2 baidu-Aip 2.2.18.0 # encoding=utf-8 from pymysql import connect,cursors from aip import AipNlp import math import logging import time logger = logging.getLogger(__name__) logger.setLevel(level=logging.INFO) handler = logging.FileHandler("baiduAi.log") handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) class BaiduAi: def __init__(self,APP_ID,API_KEY,SECRET_KEY,host,username,pwd,db): # self.APP_ID = APP_ID # self.API_KEY = API_KEY # self.SECRET_KEY = SECRET_KEY self.client = AipNlp(APP_ID,API_KEY,SECRET_KEY) self.conn = connect( host=host, user=username, password=pwd, database=db, charset='utf8' ) def get_document(self,page,size=20): cursor = self.conn.cursor(cursor=cursors.DictCursor) sql = "select * from tweet limit %s,%s" %((page-1)*size,size) cursor.execute(sql) res = cursor.fetchall() cursor.close() return res def get_count(self): cursor = self.conn.cursor() sql = "select count(*) from tweet" cursor.execute(sql) res = cursor.fetchmany(1) cursor.close() return res[0][0] def close(self): self.conn.close() def classify(self,sentence): # 修改编码格式 sentence['text'] = sentence['text'].encode(encoding='gbk', errors='ignore') \ .decode(encoding='gbk', errors='ignore') try: res = self.client.sentimentClassify(sentence['text']) if "items" in res: res = res['items'][0] cursor = self.conn.cursor() sql = "update tweet set positive=%s,negative=%s,sentiment=%s where id=%s" cursor.execute(sql, [res['positive_prob'], res['negative_prob'], res['sentiment'], sentence['id']]) self.conn.commit() cursor.close() else: logger.warning("process text:{}\nencounter warning{},text_id = {}".format(sentence['text'], res['error_msg'],sentence['id'])) except Exception: logger.error("process text:{} \nencounter error,text_id = {}".format(sentence['text']),sentence['id']) if __name__ == '__main__': baiduAi = BaiduAi()//在这里传入你自己的参数 total = baiduAi.get_count() size = 20 page = int(math.ceil(total*1.0/size)) start = time.time() for i in range(86,page+1): logger.info("load data page = %s,size = 20"%i) sentences = baiduAi.get_document(i); for s in sentences: baiduAi.classify(s) time.sleep(1) logger.info("finish classify %s/%s"%(i*20,total)) end = time.time() logger.info("Successfully classify all in %s"%(end-start)) 参考百度Ai官方文档 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |