一个脚本打比赛之SMP WEIBO 2016

news/2024/10/29 3:27:38/
## 一个脚本打比赛之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; }
uidretweetreviewsourcetimecontent
0110376358100Arduino中文社区2016-01-07 13:14我 用 微博 在 Arduino 中文 社区 上 登录 啦 ! Arduino 中文 社区 …
1110376358102荣耀6 Plus2015-11-10 09:13:35很 长 时间 没有 上 微博 看看 了 , 估计 都 快 被 忘记 了 吧 ! 无锡·新安 …
2110376358100荣耀6 Plus2015-07-26 20:07:57# 农村 现状 # 20 年 前 还是 个 小孩 , 一 到 瓜果 成熟 的 季节 , 三五…
3110376358100荣耀6 Plus2015-06-22 18:39:47我 分享 了 @环球时报 的 文章 社评 : 法国 出租 与 专车 司机 冲突 的 启示
4110376358106荣耀6 Plus2015-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; }
uidretweetreviewsourcetimecontent
0175324967100iPhone客户端2016-05-06 10:01扑通 扑通 我 的 心跳 ! 久久 不 能 平 …… 深 呼吸 、 深 呼吸 、 深 呼吸 !
1175324967100iPhone客户端2016-04-15 01:19失眠 的 夜晚 , 夜 慢慢 慢慢 原 图
2175324967100iPhone客户端2016-03-29 19:15贱人 就 是 矫情 、 奇葩 朵朵 开 的 一 天 极品 领导 同事 , 人生 不 如意 之…
3175324967100iPhone客户端2016-01-25 22:53# 买家 反馈 语录 # 来自 小伙伴 们 对 牛板筋 的 好评 , 还 在 等待 观望 的…
4175324967100iPhone客户端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; }
uidretweetreviewsourcetimecontentgenderbirthdaylocation
0110376358100Arduino中文社区2016-01-07 13:14我 用 微博 在 Arduino 中文 社区 上 登录 啦 ! Arduino 中文 社区 …m1986四川 成都
1110376358102荣耀6 Plus2015-11-10 09:13:35很 长 时间 没有 上 微博 看看 了 , 估计 都 快 被 忘记 了 吧 ! 无锡·新安 …m1986四川 成都
2110376358100荣耀6 Plus2015-07-26 20:07:57# 农村 现状 # 20 年 前 还是 个 小孩 , 一 到 瓜果 成熟 的 季节 , 三五…m1986四川 成都
3110376358100荣耀6 Plus2015-06-22 18:39:47我 分享 了 @环球时报 的 文章 社评 : 法国 出租 与 专车 司机 冲突 的 启示m1986四川 成都
4110376358106荣耀6 Plus2015-06-10 07:37:22好久 没 上 微博 了 , 不 知道 大家 还 记得 我 不 ? 梁家巷 显示 地图m1986四川 成都
5110376358100世界3D打印2015-06-05 08:08:00【 太尔 时代 助力 “ 太空 制造 ” , 挑战 微重力 环境 下 3D 打印 】 【 分…m1986四川 成都
6110376358100荣耀6 Plus2015-05-27 21:29:57愤怒 的 小鸟 存 钱 [ 钱 ] 罐 http://t.cn/z8dS7zS 显示 地…m1986四川 成都
7110376358131荣耀6 Plus2015-05-22 08:45:56成都 科技 爱好者 的 盛宴 。太尔 时代 UP 系列 机器 将 在 两 场 活动 中 展出…m1986四川 成都
8110376358100荣耀6 Plus2015-05-05 19:10:32最近 身体 不适 , 准备 适当 休整 。 如 工作 事宜 请 拨打 办公 电话 028-6…m1986四川 成都
9110376358100百度分享2015-04-30 10:43:523D 打印机 公司 太尔 时代 上 榜福布斯 中国 潜力 企业 100 强 -3D 打印 资…m1986四川 成都
(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; }
diffcount
source
努比亚Android11
0519微趣测试13
0元赢荣耀畅玩5C22
100+V6手机38
100+个性定制手机12
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; }
sourcecontentdiffcount
0努比亚Android# 苏宁 入股 努比亚 # 我 用 的 就 是 努比亚祝 努比亚能 越 办 越 好 越 办 …11
10519微趣测试/ 偷笑 OMG , 原来 有 209 人 暗恋 着 我 , 太 不可思议 了 ! 快来 看…13
20元赢荣耀畅玩5C免费 狂 抽 55 台 # 荣耀 畅 玩 5C # ? ! 有 这 好事 还 不 让 微博 …22
3100+V6手机牛刀 说 的 有点 道理 , 不过 现在 很多 放 高利贷 的 , 特别 是 县城 或者 是…38
4100+个性定制手机新版 微博 客户端 , 好听 , 好看 , 更 好 玩 ! 自 定义 个人 封面 ; 音 、…12
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]))

source分布

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


http://www.ppmy.cn/news/629265.html

相关文章

计算机的3d软件家庭版,3DOne家庭版 64位

3DOne家庭版是专为青少年开发的免费3D打印设计软件,智能简易的3D设计功能辅助学生轻松实现3D创意设计,软件重点整合了常用的实体造型和草图绘制命令,还有丰富的案例库以供学习,包括本地磁盘和网络云盘资源,支持一键输入3D打印机,让青少年创客教育课程开展更顺利! 3DOne家…

延庆区计算机学校,【基层链接】发展中的校园欢迎你——延庆五中现代化的教学专室与设备系列...

原标题:【基层链接】发展中的校园欢迎你——延庆五中现代化的教学专室与设备系列 ❖来源 :北京市延庆区第五中学公众号 延庆五中地处妫川森林公园腹地,四周绿树环抱,门前妫水流淌,自然与人文和谐统一,学校环…

全球及中国3D打印材料行业运营动态及投资价值分析报告2021年版

全球及中国3D打印材料行业运营动态及投资价值分析报告2021年版 HS--HS--HS--HS--HS--HS--HS--HS--HS--HS--HS--HS-- 【修订日期】:2021年11月 【搜索鸿晟信合研究院查看官网更多内容!】 第一章 3D打印材料相关概述 1.1 3D打印介绍 1.1.1 3D打印定义…

3D打印机加装热床(无需编程)

手头的三角洲打印机年老体衰,打印头的铜嘴换了不少,现在还在漏,打印头的外壳也自己重新打的,然后最近发现翘边已经无法用美纹纸解决了,于是对度娘进行各种拷问,结论是玻璃板换热床。于是乎,某宝…

Win11 安装UPStudio

首先选择x64版本,点击安装。 大概率可能提示安装失败,接下来禁用驱动程序强制签名: 在设置-系统-恢复中选择高级重新启动; 重启后进入如下界面; 按F7; 最后关闭windows验证,选择“始终安装”…

太尔时代3D打印机UP mini—2000台机器等你抢

(2014年8月7日;北京)北京太尔时代科技有限公司今天宣布,其研发和制造的桌面级3D打印机——UP mini的价格将下调至3199元,以满足中小学和 学生家长提高孩子学习和创造能力的殷切需求。 进入暑期后,或者由于家长工作缠身或者囿于条件所限&#…

《玩转3D打印》——1.4节3D打印机的选购

本节书摘来自异步社区《玩转3D打印》一书中的第1章,第1.4节3D打印机的选购,作者 王春玉 , 傅浩 , 于泓阳,更多章节内容可以访问云栖社区“异步社区”公众号查看 1.4 3D打印机的选购玩转3D打印现在3D打印机拥有多种品牌和型号,不同…

mac苹果电脑,怎么批量修改文件名称

mac苹果电脑,如何批量修改文件名称?在苹果电脑上对文件名称进行修改是一件非常简单的操作,相信任何mac电脑用户都知道怎么操作,只需要选中要修改名称的文件,然后点击鼠标右键,然后会弹出一个菜单&#xff0…