## 一个脚本打比赛之SMP WEIBO 2016 ## 前言:如何对用户进行精准画像是社交网络分析的基础问题。本文就如何对weibo用户网络提取特征发表一点小的想法,还请尽管拍砖。 数据来源:SMP WEIBO 2016 任务目标:分析用户关联关系与用户发帖内容,通过无监督与有监督方法对用户进行聚类。 ———- 第一部分:筛选source,即判定用户发表的内容是否是垃圾信息。

import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from time import time
%matplotlib inline

训练数据字段含义: uid: 用户唯一标识,由数字组成 retweet count: 转发数,数字 review count: 评论数,数字 source: 来源,文本 time: 创建时间,时间戳文本(目前有两种格式,yyyy-MM-dd HH:mm:ss和yyyy-MM-dd HH:mm) content: 文本内容(可能包含@信息、表情符信息等)

with open('train/train/train_status.txt','r') as f:lines = f.readlines()
status=[]
for line in lines:status.append(line.strip().split(','))
tr_status = pd.DataFrame(status).loc[:,:5]
tr_status.columns=['uid','retweet','review','source','time','content']
tr_status.to_csv('train_status.csv',index=False)
display(tr_status.head())
with open('valid/valid_status.txt','r') as f:lines = f.readlines()
status=[]
for line in lines:status.append(line.strip().split(','))
v_status = pd.DataFrame(status).loc[:,:5]
v_status.columns=['uid','retweet','review','source','time','content']
v_status.to_csv('valid_status.csv',index=False)
display(v_status.head())
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }

uid retweet review source time content
0 1103763581 0 0 Arduino中文社区 2016-01-07 13:14 我 用 微博 在 Arduino 中文 社区 上 登录 啦 ! Arduino 中文 社区 …
1 1103763581 0 2 荣耀6 Plus 2015-11-10 09:13:35 很 长 时间 没有 上 微博 看看 了 , 估计 都 快 被 忘记 了 吧 ! 无锡·新安 …
2 1103763581 0 0 荣耀6 Plus 2015-07-26 20:07:57 # 农村 现状 # 20 年 前 还是 个 小孩 , 一 到 瓜果 成熟 的 季节 , 三五…
3 1103763581 0 0 荣耀6 Plus 2015-06-22 18:39:47 我 分享 了 @环球时报 的 文章 社评 : 法国 出租 与 专车 司机 冲突 的 启示
4 1103763581 0 6 荣耀6 Plus 2015-06-10 07:37:22 好久 没 上 微博 了 , 不 知道 大家 还 记得 我 不 ? 梁家巷 显示 地图
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }

uid retweet review source time content
0 1753249671 0 0 iPhone客户端 2016-05-06 10:01 扑通 扑通 我 的 心跳 ! 久久 不 能 平 …… 深 呼吸 、 深 呼吸 、 深 呼吸 !
1 1753249671 0 0 iPhone客户端 2016-04-15 01:19 失眠 的 夜晚 , 夜 慢慢 慢慢 原 图
2 1753249671 0 0 iPhone客户端 2016-03-29 19:15 贱人 就 是 矫情 、 奇葩 朵朵 开 的 一 天 极品 领导 同事 , 人生 不 如意 之…
3 1753249671 0 0 iPhone客户端 2016-01-25 22:53 # 买家 反馈 语录 # 来自 小伙伴 们 对 牛板筋 的 好评 , 还 在 等待 观望 的…
4 1753249671 0 0 iPhone客户端 2016-01-06 19:51 童言无忌 : 朋友 女儿 今年 小学 三 年级 , 看到 她 妈妈 朋友圈 里 我 发 的 …

已标注用户字段含义:
uid: 用户唯一标识,由数字组成

gender: 用户性别,m代表男性,f代表女性,None代表此项信息缺失

birthday: 用户出生年份,None代表此项信息缺失

location: 用户地域,部分用户包含省份和城市信息,部分用户只有省份信息,None代表此项信息缺失

with open('train/train/train_labels.txt','r') as f:labels = f.readlines()
labels[0]

‘1832205887||m||1990||四川 None\n’

userHasLabel = [x.split("||")[0].strip() for x in lines]
import pandas as pd
t_labels = pd.read_csv('train/train/train_labels.txt',sep="\\|\\|",header=None)
t_labels.columns = ['uid','gender','birthday','location']v_labels = pd.read_csv('valid/valid_labels.txt',sep="\\|\\|",header=None)
v_labels.columns = ['uid','gender','birthday','location']
print(t_labels.head())
print(v_labels.head())
labeled_nodes = pd.concat([t_labels,v_labels])
labeled_nodes.to_csv('labeled_nodes.csv',index=False,encoding='gbk')

uid gender birthday location 0 1832205887 m 1990 四川 None 1 1737245804 m 1982 吉林 长春 2 2157991124 m 1976 四川 成都 3 2758890931 f 1983 黑龙江 哈尔滨 4 1802646764 m 1981 湖南 长沙 uid gender birthday location 0 1743152063 m 1984 广东 广州 1 1073390982 m 1983 北京 朝阳区 2 2137599524 m 1990 湖北 黄石 3 2279196033 f 1987 江苏 南京 4 1039584863 m 1985 广东 深圳 /home/ll/miniconda3/lib/python3.5/site-packages/ipykernel_launcher.py:2: ParserWarning: Falling back to the ‘python’ engine because the ‘c’ engine does not support regex separators (separators > 1 char and different from ‘\s+’ are interpreted as regex); you can avoid this warning by specifying engine=’python’. /home/ll/miniconda3/lib/python3.5/site-packages/ipykernel_launcher.py:5: ParserWarning: Falling back to the ‘python’ engine because the ‘c’ engine does not support regex separators (separators > 1 char and different from ‘\s+’ are interpreted as regex); you can avoid this warning by specifying engine=’python’. “””

df = pd.concat([tr_status,v_status])
df.loc[:,'uid'] = df['uid'].astype(int)
df = df.merge(labeled_nodes)
display(df.head(10))
display(df.shape)
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }

uid retweet review source time content gender birthday location
0 1103763581 0 0 Arduino中文社区 2016-01-07 13:14 我 用 微博 在 Arduino 中文 社区 上 登录 啦 ! Arduino 中文 社区 … m 1986 四川 成都
1 1103763581 0 2 荣耀6 Plus 2015-11-10 09:13:35 很 长 时间 没有 上 微博 看看 了 , 估计 都 快 被 忘记 了 吧 ! 无锡·新安 … m 1986 四川 成都
2 1103763581 0 0 荣耀6 Plus 2015-07-26 20:07:57 # 农村 现状 # 20 年 前 还是 个 小孩 , 一 到 瓜果 成熟 的 季节 , 三五… m 1986 四川 成都
3 1103763581 0 0 荣耀6 Plus 2015-06-22 18:39:47 我 分享 了 @环球时报 的 文章 社评 : 法国 出租 与 专车 司机 冲突 的 启示 m 1986 四川 成都
4 1103763581 0 6 荣耀6 Plus 2015-06-10 07:37:22 好久 没 上 微博 了 , 不 知道 大家 还 记得 我 不 ? 梁家巷 显示 地图 m 1986 四川 成都
5 1103763581 0 0 世界3D打印 2015-06-05 08:08:00 【 太尔 时代 助力 “ 太空 制造 ” , 挑战 微重力 环境 下 3D 打印 】 【 分… m 1986 四川 成都
6 1103763581 0 0 荣耀6 Plus 2015-05-27 21:29:57 愤怒 的 小鸟 存 钱 [ 钱 ] 罐 http://t.cn/z8dS7zS 显示 地… m 1986 四川 成都
7 1103763581 3 1 荣耀6 Plus 2015-05-22 08:45:56 成都 科技 爱好者 的 盛宴 。太尔 时代 UP 系列 机器 将 在 两 场 活动 中 展出… m 1986 四川 成都
8 1103763581 0 0 荣耀6 Plus 2015-05-05 19:10:32 最近 身体 不适 , 准备 适当 休整 。 如 工作 事宜 请 拨打 办公 电话 028-6… m 1986 四川 成都
9 1103763581 0 0 百度分享 2015-04-30 10:43:52 3D 打印机 公司 太尔 时代 上 榜福布斯 中国 潜力 企业 100 强 -3D 打印 资… m 1986 四川 成都
(331634, 9)
labeled_id = list(t_labels['uid']) + list(v_labels['uid'])
print(len(labeled_id),len(set(labeled_id)))

4467 4467 从第二个用户到最后一个用户均为第一个用户的粉丝 筛选出链接中给出的用户。 @output : nodelist

with open('train/train/train_links.txt','r') as f:t_links = f.readlines()
with open('valid/valid_links.txt','r') as f:v_links = f.readlines()
with open('test/test/test_links.txt','r') as f:te_links = f.readlines()
linklist=[]
for link in t_links:linklist += [str(x) for x in link.strip().split(' ')]
for link in v_links:linklist += [str(x) for x in link.strip().split(' ')]
for link in te_links:linklist += [str(x) for x in link.strip().split(' ')]
print(len(linklist))
print(len(set(linklist)))

721388 308787

nodelist = []
for node in labeled_id:try:linklist.index(str(node))nodelist.append(node)except Exception as e:#print(node)pass
print(len(nodelist))

2476

df = df.set_index('uid').loc[nodelist,:]
display(df.shape)
df.to_csv('labeled_linked_fulltable.csv')

(191119, 8) 至此,将可以筛选的Node筛选出来,具有标签与网络中存在的节点

display(df.shape)
import re
patt = re.compile('努比亚')
res = filter(patt.match, list(df['source'].drop_duplicates()))
list(res)
# re.findall(patt,list(df['source'].drop_duplicates()))
# list(df['source'].drop_duplicates()).index('努比亚Android')

(191119, 9) [‘努比亚智能手机’]

import pandas as pd
#df= pd.read_csv('labeled_linked_fulltable.csv')
df1 = df[['source','location']]
df1.loc[:,'count'] = 1
diffcount = df1.groupby('source')[['location']].apply(lambda x : x.location.drop_duplicates().count()).to_frame('diff')
count = df1.groupby('source')[['location']].apply(lambda x : x.location.count()).to_frame('count')
source = diffcount.join(count)
display(source.head())

/home/ll/miniconda3/lib/python3.5/site-packages/pandas/core/indexing.py:337: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[key] = _infer_fill_value(value) /home/ll/miniconda3/lib/python3.5/site-packages/pandas/core/indexing.py:517: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[item] = s

.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }

diff count
source
努比亚Android 1 1
0519微趣测试 1 3
0元赢荣耀畅玩5C 2 2
100+V6手机 3 8
100+个性定制手机 1 2
plt.subplot(211)
source.sort_values('count',ascending=False).head(100)['count'].plot(kind='line',figsize=(30,10),title='count long tail distribution' )
plt.subplot(212)
source.sort_values('count',ascending=False).head(100)['diff'].plot(kind='line',figsize=(30,10))
def hebing(group):
#     display(list(group.content.values))return ' '.join([str(x) for x in list(group.content.values)])
content_merge = df.groupby('source')[['content']].apply(hebing).to_frame('content')
#是否过滤,查看主题变化
content_merge = content_merge.join(source,how='left').reset_index()
#content_merge = content_merge.join(source)[content_merge['count']>10]
display(content_merge.head())tokenizer = lambda s:s.split(' ')
tfv = TfidfVectorizer(tokenizer=tokenizer)
data = tfv.fit_transform(content_merge.content)#词频统计
#max_df=1, min_df=1
tfc = CountVectorizer(max_features=10000,tokenizer=tokenizer)
tf = tfc.fit_transform(content_merge)
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }

source content diff count
0 努比亚Android # 苏宁 入股 努比亚 # 我 用 的 就 是 努比亚祝 努比亚能 越 办 越 好 越 办 … 1 1
1 0519微趣测试 / 偷笑 OMG , 原来 有 209 人 暗恋 着 我 , 太 不可思议 了 ! 快来 看… 1 3
2 0元赢荣耀畅玩5C 免费 狂 抽 55 台 # 荣耀 畅 玩 5C # ? ! 有 这 好事 还 不 让 微博 … 2 2
3 100+V6手机 牛刀 说 的 有点 道理 , 不过 现在 很多 放 高利贷 的 , 特别 是 县城 或者 是… 3 8
4 100+个性定制手机 新版 微博 客户端 , 好听 , 好看 , 更 好 玩 ! 自 定义 个人 封面 ; 音 、… 1 2
import pickle
with open('tfidf_vec.pkl','wb') as f:pickle.dump(data,f)
from time import time
import pickle
with open('tfidf_vec.pkl','rb') as f:data = pickle.load(f)
#print(data[0])
print('维度约减,自动约减到合适的维度')
print('提取重要特征')
from sklearn.decomposition import NMF, LatentDirichletAllocation
t0 = time()
n_components = 2
nmf = NMF(n_components=2).fit(data)
print("done in %0.3fs." % (time() - t0))
维度约减,自动约减到合适的维度
提取重要特征
done in 1.477s.
with open('nmf_model.pkl','wb') as f:pickle.dump(nmf,f)
print(nmf.reconstruction_err_)
topic = nmf.transform(data)
print(topic)
# if topic.shape[1] ==2 :
#     plt.figure(figsize=(30,30))
#     plt.scatter(x=topic[:,0],y=topic[:,1],c=content_merge['count'])
57.0115343243
[[ 0.02043113  0.        ][ 0.09281784  0.        ][ 0.03913675  0.        ]..., [ 0.05743546  0.03386496][ 0.07525523  0.        ][ 0.01523509  0.        ]]
from sklearn.mixture import GaussianMixture
gmm = GaussianMixture(n_components=2)
gmm.fit(topic)
pred = gmm.predict(topic)
content_merge.loc[:,'pred'] = predfrom sklearn.cluster import KMeans
km = KMeans(n_clusters=3)
km.fit(data)
pred = km.predict(data)
content_merge.loc[:,'pred'] = pred
label = ['荣耀6 Plus','iPhone客户端','虾米音乐移动版','爱相机','华住酒店App','分享按钮']
label = content_merge[content_merge.pred==0].head(100).source
#中文字体显示
import matplotlib
zhfont = matplotlib.font_manager.FontProperties(fname='/home/ll/.fonts/NotoSansMonoCJKsc-Regular.otf')
# plt.rcParams['font.sans-serif'] = ['Source Han Sans TW', 'sans-serif']
# plt.rc('font', family='Noto Sans Mono CJK SC', size=13)
plt.figure(figsize=(20,20))
plt.scatter(x=topic[:,0],y=topic[:,1],c=pred)
for l in label:pindex = content_merge[content_merge['source']==l].indexplt.annotate(l,xy=(topic[pindex,0],topic[pindex,1]),fontproperties=zhfont)
/home/ll/miniconda3/lib/python3.5/site-packages/matplotlib/font_manager.py:1297: UserWarning: findfont: Font family ['Noto Sans Mono CJK SC'] not found. Falling back to DejaVu Sans(prop.get_family(), self.defaultFamily[fontext]))

说明:图中标注的数据是使用KMEANS算法进行聚类得到的,KMEANS算法使用相似度作为衡量指标,可以看到聚类为0的cluster是用户使用的各种手机平台,包括iphone,huawei等等。
结论:使用TFIDF作为source筛选指标,可以由图看出是较管用的。

一个脚本打比赛之SMP WEIBO 2016相关推荐

  1. shell实例第19讲:一个脚本中调用另一个脚本的3种方法

    在Shell脚本中调用另一个脚本(3种方法) 准备:主脚本是second.sh,主脚本中调用first.sh 方法1:exec(1)执行方式:exec /home/weibo/shell_test/s ...

  2. 一个脚本实现全量增量备份,并推送到远端备份中心服务器

    2019独角兽企业重金招聘Python工程师标准>>> 摘要 由于工作需要,刚好需要这样一个功能的脚本,主要解决: 1. 不想在crontab中调度两条备份任务,一个做全量一个做增量 ...

  3. 老板说“把系统升级到https”,我用一个脚本实现了,而且永久免费!

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 现在很多站长都会考虑将自己的站点从http升级到https,不仅是 ...

  4. 我写了一个脚本,可在“任意”服务器上执行命令!

    冰河之前维护着上千台服务器组成的服务器集群,如果每次需要在服务器上执行命令的时候,都要手动登录每台服务器进行操作的话,那也太麻烦了.你想想,如果在上千台服务器的集群中,每台服务器中只需要简单的执行一个 ...

  5. 将你的前端应用打包成docker镜像并部署到服务器?仅需一个脚本搞定

    1.前言 前段时间,自己搞了个阿里云的服务器.想自己在上面折腾,但是不想因为自己瞎折腾而污染了现有的环境.毕竟,现在的阿里云已经没有免费的快照服务了.要想还原的话,最简单的办法就是重新装系统.而一旦重 ...

  6. python 学习笔记 12 -- 写一个脚本获取城市天气信息

    近期在玩树莓派,前面写过一篇在树莓派上使用1602液晶显示屏,那么可以显示后最重要的就是显示什么的问题了. 最easy想到的就是显示时间啊,CPU利用率啊.IP地址之类的.那么我认为呢,假设可以显示当 ...

  7. 让powershell同时只能运行一个脚本(进程互斥例子)

    powershell,mutex,互斥,进程互斥,脚本互斥 powershell脚本互斥例子,在powershell类别文章中,声明原创唯一. powershell 传教士 原创文章 2016-07- ...

  8. 对于写bash脚本的朋友,read命令是不可或缺的,需要实践一下就可以了解read命令的大致用途: 编写一个脚本: #!/bin/bash # hao32 test read echo -e Pl

    编写一个脚本: #!/bin/bash # hao32 test read echo -e "Please enter your test :" read TESTREAD ech ...

  9. docker image name 更改_将前端应用打包成docker镜像并部署?仅需一个脚本就搞定

    1.前言 前段时间,自己搞了个阿里云的服务器.想自己在上面折腾,但是不想因为自己瞎折腾而污染了现有的环境.毕竟,现在的阿里云已经没有免费的快照服务了.要想还原的话,最简单的办法就是重新装系统.而一旦重 ...

最新文章

  1. 知乎高赞回答:走上科研之路,需要培养什么能力?怎样培养这些能力?
  2. [SqlServer]数据库中自定义拆分字符串函数Split()
  3. 移动芯片领域变天?苹果宣布重大决定,芯片霸主市值一夜蒸发近千亿
  4. 使用 Spring Boot 快速构建 Spring 框架应用
  5. 【Scratch】青少年蓝桥杯_每日一题_1.1_美国队长盾牌
  6. 《机器学习实战》chapter02 K-近邻算法(KNN)
  7. c++构造函数和析构函数的调用顺序研究
  8. 优化 .NET Core logging 中的泛型 logger
  9. pythonopencv算法_python opencv之SURF算法示例
  10. UI2Code智能生成Flutter代码——版面分析篇
  11. Linux操作系统中pkg-config用法示例
  12. confly MySQL_MYSQL的操作类(已封装)
  13. CAM350 V14.5安装记录
  14. 新主播如何在直播行业混得好
  15. 给定一个字符串,去除整个字符串中重复的字符
  16. 苹果开发者账号申请流程完整版
  17. php octet stream,php 上传excel时,excel mime-type类型为application/octet-stream,无法通过验证...
  18. 用python预测你的小孩的身高_孩子身高预测
  19. 网页百度网盘上传显示服务器错误,win7系统下登陆百度浏览器提示连接服务器错误的方案?...
  20. 时间轮算法HashedWheelTimer

热门文章

  1. 前端面试题——2021最新企业面试题
  2. 台式计算机蓝牙如何安装,台式电脑没有蓝牙怎么安装
  3. Mac之如何将文件夹加入个人收藏
  4. Activity启动流程源码分析-浅析生命周期函数
  5. 图像视频滤镜算法---颜色滤镜
  6. 计算机运维中常见英语单词,芯片常用英文词汇整理.doc
  7. 【翻译】Chromium 网络栈 disk cache 设计原理
  8. 构建maven时No archetypes currently available的解决方法
  9. CPU,缓存,内存,外存全解析
  10. 基于soap 的 python web services 服务开发指南