百度AI──自然语言处理使用教程

创建自己的应用

百度研发的预训练模型ERNIE在处理中文任务上自称超越了Bert模型,本次教程以文本的情感分类作为例子,首先在控制台找到nlp模块

在这里插入图片描述
然后创建自己的应用,个人申请的时候应该是不需要审核的,之后就可以看到自己应用下的三个参数:APPID APIKEY Secret Key这三个参数是用来鉴权(oauth2.0认证方式,感兴趣可以自行百度)的,在调用百度AI的接口时需要用到。

在这里插入图片描述

接口调用支持以下语言:

  • 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官方文档

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值