# 数据分析

http://datawhale.club/t/topic/197/1

# coding: utf-8
# In[3]:
# 导入相关包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.rc('font', family='SimHei', size=13)
import os,gc,re,warnings,sys
warnings.filterwarnings("ignore")

# In[11]:
path = 'C:/Users/LENOVO/Desktop/datawhaleRES/'
#####train
item_df = item_df.rename(columns={'article_id': 'click_article_id'})  #重命名，方便后续match
#####test
item_df

# In[5]:
# 对每个用户的点击时间戳进行排序
trn_click['rank'] = trn_click.groupby(['user_id'])['click_timestamp'].rank(ascending=False).astype(int)
tst_click['rank'] = tst_click.groupby(['user_id'])['click_timestamp'].rank(ascending=False).astype(int)

# In[10]:
#计算用户点击文章的次数，并添加新的一列count
trn_click['click_cnts'] = trn_click.groupby(['user_id'])['click_timestamp'].transform('count')
tst_click['click_cnts'] = tst_click.groupby(['user_id'])['click_timestamp'].transform('count')
trn_click

# In[12]:
trn_click = trn_click.merge(item_df, how='left', on=['click_article_id'])

# In[13]:
#用户点击日志信息
trn_click.info()

# In[14]:
trn_click.describe()

# In[15]:
#训练集中的用户数量为20w
trn_click.user_id.nunique()

# In[18]:
trn_click.groupby('user_id')['click_article_id'].count().min()  # 训练集里面每个用户至少点击了两篇文章

# In[19]:
plt.figure()
plt.figure(figsize=(15, 20))
i = 1
for col in ['click_article_id', 'click_timestamp', 'click_environment', 'click_deviceGroup', 'click_os', 'click_country',
'click_region', 'click_referrer_type', 'rank', 'click_cnts']:
plot_envs = plt.subplot(5, 2, i)
i += 1
v = trn_click[col].value_counts().reset_index()[:10]
fig = sns.barplot(x=v['index'], y=v[col])
for item in fig.get_xticklabels():
item.set_rotation(90)
plt.title(col)
plt.tight_layout()
plt.show()

# In[20]:
tst_click = tst_click.merge(item_df, how='left', on=['click_article_id'])

# In[21]:
tst_click.describe()

# In[22]:
#测试集中的用户数量为5w
tst_click.user_id.nunique()

# In[23]:
tst_click.groupby('user_id')['click_article_id'].count().min() # 注意测试集里面有只点击过一次文章的用户

# In[24]:
#新闻文章数据集浏览

# In[25]:
item_df['words_count'].value_counts()

# In[26]:
print(item_df['category_id'].nunique())     # 461个文章主题
item_df['category_id'].hist()

# In[27]:
item_df.shape       # 364047篇文章

# In[28]:

# In[29]:
item_emb_df.shape

# In[30]:
#####merge
user_click_merge = trn_click.append(tst_click)

# In[31]:
#用户重复点击
user_click_count = user_click_merge.groupby(['user_id', 'click_article_id'])['click_timestamp'].agg({'count'}).reset_index()
user_click_count[:10]

# In[32]:
user_click_count[user_click_count['count']>7]

# In[33]:
user_click_count['count'].unique()

# In[34]:
#用户点击新闻次数
user_click_count.loc[:,'count'].value_counts()

# In[35]:
def plot_envs(df, cols, r, c):
plt.figure()
plt.figure(figsize=(10, 5))
i = 1
for col in cols:
plt.subplot(r, c, i)
i += 1
v = df[col].value_counts().reset_index()
fig = sns.barplot(x=v['index'], y=v[col])
for item in fig.get_xticklabels():
item.set_rotation(90)
plt.title(col)
plt.tight_layout()
plt.show()

# In[37]:
# 分析用户点击环境变化是否明显，这里随机采样10个用户分析这些用户的点击环境分布
sample_user_ids = np.random.choice(tst_click['user_id'].unique(), size=5, replace=False)
sample_users = user_click_merge[user_click_merge['user_id'].isin(sample_user_ids)]
cols = ['click_environment','click_deviceGroup', 'click_os', 'click_country', 'click_region','click_referrer_type']
for _, user_df in sample_users.groupby('user_id'):
plot_envs(user_df, cols, 2, 3)

# In[38]:
user_click_item_count = sorted(user_click_merge.groupby('user_id')['click_article_id'].count(), reverse=True)
plt.plot(user_click_item_count)

# In[39]:
#点击次数在前50的用户
plt.plot(user_click_item_count[:50])

# In[40]:
#点击次数排名在[25000:50000]之间
plt.plot(user_click_item_count[25000:50000])

# In[41]:
item_click_count = sorted(user_click_merge.groupby('click_article_id')['user_id'].count(), reverse=True)

# In[42]:
plt.plot(item_click_count)

# In[43]:
plt.plot(item_click_count[:100])

# In[44]:

plt.plot(item_click_count[:20])
# In[45]:

plt.plot(item_click_count[3500:])
# In[46]:

tmp = user_click_merge.sort_values('click_timestamp')
tmp['next_item'] = tmp.groupby(['user_id'])['click_article_id'].transform(lambda x:x.shift(-1))
union_item = tmp.groupby(['click_article_id','next_item'])['click_timestamp'].agg({'count'}).reset_index().sort_values('count', ascending=False)
union_item[['count']].describe()

# In[47]:
#画个图直观地看一看
x = union_item['click_article_id']
y = union_item['count']
plt.scatter(x, y)

# In[48]:
plt.plot(union_item['count'].values[40000:])

# In[49]:
#不同类型的新闻出现的次数
plt.plot(user_click_merge['category_id'].value_counts().values)

# In[50]:
#出现次数比较少的新闻类型, 有些新闻类型，基本上就出现过几次
plt.plot(user_click_merge['category_id'].value_counts().values[150:])

# In[51]:
#新闻字数的描述性统计
user_click_merge['words_count'].describe()

# In[52]:
plt.plot(user_click_merge['words_count'].values)

# In[53]:
plt.plot(sorted(user_click_merge.groupby('user_id')['category_id'].nunique(), reverse=True))

# In[54]:
user_click_merge.groupby('user_id')['category_id'].nunique().reset_index().describe()

# In[55]:
plt.plot(sorted(user_click_merge.groupby('user_id')['words_count'].mean(), reverse=True))

# In[56]:
#挑出大多数人的区间仔细看看
plt.plot(sorted(user_click_merge.groupby('user_id')['words_count'].mean(), reverse=True)[1000:45000])

# In[57]:
#更加详细的参数
user_click_merge.groupby('user_id')['words_count'].mean().reset_index().describe()

# In[58]:
#为了更好的可视化，这里把时间进行归一化操作
from sklearn.preprocessing import MinMaxScaler
mm = MinMaxScaler()
user_click_merge['click_timestamp'] = mm.fit_transform(user_click_merge[['click_timestamp']])
user_click_merge['created_at_ts'] = mm.fit_transform(user_click_merge[['created_at_ts']])
user_click_merge = user_click_merge.sort_values('click_timestamp')

# In[59]:

# In[60]:

def mean_diff_time_func(df, col):
df = pd.DataFrame(df, columns={col})
df['time_shift1'] = df[col].shift(1).fillna(0)
df['diff_time'] = abs(df[col] - df['time_shift1'])
return df['diff_time'].mean()
# In[61]:

# 点击时间差的平均值
mean_diff_click_time = user_click_merge.groupby('user_id')['click_timestamp', 'created_at_ts'].apply(lambda x: mean_diff_time_func(x, 'click_timestamp'))
# In[62]:

plt.plot(sorted(mean_diff_click_time.values, reverse=True))

# In[ ]:

# 前后点击文章的创建时间差的平均值
mean_diff_created_time = user_click_merge.groupby('user_id')['click_timestamp', 'created_at_ts'].apply(lambda x: mean_diff_time_func(x, 'created_at_ts'))

# In[ ]:

plt.plot(sorted(mean_diff_created_time.values, reverse=True))

# In[ ]:

# 用户前后点击文章的相似性分布
item_idx_2_rawid_dict = dict(zip(item_emb_df['article_id'], item_emb_df.index))

# In[ ]:

del item_emb_df['article_id']

# In[ ]:

item_emb_np = np.ascontiguousarray(item_emb_df.values, dtype=np.float32)

# In[ ]:

# 随机选择5个用户，查看这些用户前后查看文章的相似性
sub_user_ids = np.random.choice(user_click_merge.user_id.unique(), size=15, replace=False)
sub_user_info = user_click_merge[user_click_merge['user_id'].isin(sub_user_ids)]

# In[ ]:

def get_item_sim_list(df):
sim_list = []
item_list = df['click_article_id'].values
for i in range(0, len(item_list)-1):
emb1 = item_emb_np[item_idx_2_rawid_dict[item_list[i]]]
emb2 = item_emb_np[item_idx_2_rawid_dict[item_list[i+1]]]
sim_list.append(np.dot(emb1,emb2)/(np.linalg.norm(emb1)*(np.linalg.norm(emb2))))
sim_list.append(0)
return sim_list

# In[ ]:

for _, user_df in sub_user_info.groupby('user_id'):
item_sim_list = get_item_sim_list(user_df)
plt.plot(item_sim_list)


11-25 39