2019KDD

本程序用于预测分类结果 分别输入pid_ture_profiles 和pid_ture_test_profiles

import time
import pandasas pd
import numpyas np
import warnings
import lightgbmas lgb
from sklearn.metricsimport mean_absolute_error, r2_score
from sklearn.model_selectionimport StratifiedKFold
import matplotlib.pyplotas plt
import matplotlibas mpl
import seabornas sb
import datetime
from sklearn.metricsimport precision_score
from sklearn.metricsimport recall_score
warnings.filterwarnings("ignore")
pd.set_option('display.max_columns', 10000)
pd.set_option('display.max_rows', 10000)
pd.set_option('max_colwidth', 50000)
pd.set_option('display.width',10000)
def ZQL(x,y):
data=pd.DataFrame()
data['x']=x
data['y']=y
aa=list(data['x']==data['y'])
precision=aa.count(True)/len(aa)
for iin range(0,12):
a=data[data['y']==i]
b=a['x']==a['y']
b=list(b)
# print(b.count(True)/len(b))
    print(precision)
def model_main1(train_data, test_data):
train_data=train_data.drop('click_time',axis=1)
param1 = {
'learning_rate':0.01,  # 学习速率# 0.05,0.1,0.15
        'boosting_type':'gbdt',  #
        'objective':'multiclass',
        'metric':'multi_logloss',
        'feature_fraction':0.65,  # 训练树之前选择特征的比例 [0.4,0.5,0.6,0.7,0.8]  深度5:0.6
        'bagging_fraction':0.8,  #  [0.6,0.7,0.8,0.9] 0.6  0.8  [0.06387005830920574, 0.0638548860912314, 0.0638610192087074, 0.06385078605195317]

        'bagging_freq:2,  # 套袋频率

        'num_leaves'50,  #  一棵树的最大叶数[25,35,45,55]  45 [0.06385057088135324, 0.0638610192087074, 0.0638610192087074, 0.0638610192087074]  31 32
        'max_depth': -1,
        'lambda_l2':5,  #  [0.1,1,5,10] [0.06387748918661836, 0.06385215918644115, 0.0638849241808266, 0.06388601729372406]
        'lambda_l1':0001,  # [0.0001,0.001,0.01]: 0.001
        'num_threads: -1,
        'seed':2019,   #种子
        'num_boost_ound':100000,  # 迭代次数
        'early_stoppig_rounds':100,
        'verbose': -1,
        'num_class':12,
        # 'min_data_in_leaf ': 10,  # 一叶中最少的数据 没用e
        # # 'device_type': 'gpu' # 没用
        # 'tree_learner ': 'feature',  # 没用
        # 'alpha ': 0.9  # 没用
    }
y_train = train_data['click_mode'].values
X_train = train_data.drop(['sid', 'click_mode'], axis=1).values
X_test = test_data.drop(['sid'], axis=1).values
nfolds =5
    folds = StratifiedKFold(n_splits=nfolds, shuffle=True, random_state=123)
train_pre = np.zeros(len(train_data)*12).reshape(-1,12)#模型对训练集的预测,用做评价模型好坏
    print(train_pre.shape)
test_pre = np.zeros(len(test_data)*12).reshape(-1,12)
i=0
    for fold_, (trn_idx, val_idx)in enumerate(folds.split(X_train, y_train)):
print("fold n°{}".format(fold_ +1))
i=i+1
        # categorical_feature = [1, 2, 3, 4, 5, 6, 7, 8, -1, -2, -3, -4, -5]
        lgb_train = lgb.Dataset(X_train[trn_idx], y_train[trn_idx])# 创建训练数据
        lgb_eval = lgb.Dataset(X_train[val_idx], y_train[val_idx], reference=lgb_train)# 创建验证数据
        clf = lgb.train(param1,train_set=lgb_train,valid_sets=[lgb_train,lgb_eval],verbose_eval=-1)
# 预测训练集,分层采样后一部分用做预测
        a=pd.DataFrame(clf.predict(X_train[val_idx], ntree_limit=clf.best_iteration))
# print(a)
# print(clf.predict(X_train[val_idx], ntree_limit=clf.best_iteration))
        train_pre[val_idx] = clf.predict(X_train[val_idx], ntree_limit=clf.best_iteration)
# 预测测试集,即提交结果
        test_pre += clf.predict(X_test, ntree_limit=clf.best_iteration)/folds.n_splits
# print("xgb CV score: {:<8.8f}".format(score(y_train,train_pre)))
    test_pre = [list(x).index(max(x))for xin test_pre]
train_pre = [list(x).index(max(x))for xin train_pre]
ZQL(train_pre,y_train)
sub_te=pd.DataFrame(test_pre)
sub_te['sid']=test_data['sid']
sub_tr=pd.DataFrame(train_pre)
sub_tr['sid']=train_data['sid']
sub_te.to_csv("anser/test/pid_result1"+now+'.csv', index=False)
sub_tr.to_csv("anser/train/pid_result"+now+'.csv', index=False)
def model_main2(train_data,test_data):
train_data = train_data.drop('click_time', axis=1)
param1 = {
'learning_rate':0.01,  # 学习速率# 0.05,0.1,0.15
        'boosting_type':'gbdt',  #
        'objective':'multiclass',
        'metric':'multi_logloss',
        'feature_fraction':0.60,  # 训练树之前选择特征的比例 [0.4,0.5,0.6,0.7,0.8]  深度5:0.6
        'bagging_fraction':0.8,
    # [0.6,0.7,0.8,0.9] 0.6  0.8  [0.06387005830920574, 0.06385488609127314, 0.0638610192087074, 0.06385078605195317]
        'bagging_freq':2,  # 套袋频率
        'num_leaves':40,
    # 一棵树的最大叶数[25,35,45,55]  45 [0.06385057088135324, 0.0638610192087074, 0.0638610192087074, 0.0638610192087074]  31 32
        'max_depth': -1,
        'lambda_l2':5,
     [0.1,1,5,10] [0.06387748918661836, 0.06385215918644115, 0.06388492418089266, 0.06388601729372406]
        'lambda_l1':0.001,  # [0.0001,0.001,0.01]: 0.001
        'num_threads': -1,
        'seed':2019,  # 种子
        'num_boost_round':100000,  # 迭代次数
        'early_stopping_rounds':100,
        'verbose': -1,
        'num_class':12,
        # 'min_data_in_leaf ': 10,  # 一叶中最少的数据 没用e
        # # 'device_type': 'gpu' # 没用
        # 'tree_learner ': 'feature',  # 没用
        # 'alpha ': 0.9  # 没用
    }
y_train = train_data['click_mode'].values
X_train = train_data.drop(['sid', 'click_mode'], axis=1).values
X_test = test_data.drop(['sid'], axis=1).values
nfolds =5
    folds = StratifiedKFold(n_splits=nfolds, shuffle=True, random_state=123)
tran_pre = np.zeros(len(train_data) *12).reshape(-1, 12)# 模型对训练集的预测,用做评价模型好坏
    test_pre = np.zeros(len(test_data) *12).reshape(-1, 12)
i =0
    list_categorical = [-1,-2]
for fold_, (trn_idx, val_idx)in enumerate(folds.split(X_train, y_train)):
print("fold n°{}".format(fold_ +1))
i = i +1
        # categorical_feature = [1, 2, 3, 4, 5, 6, 7, 8, -1, -2, -3, -4, -5]
       lgb_train = lgb.Dataset(X_train[trn_idx], y_train[trn_idx],categorical_feature=list_categorical)# 创建训练数据
       lgb_eval = lgb.Dataset(X_train[val_idx], y_train[val_idx], categorical_feature=list_categorical,reference=lgb_train)# 创建验证数据
       clf = lgb.train(param1, train_set=lgb_train, valid_sets=[lgb_train, lgb_eval], verbose_eval=-1)
# 预测训练集,分层采样后一部分用做预测
        a = pd.DataFrame(clf.predict(X_train[val_idx], ntree_limit=clf.best_iteration))
# print(a)
# print(clf.predict(X_train[val_idx], ntree_limit=clf.best_iteration))
        train_pre[val_idx] = clf.predict(X_train[val_idx], ntree_limit=clf.best_iteration)
# 预测测试集,即提交结果
        test_pre += clf.predict(X_test, ntree_limit=clf.best_iteration) / folds.n_splits
# print("xgb CV score: {:<8.8f}".format(score(y_train,train_pre)))
    test_pre = [list(x).index(max(x))for xin test_pre]
train_pre = [list(x).index(max(x))for xin train_pre]
ZQL(train_pre, y_train)
sub_te = pd.DataFrame(test_pre)
sub_te['sid'] = test_data['sid']
sub_tr = pd.DataFrame(train_pre)
sub_tr['sid'] = train_data['sid']
sub_te.to_csv("anser/test/nopid_result1"+now+'.csv', index=False)
sub_tr.to_csv("anser/train/nopid_result"+now+'.csv', index=False)
def hand_time(x):# 本函数用于求当天距2018.1.1的天数
    x1=x.split(' ')[0]
d1=datetime.datetime.strptime(x1, '%Y-%m-%d')
d2 = datetime.datetime.strptime('2018/1/1', '%Y/%m/%d')
return (d1-d2).days
def hand_time2(x):# 本函数用于求现在时间与0:0:0的秒数
    x2 = x.split(' ')[1]
d1 = datetime.datetime.strptime(x2, '%H:%M:%S')
d2 = datetime.datetime.strptime('00:0:0', '%H:%M:%S')
return (d1 - d2).seconds
def fun_cha2(x):
if x<0:
return 1
    elif x==0:
return 2
    elif x>0:
return 3
def month(x):
x1 = x.split(' ')[0]
return x1.split('-')[1]
def day(x):
x1 = x.split(' ')[0]
return x1.split('-')[2]
def week(x):
x1 = x.split(' ')[0]
d1=datetime.datetime.strptime(x1, '%Y-%m-%d')
return d1.strftime("%w")
def hand(x):
x = x.fillna(0)
x['req_days']=x['req_time'].apply(lambda x:hand_time(x)if x!=0 else 0)
x['plan_days'] = x['plan_time'].apply(lambda x:hand_time(x)if x!=0 else 0)
x['req_seconds']=x['req_time'].apply(lambda x:hand_time2(x)if x!=0 else 0)
x['plan_seconds']=x['plan_time'].apply(lambda x:hand_time2(x)if x!=0 else 0)
x['cha']=x['req_days']-x['plan_days']
x['cha']=x['cha'].apply(lambda x:1 if x>0 else 1)
x['cha2'] = x['req_seconds'] - x['plan_seconds']
x['cha2'] = x['cha2'].apply(lambda x:fun_cha2(x))
x['month'] = x['plan_time'].apply(lambda x: month(x)if x !=0 else 0)
x['day'] = x['plan_time'].apply(lambda x: day(x)if x !=0 else 0)
x['week'] = x['plan_time'].apply(lambda x: week(x)if x !=0 else 0)
x['o_x'] = x['o'].apply(lambda x:float(x.split(',')[0]))
x['o_y'] = x['o'].apply(lambda x:float(x.split(',')[1]))
x['d_x'] = x['d'].apply(lambda x:float(x.split(',')[0]))
x['d_y'] = x['d'].apply(lambda x:float(x.split(',')[1]))
x['line_distance'] = np.square(x['o_x'] - x['d_x']) + np.square(x['o_y'] - x['d_y'])
x=x.drop(['pid','req_time','o','d','plan_time'],axis=1)
# d1=datetime.datetime.strftime(x,)
# d2 = datetime.datetime.strptime('2018/1/1', '%Y/%m/%d')
    return x
now=str(time.strftime("%d_%H_%M_%S", time.localtime()))
# train1=pd.read_csv('data2/pid_ture_profiles.csv')
# test1=pd.read_csv('data2/pid_ture_test_profiles.csv')
# hand_train1=hand(train1)
# hand_test1=hand(test1)
# model_main1(hand_train1,hand_test1)
print('========================有pid===================================')
train2=pd.read_csv('data2/pid_false.csv')
test2=pd.read_csv('data2/pid_false_test.csv')
hand_train2=hand(train2)
hand_test2=hand(test2)
model_main2(hand_train2,hand_test2)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容

  • 首页 资讯 文章 资源 小组 相亲 登录 注册 首页 最新文章 IT 职场 前端 后端 移动端 数据库 运维 其他...
    Helen_Cat阅读 3,824评论 1 10
  • 机器学习术语表 本术语表中列出了一般的机器学习术语和 TensorFlow 专用术语的定义。 A A/B 测试 (...
    yalesaleng阅读 1,955评论 0 11
  • 本文编译自谷歌开发者机器学习术语表项目,介绍了该项目所有的术语与基本解释。 A 准确率(accuracy) 分类模...
    630d0109dd74阅读 1,977评论 0 1
  • A 准确率(accuracy) 分类模型预测准确的比例。在多类别分类中,准确率定义如下: 在二分类中,准确率定义为...
    630d0109dd74阅读 1,298评论 0 3
  • 5种状态码 示例1: 示例2:安装一个进程观察,父子进程以及状态。父亲Ss 和 儿子S 示例3:自定义显示字段 ...
    心疼你萌萌哒阅读 200评论 0 0