xgboost的使用簡析

來源:互聯網
上載者:User

前言——記得在阿里實習的時候,大家都是用mllib下的GBDT來train model的。但由於mllib不是開源的,所以在公司外是不能夠使用。後來參加kaggle比賽的時候,認識到一個GDBT好用的工具,xgboost,所以就認真地學習了一下。


github地址:https://github.com/dmlc/xgboost

具體使用方式,其實裡面都有說明的,下面主要講講在windows下python環境怎樣使用xgboost。


1、按照官方說明來下載並編譯release版64位程式,並執行“python setup.py install”。

2、在python代碼中添加環境路徑“sys.path.append('C:\\.........\\xgboost-master\\wrapper')”(註:該路徑為你下載解壓出來的檔案夾wrapper路徑)

3、這樣就可以嘗試“import xgboost as xgb”了,如果成功就沒問題了。(註:要依賴numpy以及scipy,且安裝位元要跟你Python位元一致,64位版numpy以及scipy要到這裡下載,32位版就可以到官網下載)


下面貼個train的代碼以及predict的代碼:

train:

#!/usr/bin/pythonimport sys,ossys.path.append('C:\\xgboost-master\\wrapper')import numpy as npimport scipy.sparseimport xgboost as xgb### simple example# load file from text file, also binary buffer generated by xgboostdtrain = xgb.DMatrix('C:\\PredictAHE_Trainset_libsvmFormat.txt')dtest = xgb.DMatrix('C:\\PredictAHE_Testset_libsvmFormat.txt')# specify parameters via map, definition are same as c++ versionparam = {'max_depth':6, 'eta':0.3, 'silent':1, 'objective':'binary:logistic' }# specify validations set to watch performancewatchlist  = [(dtest,'eval'), (dtrain,'train')]num_round = 20bst = xgb.train(param, dtrain, num_round, watchlist)# this is predictionpreds = bst.predict(dtest)labels = dtest.get_label()print ('error=%f' % (  sum(1 for i in range(len(preds)) if int(preds[i]>0.5)!=labels[i]) /float(len(preds))))bst.save_model('C:\\xgb.model')


predict:

#!/usr/bin/pythonimport sys,ossys.path.append('C:\\xgboost-master\\wrapper')import numpy as npimport scipy.sparseimport xgboost as xgb### simple example# load file from text file, also binary buffer generated by xgboostdtest2 = xgb.DMatrix('C:\\PredictAHE_Temp_libsvmFormat.txt')# load model and data inbst2 = xgb.Booster(model_file='C:\\xgb.model')preds2 = bst2.predict(dtest2)# this is predictionouting = open('C:\\PredictAHE_Temp_Result.txt', 'w')outing.write(str(int(preds2[0]>0.5))) #只輸出了一個outing.close()

P.S.輸入的檔案格式要是 libsvm格式




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.