数据挖掘(pandas&xgboost)

来源:互联网 发布:恒大淘宝 法律意见书 编辑:程序博客网 时间:2024/06/05 23:07

类别特征处理

1、利用pd.get_dummies方法将类别特征进行编码。使用get_dummies进行one-hot编码(查看时间字段的类型,如果不是datetime类型需要to_datetime转化)

例如:下面代码实现对age字段的转化,其中convert_age为转化函数,将对应的age、sex、user_lv进行one-hot编码,并concat一起,dump保存。

user['age'].map(convert_age)age_df= pd.get_dummies(user["age"], prefix="age")user = pd.concat([user['user_id'], age_df, sex_df, user_lv_df], axis=1)pickle.dump(user, open(dump_path, 'w'))

load()方法的作用正好与上面的dump()方法相反,上面是序列化数据,这个方法作用是反序列化。

user = pickle.load(open(dump_path))

使用具体示例:加载数据(cache缓存,提高使用性能)

if os.path.exists(cache_file):    datas = pickle.load(open(cache_file))else:    datas = pd.read_csv(data_file, index_col=0)    pickle.dump(datas, open(cache_file, 'w'))return datas

2、特征提取,过滤的话,pandas的方式特别灵活
// 实际的场景翻译:获取未来N天的用户行为(转化为具体的某段时间actions.time >= start_date) & (actions.time < end_date))

get_actions===pd.read_csv====pd.concat([action_1, action_2, action_3])====filter(actions[(actions.time >= start_date) & (actions.time < end_date)])

3、滑动窗口特征

3.1统计距离预测开始日期前1、2、3、5、7、10、15、21、30的行为累积(方法:利用总之时间减去前i天的时间,得到当天的时间,然后将提取的特征按照 user_id 和 sku_id 进行合并,即预测的是。。具体的时间区间下的用户的行为)

start_days = datetime.strptime(train_end_date, '%Y-%m-%d') - timedelta(days=i)start_days = start_days.strftime('%Y-%m-%d')pd.merge(actions, get_action_feat(start_days, train_end_date), how='left',on=['user_id', 'sku_id'])

3.2 统计时间区间内行为累积(方法:将需要赖以支持group的id提取出来,然后concat处理,最后进行依赖取sum()求和)

// 获取一定时间段内所要预测的目标,其中type字段为label。

filter(actions[['user_id', 'sku_id', 'type']])===df = pd.get_dummies(actions['type'], prefix='%s-%s-action' % (start_date, end_date))===pd.concat([actions, df], axis=1)===actions.groupby(['user_id', 'sku_id'], as_index=False).sum()

4、xgboost模型(代码都差不多)

// //生成可训练的数据集和测试集train_start_date: 训练集开始时间user_index, training_data, label = make_train_set(train_start_date, train_end_date, test_start_date, test_end_date)train_test_split(training_data.values, label.values, test_size=0.2, random_state=0)dtrain=xgb.DMatrix(X_train, label=y_train)dtest=xgb.DMatrix(X_test, label=y_test)//这里做相应的调参处理param = {'max_depth': 6, 'eta': 0.05, 'silent': 1, 'objective': 'binary:logistic'}num_round = 309param['nthread'] = 4plst = param.items()plst += [('eval_metric', 'logloss')]evallist = [(dtest, 'eval'), (dtrain, 'train')]//xgboost训练bst=xgb.train(plst, dtrain, num_round, evallist)sub_user_index, sub_trainning_data = make_test_set(sub_start_date, sub_end_date,)sub_trainning_data = xgb.DMatrix(sub_trainning_data.values)y = bst.predict(sub_trainning_data)// 回归预测xgboostXGBRegressor(max_depth = 2,learning_rate=0.01,n_estimators=500,reg_alpha=10,gamma = 1)XGBR.fit(X,Y)from sklearn.ensembleXGBRegressor(loss='lad', alpha=0.95,n_estimators=500, max_depth=3,learning_rate=.1 )// 函数学习:labels = actions['label'].copy()fillna(填充)median(中位数)、mean(平均数)等参数axis

5、代码分析
5.1 生成精简版本user_pay, uer_view 表格
data_new/table_regenerate.py
按小时统计商户销量,并进行用户异常刷单清理,生成精简版本的pay和view表格分别为,user_pay_new.csv 和 user_view_new.csv,文件大小减小为之前的1/10已便后续访问及特征提取。

百度知道:

read_csvheader=None 第0行不作为列名;names=['']  指定列名;因为你的输入数据列有混合类型,而PANDAS默认要找到可以使所占用空间最小的类型来储存你的数据。low_memory设置为false之后,pandas就不进行寻找,直接采用较大的数据类型来储存。时间处理:pd.to_datetime。.dt.date。.dt.hour。。.dt.dayofweek按小时统计商户销量:user_pay_new = user_pay.groupby(by =['USER_ID','SHOP_ID','DATE','HOUR'],as_index = False).count()。。.sum()

5.2 外部数据爬取
additional/Weather_underground_day.py
从https://www.wunderground.com 按天读取机场所在地信息,爬取信息包含7列分别为[Port, Date, Precip , Rise_act, Rise_cil, Set_act, Set_cil],对应内容为[机场代号,日期,降水量,真实日出时间,修正日出时间,真实日落时间,修正日落时间]。

爬虫:soup = BeautifulSoup(thepage, "html.parser")==thepage = urllib.request.urlopen(theurl)soup_detail = soup.find_all('tr')soup_detail_ast=soup.find_all('div',{"class":"wx-module simple","id":"astronomy-mod"})[0]Rise_act.append(soup_detail_ast.find_all('td')[1].text.strip())
最后:Port = pd.DataFrame(Port, columns=['Port'])//将list类型的Port转为DataFrame类型sub_result = pd.concat([Port,Date,Precip, Rise_act,Rise_cil,Set_act,Set_cil  ], axis = 1)//Port,并行得到file_name = 'PORT_precip'+value.AIRPORT_CODE +'.csv'sub_result.to_csv(file_name,index = False)

additional/Weather_underground_hour.py
从https://www.wunderground.com 按小时读取机场所在地信息,爬取信息包含14列分别为[Port, Date, Time, Temp, Bodytemp, Dew, Humidity, Pressure, Visibility, Wind_dir, Wind_speed, Gust_speed, Event, Condition],对应内容为[机场代号,日期,时间,气温,体感温度,露点,湿度,压力,能见度,风向,风速,阵风强度,气象事件,气象条件]。

5.3特征生成
feature/ WEATHER_FEATURES.py
生成天气特征表 WEATHER_FEATURES.csv,包含四项,分别为人体舒适度SSH值,SSH值日增量,降水指数,天晴指数。

这个提供了一个思路,直接加入pathsys.path.append('../TOOLS')from IJCAI2017_TOOL import *

feature/ SHOP_FEATURES.py
生成商家特征表SHOP_FEATURES.csv,包含平均View/Pay比值,平均每天开店时间,关店时间,开店总时长;首次营业日期,非节假日销量中位数,节假日销量中位数,节假日/非节假日销量比值;商家类别,人均消费,评分,评论数,门店等级。

feature/ TEST_SELLS.py
生成测试集历史过去三周销量表格,修正异常销量,以历史过去14天销量的 为限制,其中 为均值, 为均方根

feature/FEATURE_MERGE.py
整合所有特征,生成方便训练模型读取的X.csv, Y.csv, Xtest.csv三个表格

5.4常规销量模型训练
model/xgb_model1.py,model/xgb_model2.py,model/ GBDT_model.py

5.5双11修正系数训练
model/ DOU11_model.py
双11修正模型,获得双11当天销量增加百分比

百度知道:

loc——通过行标签索引行数据 iloc——通过行号索引行数据 ix——通过行标签或者行号索引行数据(基于loc和iloc 的混合) index行号 columns列号#生成一个数据框DataFrame#df.loc['a'](a是行号)#df.iloc[0]#df.ix[0] df.ix['a']都可以#df.loc[:,['c']] 这就是索引列数据#df.loc[:,'c':'d'] 索引多列数据//PivotTable(透视表)参数1、index=["Name","Rep","Manager"]多个索引,values=["Price"](指定columns值)aggfunc=np.sum(对该列元素进行计数或求和)。。。。重点:这里区分values和columns聚合函数aggfunc最后是被应用到了变量“values”中你所列举的项目上。
//数据清洗:方式一.drop('Cabin',axis=1,inplace=True)  #inplace:是否将标准输出(print方法)的结果写回文件;
//数据清洗:方式二data.Age.fillna(data.Age.mean(),inplace=True)  #Age里的缺失值用Age的平均数填充  
//数据清洗:方式三使用最可能的值填充缺失值:可以用回归、使用贝叶斯形式化的基于推理的工具或决策树归纳确定。例如,利用数据集中其他顾客的属性,可以构造一棵决策树来预测income的缺失值。notnull=data[pd.notnull(data.Age)]  isnull=data[pd.isnull(data.Age)]  from sklearn.ensemble import GradientBoostingRegressor  G=GradientBoostingRegressor()  G.fit(notnull[col].values,notnull.Age)  isnull.Age=G.predict(isnull[col])  data.Age[pd.isnull(data.Age)]=isnull.Age 
//噪声数据处理方式一用箱边界光滑、用箱均值光滑c=[4,8,15,21,21,24,25,28,34]  c=pd.Series(c)  s=pd.qcut(c,[0,0.33,0.66,1])  pd.groupby(c,by=s).mean()  
//噪声数据处理方式二聚类:可以通过聚类检测离群点,将类似的值组织成群或簇。直观地,落在簇集合之外的值视为离群点。from sklearn.cluster import KMeans  c=[4,8,15,21,21,24,25,28,34]  K=KMeans(n_clusters=3)  import numpy as np  c=np.array(c)  c=c.reshape(9,1)  K.fit(c)  center=K.cluster_centers_  c=center[K.predict(c)]  print c  
//归一化线性归一化获取二维数组列方向的最大值:x.max(axis = 0)获取二维数组列方向的最小值:x.min(axis = 0)标准差归一化获取二维数组列方向的均值:x.mean(axis = 0)获取二维数组列方向的标准差:x.std(axis = 0) from sklearn import preprocessing import numpy as np X = np.array([[ 1., -1.,  2.],[ 2.,  0.,  0.],[ 0.,  1., -1.]]) X_scaled = preprocessing.scale(X)#处理后数据的均值和方差 X_scaled.mean(axis=0) X_scaled.std(axis=0) scaler = preprocessing.StandardScaler().fit(X) scaler.mean_   scaler.std_   scaler.transform(X)   scaler.transform([[-1.,  1., 0.]])   正则化(Normalization)X_normalized = preprocessing.normalize(X, norm='l2')
// 左右连接Join、取交集/并集(merge函数)默认是交集, inner连接 列名不同可以分别指定:on left_on right_on并集 how = 'outer'suffixes=('_dkdk','_djslsd')

6、可视化

窗口figure, 和一个tuple型的ax对象fig, ax = plt.subplots()函数名 功能  调用格式figure  创建一个显示窗口    plt.figure(num=1,figsize=(8,8)imshow  绘制图片    plt.imshow(image)show    显示窗口    plt.show()subplot 划分子图    plt.subplot(2,2,1)title   设置子图标题(与subplot结合使用)    plt.title('origin image')axis    是否显示坐标尺 plt.axis('off')subplots    创建带有多个子图的窗口 fig,axes=plt.subplots(2,2,figsize=(8,8))ravel   为每个子图设置变量   ax0,ax1,ax2,ax3=axes.ravel()set_title   设置子图标题(与axes结合使用)   ax0.set_title('first window')tight_layout    自动调整子图显示布局  plt.tight_layout()
// xgboost训练,这里参数xgb.XGBRegressor(max_depth = 2,learning_rate=0.01,n_estimators=500,reg_alpha=10,gamma = 1)(其中X,Y分别是Dataframe的values).fit(X,Y).predict(Xtest)matplotlib模板:fig, ax = plt.subplots()fig.patch.set_facecolor('white')font = {'family': 'serif',        'color':  'k',        'weight': 'normal',        'size': 20,        }plt.xlabel('ratio', fontdict=font)plt.hist(SHOP_INFO_EN2['DOU11'].values.reshape(-1),bins = np.linspace(0.8,1.3,21),alpha = 0.5)
阅读全文
0 0