文本分類的python實現-基於Xgboost演算法

來源:互聯網
上載者:User
描述 訓練集為評論文本,標籤為 pos,neu,neg三種分類,train.csv的第一列為文本content,第二列為label。 python的xgboost包安裝方法,網上有很多詳細的介紹 參數

XGBoost的作者把所有的參數分成了三類:1、通用參數:宏觀函數控制。2、Booster參數:控制每一步的booster。3、學習目標參數:控制訓練目標的表現。

1。通用參數: booster[預設gbtree]:gbtree:基於樹的模型、gbliner:線性模型 silent[預設0]:值為1時,靜默模式開啟,不會輸出任何資訊 nthread[預設值為最大可能的線程數]:這個參數用來進行多線程式控制制,應當輸入系統的核心數。 如果你希望使用CPU全部的核,那就不要輸入這個參數,演算法會自動檢測它

2。Booster參數:

這裡只介紹tree booster,因為它的表現遠遠勝過linear booster,所以linear booster很少用到 eta[預設0.3]:和GBM中的 learning rate 參數類似。 通過減少每一步的權重,可以提高模型的魯棒性。常用的值為0.2, 0.3 max_depth[預設6]:這個值為樹的最大深度。max_depth越大,模型會學到更具體更局部的樣本。常用的值為6 gamma[預設0]:Gamma指定了節點分裂所需的最小損失函數下降值。 這個參數的值越大,演算法越保守。這個參數的值和損失函數息息相關。 subsample[預設1]:這個參數控制對於每棵樹,隨機採樣的比例。 減小這個參數的值,演算法會更加保守,避免過擬合。但是,如果這個值設定得過小,它可能會導致欠擬合。 常用的值:0.7-1 colsample_bytree[預設1]:用來控制每棵隨機採樣的列數的佔比(每一列是一個特徵)。 常用的值:0.7-1

3。學習目標參數 objective[預設reg:linear]:這個參數定義需要被最小化的損失函數。binary:logistic二分類的羅吉斯迴歸,返回預測的機率。multi:softmax 使用softmax的多分類器,返回預測的類別。這種情況下,還需要多設一個參數:num_class(類別數目)。 multi:softprob 和multi:softmax參數一樣,但是返回的是每個資料屬於各個類別的機率。 eval_metric[預設值取決於objective參數的取值]:對於有效資料的度量方法。 對於迴歸問題,預設值是rmse,對於分類問題,預設值是error。其他的值:rmse 均方根誤差; mae 平均絕對誤差;logloss 負對數似然函數值;error 二分類錯誤率(閾值為0.5); merror 多分類錯誤率;mlogloss 多分類logloss損失函數;auc 曲線下面積。 seed[預設0]:隨機數的種子 設定它可以複現隨機資料的結果。 實驗

代碼

# -*- coding: utf-8 -*-import xgboost as xgbimport csvimport jiebajieba.load_userdict('wordDict.txt')import numpy as npfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformer# 讀取訓練集def readtrain():    with open('Train.csv', 'rb') as csvfile:        reader = csv.reader(csvfile)        column1 = [row for row in reader]    content_train = [i[1] for i in column1[1:]] # 第一列為常值內容,並去除列名    opinion_train = [i[2] for i in column1[1:]] # 第二列為類別,並去除列名    print '訓練集有 %s 條句子' % len(content_train)    train = [content_train, opinion_train]    return train# 將utf8的列錶轉換成unicodedef changeListCode(b):    a = []    for i in b:        a.append(i.decode('utf8'))    return a# 對列表進行分詞並用空格串連def segmentWord(cont):    c = []    for i in cont:        a = list(jieba.cut(i))        b = " ".join(a)        c.append(b)    return c# 類別用數字表示:pos:2,neu:1,neg:0def transLabel(labels):    for i in range(len(labels)):        if labels[i] == 'pos':            labels[i] = 2        elif labels[i] == 'neu':            labels[i] = 1        elif labels[i] == 'neg':            labels[i] = 0        else: print "label無效:",labels[i]    return labelstrain = readtrain()content = segmentWord(train[0])opinion = transLabel(train[1])  # 需要用數字表示類別opinion = np.array(opinion)     # 需要numpy格式train_content = content[:7000]train_opinion = opinion[:7000]test_content = content[7000:]test_opinion = opinion[7000:]vectorizer = CountVectorizer()tfidftransformer = TfidfTransformer()tfidf = tfidftransformer.fit_transform(vectorizer.fit_transform(train_content))weight = tfidf.toarray()print tfidf.shapetest_tfidf = tfidftransformer.transform(vectorizer.transform(test_content))test_weight = test_tfidf.toarray()print test_weight.shapedtrain = xgb.DMatrix(weight, label=train_opinion)dtest = xgb.DMatrix(test_weight, label=test_opinion)  # label可以不要,此處需要是為了測試效果param = {'max_depth':6, 'eta':0.5, 'eval_metric':'merror', 'silent':1, 'objective':'multi:softmax', 'num_class':3}  # 參數evallist  = [(dtrain,'train'), (dtest,'test')]  # 這步可以不要,用於測試效果num_round = 50  # 迴圈次數bst = xgb.train(param, dtrain, num_round, evallist)preds = bst.predict(dtest)

輸出

Building prefix dict from the default dictionary ...Loading model from cache c:\users\www\appdata\local\temp\jieba.cacheLoading model cost 0.366 seconds.Prefix dict has been built succesfully.訓練集有 10981 條句子(7000, 14758)(3981L, 14758L)[0] train-merror:0.337857   test-merror:0.409194[1] train-merror:0.322000   test-merror:0.401658[2] train-merror:0.312429   test-merror:0.401909[3] train-merror:0.300857   test-merror:0.387340[4] train-merror:0.293143   test-merror:0.389601[5] train-merror:0.286286   test-merror:0.390857[6] train-merror:0.279000   test-merror:0.388847[7] train-merror:0.270571   test-merror:0.387340[8] train-merror:0.263857   test-merror:0.379804[9] train-merror:0.257286   test-merror:0.376036[10]    train-merror:0.248000   test-merror:0.374278[11]    train-merror:0.241857   test-merror:0.371012[12]    train-merror:0.237000   test-merror:0.369254[13]    train-merror:0.231571   test-merror:0.366491[14]    train-merror:0.225857   test-merror:0.365737[15]    train-merror:0.220286   test-merror:0.365988[16]    train-merror:0.216286   test-merror:0.364732[17]    train-merror:0.212286   test-merror:0.360462[18]    train-merror:0.210143   test-merror:0.357699[19]    train-merror:0.205143   test-merror:0.356694[20]    train-merror:0.202286   test-merror:0.357699[21]    train-merror:0.198571   test-merror:0.358201[22]    train-merror:0.195429   test-merror:0.356443[23]    train-merror:0.192143   test-merror:0.358955[24]    train-merror:0.189286   test-merror:0.358955[25]    train-merror:0.186571   test-merror:0.354936[26]    train-merror:0.183429   test-merror:0.353680[27]    train-merror:0.181714   test-merror:0.353429[28]    train-merror:0.178286   test-merror:0.353680[29]    train-merror:0.174143   test-merror:0.352675[30]    train-merror:0.172286   test-merror:0.352675[31]    train-merror:0.171286   test-merror:0.353680[32]    train-merror:0.168857   test-merror:0.354434[33]    train-merror:0.167429   test-merror:0.352675[34]    train-merror:0.164286   test-merror:0.350917[35]    train-merror:0.160714   test-merror:0.348907[36]    train-merror:0.159000   test-merror:0.346898[37]    train-merror:0.157571   test-merror:0.346395[38]    train-merror:0.156286   test-merror:0.347400[39]    train-merror:0.154571   test-merror:0.346647[40]    train-merror:0.153714   test-merror:0.345642[41]    train-merror:0.152857   test-merror:0.346647[42]    train-merror:0.150000   test-merror:0.345391[43]    train-merror:0.148143   test-merror:0.345893[44]    train-merror:0.145857   test-merror:0.344135[45]    train-merror:0.144000   test-merror:0.341874[46]    train-merror:0.143000   test-merror:0.342879[47]    train-merror:0.142714   test-merror:0.341874[48]    train-merror:0.141714   test-merror:0.341372[49]    train-merror:0.138286   test-merror:0.339362

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.