机器学习(十九)— xgboost初试kaggle
1、官网下载kaggle数据集Homesite Competition数据集,文件结构大致如下:

2、代码实战
#Parameter grid search with xgboost
#feature engineering is not so useful and the LB is so overfitted/underfitted
#so it is good to trust your CV #go xgboost, go mxnet, go DMLC! http://dmlc.ml #Credit to Shize's R code and the python re-implementation import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn import preprocessing
from sklearn.cross_validation import train_test_split from sklearn.cross_validation import *
from sklearn.grid_search import GridSearchCV train = pd.read_csv("input/train.csv")[:1000]
test = pd.read_csv("input/test.csv")[:100] #去掉无意义的feature
train = train.drop('QuoteNumber', axis=1)
test = test.drop('QuoteNumber', axis=1) # Lets play with some dates
#转换feature到更有物理含义的格式
train['Date'] = pd.to_datetime(pd.Series(train['Original_Quote_Date']))
train = train.drop('Original_Quote_Date', axis=1) test['Date'] = pd.to_datetime(pd.Series(test['Original_Quote_Date']))
test = test.drop('Original_Quote_Date', axis=1) #如果我们将 datetime 转为年月日,则为物理含义更好的 feature:
train['Year'] = train['Date'].apply(lambda x: int(str(x)[:4]))
train['Month'] = train['Date'].apply(lambda x: int(str(x)[5:7]))
train['weekday'] = train['Date'].dt.dayofweek
#
test['Year'] = test['Date'].apply(lambda x: int(str(x)[:4]))
test['Month'] = test['Date'].apply(lambda x: int(str(x)[5:7]))
test['weekday'] = test['Date'].dt.dayofweek train = train.drop('Date', axis=1)
test = test.drop('Date', axis=1) #fill -999 to NAs
#这里先简单处理一下,把所有缺失值填上一个不太可能出现的取值:
train = train.fillna(-999)
test = test.fillna(-999) features = list(train.columns[1:]) #la colonne 0 est le quote_conversionflag
print(features) #对类别性质的feature做LabelEncode
#现实数据中很多特征并不是数值类型,而是类别类型,
#比如红色/蓝色/白色之类,虽然决策树天然擅长处理类别类型的特征,
#但是还是需要我们把原始的字符串值转为类别编号。
for f in train.columns:
if train[f].dtype=='object':
print(f)
lbl = preprocessing.LabelEncoder()
# lbl.fit(list(train[f].values))
lbl.fit(list(train[f].values) + list(test[f].values))
train[f] = lbl.transform(list(train[f].values))
test[f] = lbl.transform(list(test[f].values)) xgb_model = xgb.XGBClassifier() #brute force scan for all parameters, here are the tricks
#usually max_depth is 6,7,8
#learning rate is around 0.05, but small changes may make big diff
#tuning min_child_weight subsample colsample_bytree can have
#much fun of fighting against overfit
#n_estimators is how many round of boosting
#finally, ensemble xgboost with multiple seeds may reduce variance
parameters = {'nthread':[4], #when use hyperthread, xgboost may become slower
'objective':['binary:logistic'],
'learning_rate': [0.05], #so called `eta` value
'max_depth': [6],
'min_child_weight': [11],
'silent': [1],
'subsample': [0.8],
'colsample_bytree': [0.7],
'n_estimators': [5], #number of trees, change it to 1000 for better results
'missing':[-999],
'seed': [1337]} #使用 CV (cross validation) 做 xgb 分类器模型的调参
clf = GridSearchCV(xgb_model, parameters, n_jobs=5,
cv=StratifiedKFold(train['QuoteConversion_Flag'], n_folds=5, shuffle=True),
scoring='roc_auc',
verbose=2, refit=True) clf.fit(train[features], train["QuoteConversion_Flag"]) #trust your CV!
best_parameters, score, _ = max(clf.grid_scores_, key=lambda x: x[1])
print('Raw AUC score:', score)
for param_name in sorted(best_parameters.keys()):
print("%s: %r" % (param_name, best_parameters[param_name])) test_probs = clf.predict_proba(test[features])[:,1] sample = pd.read_csv('input/sample_submission.csv')
sample.QuoteConversion_Flag = test_probs
sample.to_csv("xgboost_best_parameter_submission.csv", index=False)
机器学习(十九)— xgboost初试kaggle的更多相关文章
- 剑指Offer(十九):顺时针打印矩阵
剑指Offer(十九):顺时针打印矩阵 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/baid ...
- 剑指Offer(二十九):最小的K个数
剑指Offer(二十九):最小的K个数 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net/baid ...
- Alink漫谈(十九) :源码解析 之 分位点离散化Quantile
Alink漫谈(十九) :源码解析 之 分位点离散化Quantile 目录 Alink漫谈(十九) :源码解析 之 分位点离散化Quantile 0x00 摘要 0x01 背景概念 1.1 离散化 1 ...
- 无废话ExtJs 入门教程十九[API的使用]
无废话ExtJs 入门教程十九[API的使用] extjs技术交流,欢迎加群(201926085) 首先解释什么是 API 来自百度百科的官方解释:API(Application Programmin ...
- Python之路【第十九章】:Django进阶
Django路由规则 1.基于正则的URL 在templates目录下创建index.html.detail.html文件 <!DOCTYPE html> <html lang=&q ...
- Bootstrap <基础二十九>面板(Panels)
Bootstrap 面板(Panels).面板组件用于把 DOM 组件插入到一个盒子中.创建一个基本的面板,只需要向 <div> 元素添加 class .panel 和 class .pa ...
- Bootstrap <基础十九>分页
Bootstrap 支持的分页特性.分页(Pagination),是一种无序列表,Bootstrap 像处理其他界面元素一样处理分页. 分页(Pagination) 下表列出了 Bootstrap 提 ...
- Web 开发人员和设计师必读文章推荐【系列二十九】
<Web 前端开发精华文章推荐>2014年第8期(总第29期)和大家见面了.梦想天空博客关注 前端开发 技术,分享各类能够提升网站用户体验的优秀 jQuery 插件,展示前沿的 HTML5 ...
- Web 前端开发精华文章集锦(jQuery、HTML5、CSS3)【系列十九】
<Web 前端开发精华文章推荐>2013年第七期(总第十九期)和大家见面了.梦想天空博客关注 前端开发 技术,分享各种增强网站用户体验的 jQuery 插件,展示前沿的 HTML5 和 C ...
随机推荐
- 【边做项目边学Android】小白会遇到的问题--Appcompat_V7问题
问题描写叙述: 首先遇到的问题就是adt版本号的选择,sdk版本号的选择: adt按非小白朋友说的选了最新的ADT-22.3.0,同一时候我也把sdk更新到了最新的(嗯.这个要fanqiang,或者找 ...
- 在mac上独立安装PHP环境
1.http://dditblog.com/blog_418.html 2.http://www.jianshu.com/p/0456dd3cc78b
- 安卓编译出错: Process 'command 'C:\Java\jdk1.8.0_51\bin\java.exe'' finished with non-zero exit value 1 解决!
安卓编译出错: Process 'command 'C:\Java\jdk1.8.0_51\bin\java.exe'' finished with non-zero exit value 1 解决! ...
- 解决xcode5升级后,Undefined symbols for architecture arm64:问题
The issue is that the cocoapods have not been built for arm64 architecture yet thus they cannot be l ...
- Nearest Common Ancestors(LCA)
Description A rooted tree is a well-known data structure in computer science and engineering. An exa ...
- Boxes and Candies(贪心)
Boxes and Candies Time limit : 2sec / Memory limit : 256MB Score : 300 points Problem Statement Ther ...
- [转]React表单无法输入原因----约束性和非约束性组件
转自:http://blog.csdn.net/lihongxun945/article/details/46730835 表单是前端非常重要的一块内容,并且往往包含了错误校验等逻辑. React对表 ...
- python查询IP地址所属地
1.linux命令行版 #!/usr/bin/python #-*- coding: utf-8 -*- import json import urllib import sys def get_da ...
- react-native 使用 antd-mobile-rn UI进行开发app
1.创建 react-native 项目 react-native init app03 2.安装组件 npm install antd-mobile-rn --save 3.配置按需加载 npm i ...
- 我的Android进阶之旅------>Android关于TextWatcher的初步了解
首先来看一下TextWatcher的源代码 package android.text; /** * When an object of a type is attached to an Editabl ...