Text Classification
1.0.0
通過對已有標籤的文本進行訓練,實現新文本的分類。
2019.3.25:項目最初是公司的一個輿情分析業務,後來參加了一些比賽又增加了一些小功能。當時只是想著把機器學習、深度學習的一些簡單的模型整合在一起,鍛煉一下工程能力。和一些網友交流後,覺得沒必要搞一個通用型的模塊(反正也沒人用哈哈~)。最近剛好比較清閒,就本著越簡單越好的目的把沒啥用的花里胡哨的參數和函數都刪了,只保留了預處理和卷積網絡。
準備了單一標籤的電商數據4000多條和多標籤的司法罪名數據15000多條,數據僅供學術研究使用,禁止商業傳播。
from TextClassification . load_data import load_data
# 单标签
data = load_data ( 'single' )
x = data [ 'evaluation' ]
y = [[ i ] for i in data [ 'label' ]]
# 多标签
data = load_data ( 'multiple' )
x = [ i [ 'fact' ] for i in data ]
y = [ i [ 'accusation' ] for i in data ]

用於對原始文本數據做預處理,包含分詞、轉編碼、長度統一等方法,已封裝進TextClassification.py
preprocess = DataPreprocess ()
# 处理文本
texts_cut = preprocess . cut_texts ( texts , word_len )
preprocess . train_tokenizer ( texts_cut , num_words )
texts_seq = preprocess . text2seq ( texts_cut , sentence_len )
# 得到标签
preprocess . creat_label_set ( labels )
labels = preprocess . creat_labels ( labels )整合預處理、網絡的訓練、網絡的預測,demo請參考兩個demo腳本
方法如下:
from TextClassification import TextClassification
clf = TextClassification ()
texts_seq , texts_labels = clf . get_preprocess ( x_train , y_train ,
word_len = 1 ,
num_words = 2000 ,
sentence_len = 50 )
clf . fit ( texts_seq = texts_seq ,
texts_labels = texts_labels ,
output_type = data_type ,
epochs = 10 ,
batch_size = 64 ,
model = None )
# 保存整个模块,包括预处理和神经网络
with open ( './%s.pkl' % data_type , 'wb' ) as f :
pickle . dump ( clf , f )
# 导入刚才保存的模型
with open ( './%s.pkl' % data_type , 'rb' ) as f :
clf = pickle . load ( f )
y_predict = clf . predict ( x_test )
y_predict = [[ clf . preprocess . label_set [ i . argmax ()]] for i in y_predict ]
score = sum ( y_predict == np . array ( y_test )) / len ( y_test )
print ( score ) # 0.9288