主頁 >  其他 > 用TFIDF詞袋模型進行新聞分類

用TFIDF詞袋模型進行新聞分類

2021-10-24 08:42:05 其他

詞袋 不關注詞的先后順序---詞袋模型(bow--一元模型) bag of words
二元模型
n-gram

# 創建輸出目錄  保存訓練好的模型
import os#對檔案和目錄進行操作
output_dir = u'output'
if not os.path.exists(output_dir):
    os.mkdir(output_dir)

加載資料

import numpy as np#一個資料分析處理資料的常見的庫,它提供的資料結構比 Python 自身的更高效
import pandas as pd

1.Pandas 是基于 NumPy 的一個開源 Python 庫,它被廣泛用于快速分析資料,以及資料清洗和準備等作業,它的名字來源是由“ Panel data”(面板資料,一個計量經濟學名詞)兩個單詞拼成的,簡單地說,你可以把 Pandas 看作是 Python 版的 Excel,
2. Pandas能很好地處理來自各種不同來源的資料,比如 Excel 表格、CSV 檔案、SQL 資料庫,甚至還能處理存盤在網頁上的資料,
3. Pandas基于Numpy,常常與Numpy、matplotlib一起使用,
4. Pandas庫的兩個主要資料結構:
Series:一維
DataFrame:多維

python list 串列保存的是物件的指標,比如 [0,1,2] 需要保存 3 個指標和 3 個整數的物件,這樣就很浪費記憶體了,

Numpy 是儲存在一個連續的記憶體塊中,節約了計算資源,

# 查看訓練資料
train_data = pd.read_csv('sohu_train.txt', sep='\t', header=None, dtype=np.str_, encoding='utf8',error_bad_lines=False, delimiter="\t", names=[u'頻道', u'文章'])
train_data.head()

# 載入停用詞
stopwords = set()
with open('stopwords.txt', 'r',encoding='utf8') as infile:
    for line in infile:
        line = line.rstrip('\n')
        if line:
            stopwords.add(line.lower())

計算每個文章的tfidf特征

import jieba
from sklearn.feature_extraction.text import TfidfVectorizer

min_df去掉df值小的詞 這樣的詞一般是非常專業的名詞或者是生僻詞 是噪音
max_df 去掉df值很大的詞 這樣詞是常用詞 去掉不要

tfidf = TfidfVectorizer(tokenizer=jieba.lcut, stop_words=stopwords, min_df=50, max_df=0.3)#使用TfidfVectorizer實體化
x = tfidf.fit_transform(train_data[u'文章'])

·輸出結果

Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\10248\AppData\Local\Temp\jieba.cache
Loading model cost 0.550 seconds.
Prefix dict has been built successfully.
E:\ANACODAN\lib\site-packages\sklearn\feature_extraction\text.py:388: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['&', ',', '.', ';', 'e', 'g', 'nbsp', '—', '\u3000', '儻', '兼', '前', '唷', '啪', '啷', '喔', '始', '漫', '然', '特', '竟', '若果', '莫', '見', '設', '說', '達', '非'] not in stop_words.
  warnings.warn('Your stop_words may be inconsistent with '
print(u'詞表大小: {}'.format(len(tfidf.vocabulary_)))
詞表大小: 14516

訓練分類器

編碼目標變數 因為咱們的標簽是字串 sklearn只接受數值

from sklearn.preprocessing import LabelEncoder#LabelEncoder:將類別資料數字化
y_encoder = LabelEncoder()
y = y_encoder.fit_transform(train_data[u'頻道'])#將類別轉換成0,1,2,3,4,5,6,7,8,9...
y[:10]

·輸出結果

array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3])

編碼X變數
x = tfidf.transform(train_data[u'文章'])

# 劃分訓練測驗資料
from sklearn.model_selection import train_test_split#分割資料集
# 根據y分層抽樣,測驗資料占20%
#因為現在資料量很大  此時采用對下標進行分割
train_idx, test_idx = train_test_split(range(len(y)), test_size=0.2, stratify=y)
train_x = x[train_idx, :]#訓練集
train_y = y[train_idx]
test_x = x[test_idx, :]#測驗集
test_y = y[test_idx]

訓練邏輯回歸模型 我們是12分類 屬于多分類

常用引數說明
penalty: 正則項型別,l1還是l2
C: 正則項懲罰系數的倒數,越大則懲罰越小
fit_intercept: 是否擬合常數項
max_iter: 最大迭代次數
multi_class: 以何種方式訓練多分類模型
ovr = 對每個標簽訓練二分類模型
multinomial ovo = 直接訓練多分類模型,僅當solver={newton-cg, sag, lbfgs}時支持
solver: 用哪種方法求解,可選有{liblinear, newton-cg, sag, lbfgs}
小資料liblinear比較好,大資料量sag更快
多分類問題,liblinear只支持ovr模式,其他支持ovr和multinomial
liblinear支持l1正則,其他只支持l2正則

from sklearn.linear_model import LogisticRegression#引入邏輯回歸
model = LogisticRegression(multi_class='multinomial', solver='lbfgs')#solver='lbfgs':求解方式
model.fit(train_x, train_y)

·輸出結果

E:\ANACODAN\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
LogisticRegression(multi_class='multinomial')

模型效果評估

from sklearn.metrics import confusion_matrix, precision_recall_fscore_support
# 在測驗集上計算模型的表現
test_y_pred = model.predict(test_x)
# 計算混淆矩陣
pd.DataFrame(confusion_matrix(test_y, test_y_pred), columns=y_encoder.classes_, index=y_encoder.classes_)

·輸出結果

	體育	健康	女人	娛樂	房地產	教育	文化	新聞	旅游	汽車	科技	財經
體育	193	1	0	1	0	0	3	2	0	0	0	0
健康	0	165	9	0	0	4	0	7	3	0	4	8
女人	1	5	167	4	0	0	13	5	3	0	1	1
娛樂	0	1	9	164	0	5	17	2	0	0	1	1
房地產	0	1	4	0	180	0	0	3	0	0	1	11
教育	0	0	3	2	0	185	2	6	1	0	1	0
文化	0	3	13	17	0	1	153	8	2	1	2	0
新聞	1	4	6	5	1	12	4	124	5	2	11	25
旅游	0	2	8	0	6	1	8	8	163	0	1	3
汽車	1	1	3	0	0	0	0	4	2	182	1	6
科技	0	1	0	0	0	2	2	12	5	1	164	13
財經	1	4	3	0	12	0	4	19	2	4	11	140
# 計算各項評價指標
def eval_model(y_true, y_pred, labels):
    # 計算每個分類的Precision, Recall, f1, support
    p, r, f1, s = precision_recall_fscore_support(y_true, y_pred)
    # 計算總體的平均Precision, Recall, f1, support
    tot_p = np.average(p, weights=s)
    tot_r = np.average(r, weights=s)
    tot_f1 = np.average(f1, weights=s)
    tot_s = np.sum(s)
    res1 = pd.DataFrame({
        u'Label': labels,
        u'Precision': p,
        u'Recall': r,
        u'F1': f1,
        u'Support': s
    })
    res2 = pd.DataFrame({
        u'Label': [u'總體'],
        u'Precision': [tot_p],
        u'Recall': [tot_r],
        u'F1': [tot_f1],
        u'Support': [tot_s]
    })
    res2.index = [999]
    res = pd.concat([res1, res2])
    return res[[u'Label', u'Precision', u'Recall', u'F1', u'Support']]

·輸出結果

eval_model(test_y, test_y_pred, y_encoder.classes_)

Label	Precision	Recall	F1	Support
0	體育	0.979695	0.965	0.972292	200
1	健康	0.877660	0.825	0.850515	200
2	女人	0.742222	0.835	0.785882	200
3	娛樂	0.849741	0.820	0.834606	200
4	房地產	0.904523	0.900	0.902256	200
5	教育	0.880952	0.925	0.902439	200
6	文化	0.742718	0.765	0.753695	200
7	新聞	0.620000	0.620	0.620000	200
8	旅游	0.876344	0.815	0.844560	200
9	汽車	0.957895	0.910	0.933333	200
10	科技	0.828283	0.820	0.824121	200
11	財經	0.673077	0.700	0.686275	200
999	總體	0.827759	0.825	0.825831	2400

模型保存

# 保存模型到檔案  pip install dill 
#注意  我們要把tfidf特征提取模型保存  標簽轉換模型   預測模型
!pip install dill
import dill
import pickle
model_file = os.path.join(output_dir, u'model.pkl')
with open(model_file, 'wb') as outfile:
    dill.dump({
        'y_encoder': y_encoder,
        'tfidf': tfidf,
        'lr': model
    }, outfile)

·輸出結果

Requirement already satisfied: dill in e:\anacodan\lib\site-packages (0.3.4)

測驗模型,對新檔案預測

# 加載新檔案資料
new_data = pd.read_csv('sohu_test.txt', sep='\t', header=None, dtype=np.str_, encoding='utf8',error_bad_lines=False, delimiter="\t", names=[u'頻道', u'文章'])
new_data.head()

# 加載模型
import pickle
model_file = os.path.join(output_dir, u'model.pkl')
with open(model_file, 'rb') as infile:
    model = pickle.load(infile)
# 對新檔案預測(這里只對前10篇預測)
# 1. 轉化為詞袋表示
new_x = model['tfidf'].transform(new_data[u'文章'][:50])

·輸出結果


E:\ANACODAN\lib\site-packages\sklearn\feature_extraction\text.py:388: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['&', ',', '.', ';', 'e', 'g', 'nbsp', '—', '\u3000', '儻', '兼', '前', '唷', '啪', '啷', '喔', '始', '漫', '然', '特', '竟', '若果', '莫', '見', '設', '說', '達', '非'] not in stop_words.
  warnings.warn('Your stop_words may be inconsistent with '
# 2. 預測類別
new_y_pred = model['lr'].predict(new_x)
new_y_pred

·輸出結果

array([3, 0, 3, 3, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
       3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
       3, 3, 3, 3, 3, 3])
# 3. 解釋類別
pd.DataFrame({u'預測頻道': model['y_encoder'].inverse_transform(new_y_pred), u'實際頻道': new_data[u'頻道'][:50]})

·輸出結果

	預測頻道	實際頻道
0	娛樂	娛樂
1	體育	娛樂
2	娛樂	娛樂
3	娛樂	娛樂
4	教育	娛樂
5	娛樂	娛樂
6	娛樂	娛樂
7	娛樂	娛樂
8	娛樂	娛樂
9	娛樂	娛樂
10	娛樂	娛樂
11	娛樂	娛樂
12	娛樂	娛樂
13	娛樂	娛樂
14	娛樂	娛樂
15	娛樂	娛樂
16	娛樂	娛樂
17	娛樂	娛樂
18	娛樂	娛樂
19	娛樂	娛樂
20	娛樂	娛樂
21	娛樂	娛樂
22	娛樂	娛樂
23	娛樂	娛樂
24	娛樂	娛樂
25	娛樂	娛樂
26	娛樂	娛樂
27	娛樂	娛樂
28	娛樂	娛樂
29	娛樂	娛樂
30	娛樂	娛樂
31	娛樂	娛樂
32	娛樂	娛樂
33	娛樂	娛樂
34	娛樂	娛樂
35	娛樂	娛樂
36	娛樂	娛樂
37	娛樂	娛樂
38	娛樂	娛樂
39	娛樂	娛樂
40	娛樂	娛樂
41	娛樂	娛樂
42	娛樂	娛樂
43	娛樂	娛樂
44	娛樂	娛樂
45	娛樂	娛樂
46	娛樂	娛樂
47	娛樂	娛樂
48	娛樂	娛樂
49	娛樂	娛樂

主函式,呼叫模型對新聞進行預測

# 加載模型
import pickle
import os
import numpy as np
import pandas as pd

output_dir = u'output'
if not os.path.exists(output_dir):
    os.mkdir(output_dir)

model_file = os.path.join(output_dir, u'model.pkl')
with open(model_file, 'rb') as infile:
    model = pickle.load(infile)

oo = 1
while oo == 1:
    f = open('yuce.txt', 'w', encoding='utf8')
    f.write(input())
    f.close()
    new1_data = pd.read_csv('yuce.txt', sep='\t', header=None, dtype=np.str_, encoding='utf8', names=[u'文章'])
    new1_data.head()
    # 加載模型
    import pickle

    model_file = os.path.join(output_dir, u'model.pkl')
    with open(model_file, 'rb') as infile:
        model = pickle.load(infile)
    new1_x = model['tfidf'].transform(new1_data[u'文章'])
    # 2. 預測類別
    new1_y_pred = model['lr'].predict(new1_x)
    pd.DataFrame({u'預測頻道': model['y_encoder'].inverse_transform(new1_y_pred)})
    print(pd.DataFrame({u'預測頻道': model['y_encoder'].inverse_transform(new1_y_pred)}))
    with open(r'yuce.txt', 'a+', encoding='utf-8') as test:
        test.truncate(0)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/333571.html

標籤:AI

上一篇:Machine Learning(吳恩達<一>)

下一篇:R語言使用pheatmap繪制熱力圖(資料歸一化、行列聚類、注釋、文字角度、字體)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more