智能文章系统实战-人工智能机器学习预测文章分类(11)

admin 发布于:2018-7-1 10:33  有 1763 人浏览,获得评论 0 条  

1.安装环境

#pip3 install pymysql
#pip3 install jieba
#pip3 install numpy
#pip3 install scipy
#pip3 install sklearn

 

2.机器学习预测分类

 

#!/usr/bin/env python
#-*- coding:utf-8 -*-

#安装环境
#pip3 install pymysql
#pip3 install jieba
#pip3 install numpy
#pip3 install scipy
#pip3 install sklearn


#引入库
import pymysql.cursors  #数据库
import re #正则过滤
import jieba #分词
from sklearn.feature_extraction.text import CountVectorizer  #结构化表示--向量空间模型
from sklearn.model_selection import train_test_split #把数据分成训练集和测试集
from sklearn.naive_bayes import MultinomialNB #朴素贝叶斯分类器


#建立对象
vecObject = CountVectorizer(analyzer='word', max_features=4000,  lowercase = False)
classifierObject = MultinomialNB()

#初始化内容和分类的列表
contentList=[]
categoryList=[]



#定义函数,HTML转化为分词后用空格分离的字符串
def htmlToWords(html):
	reObject = re.compile(r'<[^>]+>',re.S)
	#过滤HTML
	text = reObject.sub('',html)
	#过滤\r\n
	text = re.sub('\t|\n|\r','',text)
	#分词
	words=jieba.cut(text)
	#把分词数组组成字符串返回
	return " ".join(words)
	



# 连接MySQL数据库
connection = pymysql.connect(host='localhost', port=3306, user='root', password='', db='article', charset='utf8', cursorclass=pymysql.cursors.DictCursor)

# 通过cursor创建游标
cursor = connection.cursor()

# 执行数据查询
sql = "SELECT `id`, `title`,`content`,`category` FROM `article` order by id desc limit 100"
cursor.execute(sql)

#查询数据库多条数据
result = cursor.fetchall()
for data in result:
    
	#HTML转化为分词后用空格分离的字符串
	wordsStr=htmlToWords(data['content'])
	
	#添加内容
	contentList.append(wordsStr)
	categoryList.append(data['category'])
	
	

# 关闭数据连接
connection.close()

#把数据分成训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(contentList, categoryList, random_state=1)


#结构化表示--向量空间模型
vecObject.fit(x_train)

#人工智能训练数据
classifierObject.fit(vecObject.transform(x_train), y_train)

#测试 测试集,准确度
score=classifierObject.score(vecObject.transform(x_test), y_test)
print("准确度score=",score,"\n")




#新数据预测分类

#预测分类案例1
predictHTML='<p>人民币对美元中间价为6.5569,创2017年12月25日以来最弱水平。人民币贬值成为市场讨论的热点,在美元短暂升值下,新兴市场货币贬值问题也备受关注。然而,从货币本身的升值与贬值来看,货币贬值的收益率与促进性是正常的,反而货币升值的破坏与打击则是明显的。当前人民币贬值正在进行中,市场预期破7的舆论喧嚣而起。尽管笔者也预计过年内破7的概率存在,但此时伴随中国股市下跌局面,我们应该审慎面对这一问题。</p>' #新的文章内容HTML
predictWords=htmlToWords(predictHTML)
predictCategory=classifierObject.predict(vecObject.transform([predictWords]))
print("案例1分词后文本=",predictWords,"\n")
print("案例1预测文本类别=","".join(predictCategory),"\n\n\n")


#预测分类案例2
predictHTML='<p>25日在报道称,央视罕见播放了多枚“东风-10A”巡航导弹同时命中一栋大楼的画面,坚固的钢筋混凝土建筑在导弹的打击下,瞬间灰飞烟灭。这种一栋大楼瞬间被毁的恐怖画面,很可能是在预演一种教科书式的斩首行动,表明解放军具备了超远距离的精准打击能力</p>' #新的文章内容HTML
predictWords=htmlToWords(predictHTML)
predictCategory=classifierObject.predict(vecObject.transform([predictWords]))
print("案例2分词后文本=",predictWords,"\n")
print("案例2预测文本类别=","".join(predictCategory),"\n")



 

 

3.输出结果

 

[root@bogon python]# python3 predictCategory.py 
Building prefix dict from the default dictionary ...
Loading model from cache /tmp/jieba.cache
Loading model cost 1.588 seconds.
Prefix dict has been built succesfully.
准确度score= 0.8571428571428571 

案例1分词后文本= 人民币 对 美元 中间价 为 6.5569 , 创 2017 年 12 月 25 日 以来 最 弱 水平 。 人民币 贬值 成为 市场 讨论 的 热点 , 在 美元 短暂 升值 下 , 新兴 市场 货币贬值 问题 也 备受 关注 。 然而 , 从 货币 本身 的 升值 与 贬值 来看 , 货币贬值 的 收益率 与 促进性 是 正常 的 , 反而 货币 升值 的 破坏 与 打击 则 是 明显 的 。 当前 人民币 贬值 正在 进行 中 , 市场 预期 破 7 的 舆论 喧嚣 而 起 。 尽管 笔者 也 预计 过年 内破 7 的 概率 存在 , 但 此时 伴随 中国 股市 下跌 局面 , 我们 应该 审慎 面对 这一 问题 。 

案例1预测文本类别= 金融 



案例2分词后文本= 25 日 在 报道 称 , 央视 罕见 播放 了 多枚 “ 东风 - 10A ” 巡航导弹 同时 命中 一栋 大楼 的 画面 , 坚固 的 钢筋 混凝土 建筑 在 导弹 的 打击 下 , 瞬间 灰飞烟灭 。 这种 一栋 大楼 瞬间 被 毁 的 恐怖 画面 , 很 可能 是 在 预演 一种 教科书 式 的 斩首 行动 , 表明 解放军 具备 了 超 远距离 的 精准 打击 能力 

案例2预测文本类别= 军事 

[root@bogon python]#