中文文本分類——商品評論情感判別

目錄

1、數據集下載

2、載入數據,做預處理(分詞),切分訓練集與測試集

3、計算訓練集和測試集每條評論數據的向量並存入文件

4、獲得訓練集向量和標籤,測試集向量和標籤

5、訓練SVM模型

6、構建待遇測句子的向量

7、對單個句子進行情感判斷


1、數據集下載

商品(書籍、酒店、計算機、牛奶、手機、熱水器)等評論數據

from sklearn.model_selection import train_test_split
from gensim.models.word2vec import Word2Vec
import numpy as np
import pandas as pd
import jieba
from sklearn.externals import joblib
from sklearn.svm import SVC

2、載入數據,做預處理(分詞),切分訓練集與測試集

#載入數據,做預處理(分詞),切分訓練集與測試集
def load_file_and_preprocessing():
    neg=pd.read_excel('chinese_data/neg.xls',header=None,index=None)
    pos=pd.read_excel('chinese_data/pos.xls',header=None,index=None)
    cw=lambda x:list(jieba.cut(x))
    pos['words']=pos[0].apply(cw)
    neg['words']=neg[0].apply(cw)
    # use 1 for positive sentiment,0 for negative
    y=np.concatenate((np.ones(len(pos)),np.zeros(len(neg))))
    #訓練集:測試集=8:2
    x_train,x_test,y_train,y_test=train_test_split(np.concatenate((pos['words'],neg['words'])),y,test_size=0.2)

    #NumPy提供了多種文件操作函數方便存取數組內容(npy格式以二進制存儲數據的)
    np.save('pre_data/y_train.npy',y_train)
    np.save('pre_data/y_test.npy',y_test)
    return x_train,x_test

3、計算訓練集和測試集每條評論數據的向量並存入文件

#對每個句子的所有詞向量取均值,來生成一個句子的vector
def build_sentence_vector(text,size,w2v_model):
    vec=np.zeros(size).reshape((1,size))
    count=0
    for word in text:
        try:
            vec+=w2v_model[word].reshape((1,size))
            count+=1
        except KeyError:
            continue
    if count!=0:
        vec/=count
    return vec

#計算詞向量
def get_train_vecs(x_train,x_test):
    n_dim=300 #詞向量維度
    #試用Word2Vec建立詞向量模型
    w2v_model=Word2Vec(size=n_dim,window=5,sg=0,hs=0,negative=5,min_count=10)
    w2v_model.build_vocab(x_train) #準備模型詞彙表
    #在評論訓練集上建模
    w2v_model.train(x_train,total_examples=w2v_model.corpus_count,epochs=w2v_model.iter) #訓練詞向量

    #訓練集評論向量集合
    train_vecs=np.concatenate([build_sentence_vector(z,n_dim,w2v_model) for z in x_train])
    np.save('pre_data/train_vecs.npy',train_vecs) #將訓練集保存到文件中
    print(train_vecs.shape)  #輸出訓練集的維度

    #在測試集上訓練
    w2v_model.train(x_test,total_examples=w2v_model.corpus_count,epochs=w2v_model.iter)
    w2v_model.save('pre_data/w2v_model/w2v_model.pkl')
    test_vecs=np.concatenate([build_sentence_vector(z,n_dim,w2v_model) for z in x_test])
    np.save('pre_data/test_vecs.npy',test_vecs)
    print(test_vecs.shape)

4、獲得訓練集向量和標籤,測試集向量和標籤

#獲得訓練集向量和標籤,測試集向量和標籤
def get_data():
    train_vecs=np.load('pre_data/train_vecs.npy')
    y_train=np.load('pre_data/y_train.npy')
    test_vecs=np.load('pre_data/test_vecs.npy')
    y_test=np.load('pre_data/y_test.npy')
    return train_vecs,y_train,test_vecs,y_test

5、訓練SVM模型

#訓練SVM模型
def svm_train(train_vecs,y_train,test_vecs,y_test):
    clf=SVC(kernel='rbf',verbose=True)
    clf.fit(train_vecs,y_train)   #根據給定的訓練數據擬合SVM模型
    joblib.dump(clf,'pre_data/svm_model/model.pkl')  #保存訓練好的SVM模型
    print(clf.score(test_vecs,y_test))   #輸出測試數據的平均準確度

6、構建待遇測句子的向量

#構建待遇測句子的向量
def get_predict_vecs(words):
    n_dim=300
    w2v_model=Word2Vec.load('pre_data/w2v_model/w2v_model.pkl')
    train_vecs=build_sentence_vector(words,n_dim,w2v_model)
    return train_vecs

7、對單個句子進行情感判斷

#對單個句子進行情感判斷
def svm_predict(string):
    words=jieba.lcut(string)
    words_vecs=get_predict_vecs(words)
    clf=joblib.load('pre_data/svm_model/model.pkl')
    result=clf.predict(words_vecs)

    if int(result[0])==1:
        print(string,'positive')
    else:
        print(string,'negative')
if __name__=='__main__':
    #x_train, x_test=load_file_and_preprocessing()
    #get_train_vecs(x_train, x_test)

    #train_vecs, y_train, test_vecs, y_test=get_data()
    #svm_train(train_vecs, y_train, test_vecs, y_test)

    #對輸入句子情感進行判斷
    string='電池充完了電連手機都打不開,簡直爛的要命,真是金玉其外,敗絮其中!連5號電池都不如'
    #string='牛逼的手機,從3米高的地方摔下去都沒壞,質量非常好'
    #string='這款電腦感覺還行,能用,先試用一下,應該不錯'
    svm_predict(string)

 

 

中文自然語言處理流程

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章