KAGGLE 比赛学习笔记---OTTO---baseline解读2-时间维度的数据解读

2023-11-21 20:20

本文主要是介绍KAGGLE 比赛学习笔记---OTTO---baseline解读2-时间维度的数据解读,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

时间序列EDA-用户和实时会话
在Kaggle的Otto比赛中,“会话”一词实际上意味着“用户”。在本笔记本中,我们将显示用户及其实时会话时间序列EDA。我们观察到用户呈现出会话行为的常规模式。这些观察可以帮助我们为用户描述和设计特征。这些观察还可以让我们深入预测未来的点击、购物车和订单行为。我们将使用RAPID cuDF处理数据帧,使用matplotlib显示EDA。这里有关于这个笔记本的Kaggle讨论

# LOAD LIBRARIES
import pandas as pd, numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import cudf, cupy
print('Using RAPIDS version',cudf.__version__)# LOAD TRAIN DATA. RANDOM SAMPLE 10%
train = cudf.read_parquet('../input/otto-full-optimized-memory-footprint/train.parquet')
sessions = train.session.unique()
sample = cupy.random.choice(sessions,len(sessions)//10,replace=False)
train = train.loc[train.session.isin(sample)]
print('We are using random 1/10 of users. Truncated train data has shape', train.shape )
train.head()# MIN AND MAX TRAIN DATES
# IF USING ORIGINAL CSV, USE "TS * 1e6" BELOW
train.ts = cudf.to_datetime(train.ts * 1e9)
print('Train min date and max date are:', train.ts.min(),'and', train.ts.max() )
print('We will truncate train data to begin Aug 1st, 2022')
train = train.loc[train.ts >= cudf.to_datetime('2022-08-01')]# COMPUTE DAY AND HOUR OF ACTIVITY
train['day'] = train.ts.dt.day
train['hour'] = train.ts.dt.hour
train = train.reset_index(drop=True)
# THE NEXT TWO LINES REPLICATE GROUPBY TRANSFORM
tmp = train.groupby('session').aid.agg('count').rename('n')
train = train.merge(tmp,on='session')
frequent_users = cupy.asnumpy( train.loc[train.n>40,'session'].unique() )
print(f"There are {len(frequent_users)} users whom each have over 40 item interactions in our truncated train data sample.")
print("We will display 128 of these most active users' behavior below.")# COMPUTE USER REAL SESSIONS
train.ts = train.ts.astype('int64')/1e9
# THE NEXT THREE LINES REPLICATE GROUPBY DIFF
train = train.sort_values(['session','ts']).reset_index(drop=True)
train['d'] = train.ts.diff()
train.loc[ train.session.diff()!=0, 'd'] = 0
# IDENTITY REAL USER SESSIONS WHEN WE SEE 2 HOUR PAUSE IN ACTIVITY
train.d = (train.d > 60*60*2).astype('int8').fillna(0)
train['d'] = train.groupby('session').d.cumsum()plt.hist(train.d.to_array(), bins=100)
plt.title("Histogram of Train Users' Real Session Count")
m = train.d.mean()
print(f'The mean session count per train user is {m:0.1f} with right skewed distribution below')
plt.show()#Display User and Sessions Time Series
#Below we display a scatter plot with jitter. The x axis is day of the month August 2022. And the y axis is hour of the day. Many dots would fall on top of each other, so we add random x and y jitter. Also we color the clicks blue, carts orange, and orders red. We plot the clicks first, then carts, then orders. This guarentees that the orders and carts (when present) will always be visible and not be obscured by click dots# DISPLAY USER ACTIVITY
colors = np.array( [(0,0,1),(1,0.5,0),(1,0,0)] )for k in range(128):u = np.random.choice(frequent_users)tmp = train.loc[train.session==u].to_pandas()ss = tmp.d.max()+1ii = len(tmp)plt.figure(figsize=(20,5))for j in [0,1,2]:s = 25if j==1: s=50elif j==2: s=100tmp2 = tmp.loc[tmp['type']==j]xx = np.random.uniform(-0.3,0.3,len(tmp2))yy = np.random.uniform(-0.5,0.5,len(tmp2))plt.scatter(tmp2.day.values+xx, tmp2.hour.values+yy, s=s, c=colors[tmp2['type'].values])plt.ylim((0,24))plt.xlim((0,30))c1 = mpatches.Patch(color=colors[0], label='Click')c2 = mpatches.Patch(color=colors[1], label='Cart')c3 = mpatches.Patch(color=colors[2], label='Order')plt.plot([0,30],[6-0.5,6-0.5],'--',color='gray')plt.plot([0,30],[21+0.5,21+0.5],'--',color='gray')for k in range(0,30):plt.plot([k+0.5,k+0.5],[0,24],'--',color='gray')for k in range(1,5):plt.plot([7*k+0.5,7*k+0.5],[0,24],'--',color='black')plt.legend(handles=[c1,c2,c3])plt.xlabel('Day of August 2022',size=16)plt.xticks([1,5,10,15,20,25,29],['Mon\nAug 1st','Fri\nAug 5th','Wed\nAug 10th','Mon\nAug 15th','Sat\nAug 20th','Thr\nAug 25th','Mon\nAug 29th'])plt.ylabel('Hour of Day',size=16)plt.yticks([0,4,8,12,16,20,24],['midnight','4am','8am','noon','4pm','8pm','midnight'])plt.title(f'User {u} has {ss} real sessions with {ii} item interactions',size=18)plt.show()print('\n\n')#    Observations
#We observe many patterns above. Most users exhibit regular behavior. They click, cart and order at the same hours each day. Also most users like to shop on the same days of the each week. Most users are active during the waking hours of day but some users like to shop during the night while others are sleeping. We also notice that users shop in clusters of activity. Our challenge in this competition is that we must both predict the remainder of the last cluster (provided in test data) and predict new clusters (after last timestamp in test). Furthermore all users in test data (not displayed in this notebook) have less than 1 week data, so we must predict user behavior given little user history information (i.e. the RecSys "cold start" problem). Understanding users and their behavior will help us predict test users' future behavior!

运行结果示例

请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述

这篇关于KAGGLE 比赛学习笔记---OTTO---baseline解读2-时间维度的数据解读的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/404843

相关文章

Python标准库datetime模块日期和时间数据类型解读

《Python标准库datetime模块日期和时间数据类型解读》文章介绍Python中datetime模块的date、time、datetime类,用于处理日期、时间及日期时间结合体,通过属性获取时间... 目录Datetime常用类日期date类型使用时间 time 类型使用日期和时间的结合体–日期时间(

使用Python开发一个Ditto剪贴板数据导出工具

《使用Python开发一个Ditto剪贴板数据导出工具》在日常工作中,我们经常需要处理大量的剪贴板数据,下面将介绍如何使用Python的wxPython库开发一个图形化工具,实现从Ditto数据库中读... 目录前言运行结果项目需求分析技术选型核心功能实现1. Ditto数据库结构分析2. 数据库自动定位3

pandas数据的合并concat()和merge()方式

《pandas数据的合并concat()和merge()方式》Pandas中concat沿轴合并数据框(行或列),merge基于键连接(内/外/左/右),concat用于纵向或横向拼接,merge用于... 目录concat() 轴向连接合并(1) join='outer',axis=0(2)join='o

批量导入txt数据到的redis过程

《批量导入txt数据到的redis过程》用户通过将Redis命令逐行写入txt文件,利用管道模式运行客户端,成功执行批量删除以Product*匹配的Key操作,提高了数据清理效率... 目录批量导入txt数据到Redisjs把redis命令按一条 一行写到txt中管道命令运行redis客户端成功了批量删除k

C语言中%zu的用法解读

《C语言中%zu的用法解读》size_t是无符号整数类型,用于表示对象大小或内存操作结果,%zu是C99标准中专为size_t设计的printf占位符,避免因类型不匹配导致错误,使用%u或%d可能引发... 目录size_t 类型与 %zu 占位符%zu 的用途替代占位符的风险兼容性说明其他相关占位符验证示

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3

Linux系统之lvcreate命令使用解读

《Linux系统之lvcreate命令使用解读》lvcreate是LVM中创建逻辑卷的核心命令,支持线性、条带化、RAID、镜像、快照、瘦池和缓存池等多种类型,实现灵活存储资源管理,需注意空间分配、R... 目录lvcreate命令详解一、命令概述二、语法格式三、核心功能四、选项详解五、使用示例1. 创建逻

Java获取当前时间String类型和Date类型方式

《Java获取当前时间String类型和Date类型方式》:本文主要介绍Java获取当前时间String类型和Date类型方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录Java获取当前时间String和Date类型String类型和Date类型输出结果总结Java获取

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库