自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

自然語言處理第一番之文本分類器

大數(shù)據(jù) 自然語言處理
文本分類應(yīng)該是自然語言處理中最普遍的一個應(yīng)用,例如文章自動分類、郵件自動分類、垃圾郵件識別、用戶情感分類等等,在生活中有很多例子,這篇文章主要從傳統(tǒng)和深度學(xué)習(xí)兩塊來解釋下我們?nèi)绾巫鲆粋€文本分類器。

[[194511]]

前言

文本分類應(yīng)該是自然語言處理中最普遍的一個應(yīng)用,例如文章自動分類、郵件自動分類、垃圾郵件識別、用戶情感分類等等,在生活中有很多例子,這篇文章主要從傳統(tǒng)和深度學(xué)習(xí)兩塊來解釋下我們?nèi)绾巫鲆粋€文本分類器。

文本分類方法

傳統(tǒng)的文本方法的主要流程是人工設(shè)計一些特征,從原始文檔中提取特征,然后指定分類器如LR、SVM,訓(xùn)練模型對文章進行分類,比較經(jīng)典的特征提取方法如頻次法、tf-idf、互信息方法、N-Gram。

深度學(xué)習(xí)火了之后,也有很多人開始使用一些經(jīng)典的模型如CNN、LSTM這類方法來做特征的提取, 這篇文章會比較粗地描述下,在文本分類的一些實驗

傳統(tǒng)文本分類方法

這里主要描述兩種特征提取方法:頻次法、tf-idf、互信息、N-Gram。

頻次法

頻次法,顧名思義,十分簡單,記錄每篇文章的次數(shù)分布,然后將分布輸入機器學(xué)習(xí)模型,訓(xùn)練一個合適的分類模型,對這類數(shù)據(jù)進行分類,需要指出的時,在統(tǒng)計次數(shù)分布時,可合理提出假設(shè),頻次比較小的詞對文章分類的影響比較小,因此我們可合理地假設(shè)閾值,濾除頻次小于閾值的詞,減少特征空間維度。

TF-IDF

TF-IDF相對于頻次法,有更進一步的考量,詞出現(xiàn)的次數(shù)能從一定程度反應(yīng)文章的特點,即TF,而TF-IDF,增加了所謂的反文檔頻率,如果一個詞在某個類別上出現(xiàn)的次數(shù)多,而在全部文本上出現(xiàn)的次數(shù)相對比較少,我們認(rèn)為這個詞有更強大的文檔區(qū)分能力,TF-IDF就是綜合考慮了頻次和反文檔頻率兩個因素。

互信息方法

互信息方法也是一種基于統(tǒng)計的方法,計算文檔中出現(xiàn)詞和文檔類別的相關(guān)程度,即互信息

N-Gram

基于N-Gram的方法是把文章序列,通過大小為N的窗口,形成一個個Group,然后對這些Group做統(tǒng)計,濾除出現(xiàn)頻次較低的Group,把這些Group組成特征空間,傳入分類器,進行分類。

深度學(xué)習(xí)方法

基于CNN的文本分類方法

  • 最普通的基于CNN的方法就是Keras上的example做情感分析,接Conv1D,指定大小的window size來遍歷文章,加上一個maxpool,如此多接入幾個,得到特征表示,然后加上FC,進行最終的分類輸出。
  • 基于CNN的文本分類方法,最出名的應(yīng)該是2014 Emnlp的 Convolutional Neural Networks for Sentence Classification,使用不同filter的cnn網(wǎng)絡(luò),然后加入maxpool, 然后concat到一起。 

 

  • 這類CNN的方法,通過設(shè)計不同的window size來建模不同尺度的關(guān)系,但是很明顯,丟失了大部分的上下文關(guān)系,Recurrent Convolutional Neural Networks for Text Classification,將每一個詞形成向量化表示時,加上上文和下文的信息,每一個詞的表示如下:

 

整個結(jié)構(gòu)框架如下:

 

 

  • 如針對這句話”A sunset stroll along the South Bank affords an array of stunning vantage points”,stroll的表示包括c_l(stroll),pre_word2vec(stroll),c_r(stroll), c_l(stroll)編碼A sunset的語義,而c_r(stroll)編碼along the South Bank affords an array of stunning vantage points的信息,每一個詞都如此處理,因此會避免普通cnn方法的上下文缺失的信息。

基于LSTM的方法

  • 和基于CNN的方法中***種類似,直接暴力地在embedding之后加入LSTM,然后輸出到一個FC進行分類,基于LSTM的方法,我覺得這也是一種特征提取方式,可能比較偏向建模時序的特征;
  • 在暴力的方法之上,A C-LSTM Neural Network for Text Classification,將embedding輸出不直接接入LSTM,而是接入到cnn,通過cnn得到一些序列,然后吧這些序列再接入到LSTM,文章說這么做會提高***分類的準(zhǔn)去率。

代碼實踐

語料及任務(wù)介紹

訓(xùn)練的語料來自于大概31個新聞類別的新聞?wù)Z料,但是其中有一些新聞數(shù)目比較少,所以取了數(shù)量比較多的前20個新聞類比的新聞?wù)Z料,每篇新聞稿字?jǐn)?shù)從幾百到幾千不等,任務(wù)就是訓(xùn)練合適的分類器然后將新聞分為不同類別: 

 

Bow

Bow對語料處理,得到tokens set:

  1. def __get_all_tokens(self): 
  2.     """ get all tokens of the corpus 
  3.     ""
  4.     fwrite = open(self.data_path.replace("all.csv","all_token.csv"), 'w'
  5.     with open(self.data_path, "r"as fread: 
  6.         i = 0 
  7.         # while True
  8.         for line in fread.readlines(): 
  9.             try: 
  10.                 line_list = line.strip().split("\t"
  11.                 label = line_list[0] 
  12.                 self.labels.append(label) 
  13.                 text = line_list[1] 
  14.                 text_tokens = self.cut_doc_obj.run(text) 
  15.                 self.corpus.append(' '.join(text_tokens)) 
  16.                 self.dictionary.add_documents([text_tokens]) 
  17.                 fwrite.write(label+"\t"+"\\".join(text_tokens)+"\n") 
  18.                 i+=1 
  19.             except BaseException as e: 
  20.                 msg = traceback.format_exc() 
  21.                 print msg 
  22.                 print "=====>Read Done<======" 
  23.                 break 
  24.     self.token_len = self.dictionary.__len__() 
  25.     print "all token len "+ str(self.token_len) 
  26.     self.num_data = i 
  27.     fwrite.close()  

然后,tokens set 以頻率閾值進行濾除,然后對每篇文章做處理來進行向量化:

  1. def __filter_tokens(self, threshold_num=10): 
  2.     small_freq_ids = [tokenid for tokenid, docfreq in self.dictionary.dfs.items() if docfreq < threshold_num ] 
  3.     self.dictionary.filter_tokens(small_freq_ids) 
  4.     self.dictionary.compactify() 
  5.  
  6. def vec(self): 
  7.     """ vec: get a vec representation of bow 
  8.     ""
  9.     self.__get_all_tokens() 
  10.     print "before filter, the tokens len: {0}".format(self.dictionary.__len__()) 
  11.     self.__filter_tokens() 
  12.     print "After filter, the tokens len: {0}".format(self.dictionary.__len__()) 
  13.     self.bow = [] 
  14.     for file_token in self.corpus: 
  15.         file_bow = self.dictionary.doc2bow(file_token) 
  16.         self.bow.append(file_bow) 
  17.     # write the bow vec into a file 
  18.     bow_vec_file = open(self.data_path.replace("all.csv","bow_vec.pl"), 'wb'
  19.     pickle.dump(self.bow,bow_vec_file) 
  20.     bow_vec_file.close() 
  21.     bow_label_file = open(self.data_path.replace("all.csv","bow_label.pl"), 'wb'
  22.     pickle.dump(self.labels,bow_label_file) 
  23.     bow_label_file.close()  

最終就得到每篇文章的bow的向量,由于這塊的代碼是在我的筆記本上運行的,直接跑占用內(nèi)存太大,因為每一篇文章在token set中的表示是極其稀疏的,因此我們可以選擇將其轉(zhuǎn)為csr表示,然后進行模型訓(xùn)練,轉(zhuǎn)為csr并保存中間結(jié)果代碼如下:

  1. def to_csr(self): 
  2.     self.bow = pickle.load(open(self.data_path.replace("all.csv","bow_vec.pl"), 'rb')) 
  3.     self.labels = pickle.load(open(self.data_path.replace("all.csv","bow_label.pl"), 'rb')) 
  4.     data = [] 
  5.     rows = [] 
  6.     cols = [] 
  7.     line_count = 0 
  8.     for line in self.bow: 
  9.         for elem in line: 
  10.             rows.append(line_count) 
  11.             cols.append(elem[0]) 
  12.             data.append(elem[1]) 
  13.         line_count += 1 
  14.     print "dictionary shape ({0},{1})".format(line_count, self.dictionary.__len__()) 
  15.     bow_sparse_matrix = csr_matrix((data,(rows,cols)), shape=[line_count, self.dictionary.__len__()]) 
  16.     print "bow_sparse matrix shape: " 
  17.     print bow_sparse_matrix.shape 
  18.     # rarray=np.random.random(size=line_count) 
  19.     self.train_set, self.test_set, self.train_tag, self.test_tag = train_test_split(bow_sparse_matrix, self.labels, test_size=0.2) 
  20.     print "train set shape: " 
  21.     print self.train_set.shape 
  22.     train_set_file = open(self.data_path.replace("all.csv","bow_train_set.pl"), 'wb'
  23.     pickle.dump(self.train_set,train_set_file) 
  24.     train_tag_file = open(self.data_path.replace("all.csv","bow_train_tag.pl"), 'wb'
  25.     pickle.dump(self.train_tag,train_tag_file) 
  26.     test_set_file = open(self.data_path.replace("all.csv","bow_test_set.pl"), 'wb'
  27.     pickle.dump(self.test_set,test_set_file) 
  28.     test_tag_file = open(self.data_path.replace("all.csv","bow_test_tag.pl"), 'wb'
  29.     pickle.dump(self.test_tag,test_tag_file)  

***訓(xùn)練模型代碼如下: 

  1. def train(self): 
  2.     print "Beigin to Train the model" 
  3.     lr_model = LogisticRegression() 
  4.     lr_model.fit(self.train_set, self.train_tag) 
  5.     print "End Now, and evalution the model with test dataset" 
  6.     # print "mean accuracy: {0}".format(lr_model.score(self.test_set, self.test_tag)) 
  7.     y_pred = lr_model.predict(self.test_set) 
  8.     print classification_report(self.test_tag, y_pred) 
  9.     print confusion_matrix(self.test_tag, y_pred) 
  10.     print "save the trained model to lr_model.pl" 
  11.     joblib.dump(lr_model, self.data_path.replace("all.csv","bow_lr_model.pl"))   

TF-IDF

TF-IDF和Bow的操作十分類似,只是在向量化使使用tf-idf的方法:

  1. def vec(self): 
  2.     """ vec: get a vec representation of bow 
  3.     ""
  4.     self.__get_all_tokens() 
  5.     print "before filter, the tokens len: {0}".format(self.dictionary.__len__()) 
  6.     vectorizer = CountVectorizer(min_df=1e-5) 
  7.     transformer = TfidfTransformer() 
  8.     # sparse matrix 
  9.     self.tfidf = transformer.fit_transform(vectorizer.fit_transform(self.corpus)) 
  10.     words = vectorizer.get_feature_names() 
  11.     print "word len: {0}".format(len(words)) 
  12.     # print self.tfidf[0] 
  13.     print "tfidf shape ({0},{1})".format(self.tfidf.shape[0], self.tfidf.shape[1]) 
  14.  
  15.     # write the tfidf vec into a file 
  16.     tfidf_vec_file = open(self.data_path.replace("all.csv","tfidf_vec.pl"), 'wb'
  17.     pickle.dump(self.tfidf,tfidf_vec_file) 
  18.     tfidf_vec_file.close() 
  19.     tfidf_label_file = open(self.data_path.replace("all.csv","tfidf_label.pl"), 'wb'
  20.     pickle.dump(self.labels,tfidf_label_file) 
  21.     tfidf_label_file.close()  

這兩類方法效果都不錯,都能達到98+%的準(zhǔn)確率。

CNN

語料處理的方法和傳統(tǒng)的差不多,分詞之后,使用pretrain 的word2vec,這里我遇到一個坑,我開始對我的分詞太自信了,***模型一直不能收斂,后來向我們組博士請教,極有可能是由于分詞的詞序列中很多在pretrained word2vec里面是不存在的,而我這部分直接丟棄了,所有可能存在問題,分詞添加了詞典,然后,對于pre-trained word2vec不存在的詞做了一個隨機初始化,然后就能收斂了,學(xué)習(xí)了!!!

載入word2vec模型和構(gòu)建cnn網(wǎng)絡(luò)代碼如下(增加了一些bn和dropout的手段):

  1. def gen_embedding_matrix(self, load4file=True): 
  2.     """ gen_embedding_matrix: generate the embedding matrix 
  3.     ""
  4.     if load4file: 
  5.         self.__get_all_tokens_v2() 
  6.     else
  7.         self.__get_all_tokens() 
  8.     print "before filter, the tokens len: {0}".format( 
  9.         self.dictionary.__len__()) 
  10.     self.__filter_tokens() 
  11.     print "after filter, the tokens len: {0}".format( 
  12.         self.dictionary.__len__()) 
  13.     self.sequence = [] 
  14.     for file_token in self.corpus: 
  15.         temp_sequence = [x for x, y in self.dictionary.doc2bow(file_token)] 
  16.         print temp_sequence 
  17.         self.sequence.append(temp_sequence) 
  18.  
  19.     self.corpus_size = len(self.dictionary.token2id) 
  20.     self.embedding_matrix = np.zeros((self.corpus_size, EMBEDDING_DIM)) 
  21.     print "corpus size: {0}".format(len(self.dictionary.token2id)) 
  22.     for key, v in self.dictionary.token2id.items(): 
  23.         key_vec = self.w2vec.get(key
  24.         if key_vec is not None: 
  25.             self.embedding_matrix[v] = key_vec 
  26.         else
  27.             self.embedding_matrix[v] = np.random.rand(EMBEDDING_DIM) - 0.5 
  28.     print "embedding_matrix len {0}".format(len(self.embedding_matrix)) 
  29.  
  30. def __build_network(self): 
  31.     embedding_layer = Embedding( 
  32.         self.corpus_size, 
  33.         EMBEDDING_DIM, 
  34.         weights=[self.embedding_matrix], 
  35.         input_length=MAX_SEQUENCE_LENGTH, 
  36.         trainable=False
  37.     # train a 1D convnet with global maxpooling 
  38.     sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH, ), dtype='int32'
  39.     embedded_sequences = embedding_layer(sequence_input) 
  40.     x = Convolution1D(128, 5)(embedded_sequences) 
  41.     x = BatchNormalization()(x) 
  42.     x = Activation('relu')(x) 
  43.     x = MaxPooling1D(5)(x) 
  44.     x = Convolution1D(128, 5)(x) 
  45.     x = BatchNormalization()(x) 
  46.     x = Activation('relu')(x) 
  47.     x = MaxPooling1D(5)(x) 
  48.     print "before 256", x.get_shape() 
  49.     x = Convolution1D(128, 5)(x) 
  50.     x = BatchNormalization()(x) 
  51.     x = Activation('relu')(x) 
  52.     x = MaxPooling1D(15)(x) 
  53.     x = Flatten()(x) 
  54.  
  55.     x = Dense(128)(x) 
  56.     x = BatchNormalization()(x) 
  57.     x = Activation('relu')(x) 
  58.     x = Dropout(0.5)(x) 
  59.     print x.get_shape() 
  60.     preds = Dense(self.class_num, activation='softmax')(x) 
  61.     print preds.get_shape() 
  62.     adam = Adam(lr=0.0001) 
  63.     self.model = Model(sequence_input, preds) 
  64.     self.model.compile( 
  65.         loss='categorical_crossentropy', optimizer=adam, metrics=['acc']) 

 

另外一種網(wǎng)絡(luò)結(jié)構(gòu),韓國人那篇文章,網(wǎng)絡(luò)構(gòu)造如下:

  1. def __build_network(self): 
  2.     embedding_layer = Embedding( 
  3.         self.corpus_size, 
  4.         EMBEDDING_DIM, 
  5.         weights=[self.embedding_matrix], 
  6.         input_length=MAX_SEQUENCE_LENGTH, 
  7.         trainable=False
  8.     # train a 1D convnet with global maxpooling 
  9.     sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH, ), dtype='int32'
  10.     embedded_sequences = embedding_layer(sequence_input) 
  11.     conv_blocks = [] 
  12.     for sz in self.filter_sizes: 
  13.         conv = Convolution1D( 
  14.             self.num_filters, 
  15.             sz, 
  16.             activation="relu"
  17.             padding='valid'
  18.             strides=1)(embedded_sequences) 
  19.         conv = MaxPooling1D(2)(conv) 
  20.         conv = Flatten()(conv) 
  21.         conv_blocks.append(conv) 
  22.     z = Merge( 
  23.         conv_blocks, 
  24.         mode='concat') if len(conv_blocks) > 1 else conv_blocks[0] 
  25.     z = Dropout(0.5)(z) 
  26.     z = Dense(self.hidden_dims, activation="relu")(z) 
  27.     preds = Dense(self.class_num, activation="softmax")(z) 
  28.     rmsprop = RMSprop(lr=0.001) 
  29.     self.model = Model(sequence_input, preds) 
  30.     self.model.compile( 
  31.         loss='categorical_crossentropy'
  32.         optimizer=rmsprop, 
  33.         metrics=['acc']) 

 

LSTM

由于我這邊的task是對文章進行分類,序列太長,直接接LSTM后直接爆內(nèi)存,所以我在文章序列直接,接了兩層Conv1D+MaxPool1D來提取維度較低的向量表示然后接入LSTM,網(wǎng)絡(luò)結(jié)構(gòu)代碼如下:

  1. def __build_network(self): 
  2.     embedding_layer = Embedding( 
  3.         self.corpus_size, 
  4.         EMBEDDING_DIM, 
  5.         weights=[self.embedding_matrix], 
  6.         input_length=MAX_SEQUENCE_LENGTH, 
  7.         trainable=False
  8.     # train a 1D convnet with global maxpooling 
  9.     sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH, ), dtype='int32'
  10.     embedded_sequences = embedding_layer(sequence_input) 
  11.     x = Convolution1D( 
  12.         self.num_filters, 5, activation="relu")(embedded_sequences) 
  13.     x = MaxPooling1D(5)(x) 
  14.     x = Convolution1D(self.num_filters, 5, activation="relu")(x) 
  15.     x = MaxPooling1D(5)(x) 
  16.     x = LSTM(64, dropout_W=0.2, dropout_U=0.2)(x) 
  17.     preds = Dense(self.class_num, activation='softmax')(x) 
  18.     print preds.get_shape() 
  19.     rmsprop = RMSprop(lr=0.01) 
  20.     self.model = Model(sequence_input, preds) 
  21.     self.model.compile( 
  22.         loss='categorical_crossentropy'
  23.         optimizer=rmsprop, 
  24.         metrics=['acc']) 

 

CNN 結(jié)果: 

 

C-LSTM 結(jié)果:

 

整個實驗的結(jié)果由于深度學(xué)習(xí)這部分都是在公司資源上跑的,沒有真正意義上地去做一些trick來調(diào)參來提高性能,這里所有的代碼的網(wǎng)絡(luò)配置包括參數(shù)都僅做參考,更深地工作需要耗費更多的時間來做參數(shù)的優(yōu)化。

PS: 這里發(fā)現(xiàn)了一個keras 1.2.2的bug, 在寫回調(diào)函數(shù)TensorBoard,當(dāng)histogram_freq=1時,顯卡占用明顯增多,M40的24g不夠用,個人感覺應(yīng)該是一個bug,但是考慮到1.2.2而非2.0,可能后面2.0都優(yōu)化了。

所有的代碼都在github上:tensorflow-101/nlp/text_classifier/scripts

總結(jié)和展望

在本文的實驗效果中,雖然基于深度學(xué)習(xí)的方法和傳統(tǒng)方法相比沒有什么優(yōu)勢,可能原因有幾個方面:

  • Pretrained Word2vec Model并沒有覆蓋新聞中切分出來的詞,而且比例還挺高,如果能用網(wǎng)絡(luò)新聞?wù)Z料訓(xùn)練出一個比較精準(zhǔn)的Pretrained Word2vec,效果應(yīng)該會有很大的提升;
  • 可以增加模型訓(xùn)練收斂的trick以及優(yōu)化器,看看是否有準(zhǔn)確率的提升;
  • 網(wǎng)絡(luò)模型參數(shù)到現(xiàn)在為止,沒有做過深的優(yōu)化。
責(zé)任編輯:龐桂玉 來源: 36大數(shù)據(jù)
相關(guān)推薦

2024-02-05 14:18:07

自然語言處理

2021-05-18 07:15:37

Python

2021-09-03 12:01:07

模型自然語言

2021-05-13 07:17:13

Snownlp自然語言處理庫

2020-04-24 10:53:08

自然語言處理NLP是人工智能

2023-05-24 16:13:31

ChatGPT神經(jīng)網(wǎng)絡(luò)

2021-05-17 09:00:00

自然語言人工智能技術(shù)

2017-10-19 17:05:58

深度學(xué)習(xí)自然語言

2024-04-24 11:38:46

語言模型NLP人工智能

2022-10-09 08:00:00

機器學(xué)習(xí)文本分類算法

2017-04-17 15:03:16

Python自然語言處理

2021-06-28 10:10:42

人工智能AI自然語言

2017-05-05 15:34:49

自然語言處理

2023-05-30 14:39:34

ChatGPT-4NLP

2020-02-25 12:00:53

自然語言開源工具

2020-02-25 23:28:50

工具代碼開發(fā)

2021-11-12 15:43:10

Python自然語言數(shù)據(jù)

2023-08-04 10:18:15

2023-03-22 08:00:00

2020-11-12 18:57:14

摘要PythonNLP
點贊
收藏

51CTO技術(shù)棧公眾號