㈠ 如何用python实现《多社交网络的影响力最大化问题分析》中的算法
经过一周,现已初步完成,其中多出代码不够美观以及效率不高,还请指点
# _*_ coding:utf-8 _*_
# ==================================================================================
#
# Description: Influence Maximization on Multiple Social Networks
#
# ==================================================================================
import matplotlib.pyplot as plt
import networkx as nx
import heapq
#总图
G = nx.DiGraph()
def load_graph(file):
'''
加载文件为列表格式,并得到G,画出图结构
'''
#将总列表设成全局格式
global gllist
#迭代文件中每个元素
with open(file) as f:
lines = f.readlines()
mylist = [line.strip().split() for line in lines]
gllist = []
#将字符串型转换为整型
for i in mylist:
gllist.append(i[:-2]+map(lambda x: float(x), i[-2:]))
print '初始全局列表:'
print gllist
drawlist=[]
#提取二维列表mylist每行前三个元素,赋给新的列表drawlist
for i in range(len(mylist)):
drawlist.append([])
for j in range(3):
drawlist[i].append(mylist[i][j])
#将列表drawlist加载为有向加权图
G.add_weighted_edges_from(drawlist)
nx.draw(G, with_labels=True, width=1, node_color='y', edge_color='b')
plt.show()
print 'G图中所有节点:',G.nodes()
print 'G图中所有边:',G.edges()
print '\n'
def get_self_node(gllist, target=None):
'''
获取目标节点的自传播节点,返回selflist并包含目标节点
'''
#初始化自传播节点列表
selflist = [target]
#存放已传播节点列表
haslist = []
flag = 0
while (flag != 0):
flag = 0
for target in selflist:
if target not in haslist:
for i in range(len(gllist)):
#判断二维列表中,每行第三个元素是否为1,若为1,则为自传播节点
if ((gllist[i][0] == target)or(gllist[i][1]==target))and(gllist[i][3]==1.0):
if gllist[i][0] == target:
if gllist[i][1] not in haslist:
selflist.append(gllist[i][1])
haslist.append(gllist[i][1])
flag += 1
else:
if gllist[i][0] not in haslist:
selflist.append(gllist[i][0])
haslist.append(gllist[i][0])
flag += 1
#去除重复元素
haslist = set(haslist)
selflist = set(selflist)
#去除重复元素
selflist = set(selflist)
return selflist
def longest_path(gllist,source=None,target=None):
'''
获取起始点到实体的最大路径集合,返回为longestpath列表
'''
longestpath = []
newlist = []
for i in range(len(gllist)):
newlist.append([])
for j in range(3):
newlist[i].append(gllist[i][j])
#构建图结构
G1 = nx.DiGraph()
#添加带权有向边
G1.add_weighted_edges_from(newlist)
#获取目标节点的所有自传播街边,并存入selflist中
selflist = get_self_node(gllist, target)
max_path = 0
val_path = 1
#获取初始节点到目标节点及目标节点的自传播节点的最大路径
for v in selflist:
if v != source:
#遍历两点之间所有路径,并进行比对
for path in nx.all_simple_paths(G1,source=source,target=v):
#判断路径后两个元素是否为相同实体(如:b1->b2)
if is_self_transmit_node(path[-2], v) == 0:
for i in range(0, len(path)-1):
val_path *= G1.get_edge_data(path[i], path[i+1])['weight']
if max_path < val_path:
max_path = val_path
val_path = 1
#若目标节点为起始节点则直接跳出
else: continue ############ 有待商榷 ##############
longestpath.append(max_path)
#返回初始节点到实体的最大路径
return longestpath
def is_self_transmit_node(u, v):
'''
判断目标节点不为起始节点的自传播点
'''
flag = 0
#获得起始节点的所有自传播点
selflist = get_self_node(gllist, v)
for x in selflist:
if u == x:
flag = 1
return flag
def single_strong_infl(longestpath):
'''
计算起始点到实体的传播概率(影响强度),返回影响强度stronginfl
'''
temp = 1
for x in longestpath:
temp *= 1-x
stronginfl = 1-temp
return stronginfl
def all_strong_infl(G):
'''
获得每个节点对实体的影响概率
'''
allstrong = [] #初始化所有节点的加权影响范围列表
gnodes = [] #初始化节点列表
tempnodes = [] #初始化临时节点列表
gnodes = G.nodes()
for u in gnodes:
strong = 0 #存储初始节点对每个实体的影响范围加权,初始化为0
#重置临时节点列表
tempnodes = G.nodes()
for v in tempnodes:
#非自身节点
if u != v:
#判断目标节点不为起始节点的自传播点
if is_self_transmit_node(v, u) == 0:
#获取起始节点到实体间最大加权路径,并存入longestpath
longestpath = longest_path(gllist, u, v)
#去除已遍历目标节点的所有自传播节点
renode = get_self_node(gllist, v)
for x in renode:
if x != v:
tempnodes.remove(x)
#计算起始节点到实体间传播概率(影响强度)
stronginfl = single_strong_infl(longestpath)
strong += stronginfl
#添加单个节点到所有实体的加权影响范围
allstrong.append([u, round(strong, 2)])
#返回每个节点到所有实体的加权影响范围
return allstrong
#output allstrong : [['a1', 2.48], ['a2', 1.6880000000000002], ['b1', 0.7], ['b2', 0], ['c1', 0], ['d2', 0.6]]
def uS_e_uppergain(u, ev, S):
'''
获取节点u在集合S的基础上对实体ev的影响增益, 传入候选节点,上界gain(u|S, ev)
'''
#获取目前实体的所有自传播节点
selflist = get_self_node(gllist, ev)
stronglist = []
#遍历自传遍节点
for v in selflist:
'''
判断节点v是否存在种子集合S中
其中v为单个节点,如v(ev, Gi)
S为种子节点集合,如['a1','a2','b1','b2','c1','d2']
'''
if v in S:
ppSv = 1
else:
longestpath = []
#遍历种子集合
for s in S:
#初始化路径权值与最大路径权值
val_path = 1
max_path = 0
#遍历两点之间所有路径,并进行比对
for path in nx.all_simple_paths(G,source=s,target=v):
#判断路径后两个元素是否为相同实体(如:b1->b2)
if is_self_transmit_node(path[-2], v) == 0:
for i in range(0, len(path)-1):
val_path *= G.get_edge_data(path[i], path[i+1])['weight']
if max_path < val_path:
max_path = val_path
#重置路径权值为1
val_path = 1
#将最大加权路径存入longestpath列表
longestpath.append(max_path)
#得到上界pp(S,v)的影响概率,上界pp(S,v)
ppSv = single_strong_infl(longestpath)
stronglist.append(ppSv)
#得到上界pp(S,ev)的影响概率,上界pp(S,ev)
ppSev = single_strong_infl(stronglist)
#获取pp(u,ev)
ppuev = single_strong_infl(longest_path(gllist, u, ev))
#计算上界gain(u|S,ev)
uSevgain = (1 - ppSev) * ppuev
return uSevgain
def uppergain(u, emu, ems, S):
'''
在已有种子集合S的基础上,求得节点u的影响增益上界,
其中传进参数ems为二维列表,如[['a1',2.48],['a2',1.688]],S则为['a1','a2']
'''
uSgain = 0.0
#遍历emu得到列表形式,得到如['a1',2.48]形式
for ev in emu:
#判断节点是否存在种子集合中
if ev[0] in S:
uSgain += uS_e_uppergain(u, ev[0], S)
else:
uSgain += ev[1]
#返回上界gain(u|S)
return uSgain
def bound_base_imms(G, k):
'''
完全使用影响增益上界的方式选择top-k个种子节点的过程
'''
#初始化emu,H,初始化ems=空集,S=空集
Htemp = []
Htemp = all_strong_infl(G)
H = []
#遍历Htemp=[['a1',2.48],['a2',1.688]],得到如['a1',2.48]形式
for x in Htemp:
#逐个获取二维列表中每一行,形式为['a1',2.48,0]
H.append([x[0],x[1],0])
emu = []
emu = all_strong_infl(G)
ems = []
S = []
for i in range(k):
#提取堆顶元素,tnode的形式为['a1',2.48,0]
tnode = heapq.nlargest(1, H, key=lambda x: x[1])
#将[['b2', 3.1, 0]]格式改为['b2', 3.1, 0]格式
tnode = sum(tnode, [])
while (tnode[2] != i):
gain = 0.0
#获取节点u的影响增益上界
gain = uppergain(tnode, emu, ems, S)
#赋值影响范围
tnode[1] = gain
#修改status
tnode[2] = i
#对堆进行排序
H = heapq.nlargest(len(H), H, key=lambda x: x[1])
#获取堆顶元素
tnode = heapq.nlargest(1, H, key=lambda x: x[1])
tnode = sum(tnode, [])
#添加node到种子集合
S.append([tnode[0]])
#更新ems,添加新节点及节点对每个实体的影响范围加权
ems.append([tnode[0], tnode[1]])
#删除堆顶元素
H.remove(tnode)
print ems
return sum(S, [])
if __name__=='__main__':
#大小为k的种子集合S
k = 60
#加载文件数据,得到图G和初始列表gllist
load_graph('test.txt')
#完全使用影响增益上界值的计算过程函数,打印种子集合S
print '种子集合:',bound_base_imms(G, k)
test.txt
a1 b1 0.2 0
a1 c1 0.8 0
a2 b2 0.4 0
a2 d2 1 0
b1 c1 0.7 0
c2 a2 0.8 0
d2 b2 0.6 0
a1 a2 1 1
a2 a1 0.1 1
....
a1 l1 0.5 0
a1 m1 0.5 0
a1 q1 0.5 0
a1 v1 0.5 0
a1 z1 0.5 0
a1 s1 0.5 0
a1 w1 0.5 0
a1 u1 0.5 0
其中前两列为传播实体,第三列为实体间传播概率,最后一列为0代表同一网络传播,为1代表网络间自传播。
下来要进行优化:
1.采用独立级联模型,设置阈值
2.将最大路径改为最短路径,利用log
㈡ 如何用 python 分析网站日志
日志的记录
Python有一个logging模块,可以用来产生日志。
(1)学习资料
http://blog.sina.com.cn/s/blog_4b5039210100f1wv.html
http://blog.donews.com/limodou/archive/2005/02/16/278699.aspx
http://kenby.iteye.com/blog/1162698
http://blog.csdn.NET/fxjtoday/article/details/6307285
前边几篇文章仅仅是其它人的简单学习经验,下边这个链接中的内容比较全面。
http://www.red-dove.com/logging/index.html
(2)我需要关注内容
日志信息输出级别
logging模块提供了多种日志级别,如:NOTSET(0),DEBUG(10),
INFO(20),WARNING(30),WARNING(40),CRITICAL(50)。
设置方法:
logger = getLogger()
logger.serLevel(logging.DEBUG)
日志数据格式
使用Formatter设置日志的输出格式。
设置方法:
logger = getLogger()
handler = loggingFileHandler(XXX)
formatter = logging.Formatter("%(asctime)s %(levelname) %(message)s","%Y-%m-%d,%H:%M:%S")
%(asctime)s表示记录日志写入时间,"%Y-%m-%d,%H:%M:%S“设定了时间的具体写入格式。
%(levelname)s表示记录日志的级别。
%(message)s表示记录日志的具体内容。
日志对象初始化
def initLog():
logger = logging.getLogger()
handler = logging.FileHandler("日志保存路径")
formatter = logging.Formatter("%(asctime)s %(levelname) %(message)s","%Y-%m-%d,%H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel
写日志
logging.getLogger().info(), logging.getLogger().debug()......
2. 日志的分析。
(1)我的日志的内容。(log.txt)
2011-12-12,12:11:31 INFO Client1: 4356175.0 1.32366309133e+12 1.32366309134e+12
2011-12-12,12:11:33 INFO Client1: 4361320.0 1.32366309334e+12 1.32366309336e+12
2011-12-12,12:11:33 INFO Client0: 4361320.0 1.32366309389e+12 1.32366309391e+12
2011-12-12,12:11:39 INFO Client1: 4366364.0 1.32366309934e+12 1.32366309936e+12
2011-12-12,12:11:39 INFO Client0: 4366364.0 1.32366309989e+12 1.32366309991e+12
2011-12-12,12:11:43 INFO Client1: 4371416.0 1.32366310334e+12 1.32366310336e+12
2011-12-12,12:11:43 INFO Client0: 4371416.0 1.32366310389e+12 1.32366310391e+12
2011-12-12,12:11:49 INFO Client1: 4376450.0 1.32366310934e+12 1.32366310936e+12
我需要将上述内容逐行读出,并将三个时间戳提取出来,然后将其图形化。
(2) 文件操作以及字符串的分析。
打开文件,读取出一行日志。
file = file("日志路径",“r”)
while True:
line = file.readline()
if len(len) == 0:
break;
print line
file.close()
从字符串中提取数据。
字符串操作学习资料:
http://reader.you.com/sharelite?itemId=-4646262544179865983&method=viewSharedItemThroughLink&sharedBy=-1137845767117085734
从上面展示出来的日志内容可见,主要数据都是用空格分隔,所以需要使用字符串的
split函数对字符串进行分割:
paraList = line.split(),该函数默认的分割符是空格,返回值为一个list。
paraList[3], paraList[4], paraList[5]中分别以字符串形式存储着我需要的时间戳。
使用float(paraList[3])将字符串转化为浮点数。
(3)将日志图形化。
matplotlib是python的一个绘图库。我打算用它来将日志图形化。
matplotlib学习资料。
matplotlib的下载与安装:
http://yexin218.iteye.com/blog/645894
http://blog.csdn.Net/sharkw/article/details/1924949
对matplotlib的宏观介绍:
http://apps.hi..com/share/detail/21928578
对matplotlib具体使用的详细介绍:
http://blog.sina.com.cn/s/blog_4b5039210100ie6a.html
在matplotlib中设置线条的颜色和形状:
http://blog.csdn.net/kkxgx/article/details/python
如果想对matplotlib有一个全面的了解,就需要阅读教程《Matplotlib for Python developers》,教程下载地址:
http://download.csdn.net/detail/nmgfrank/4006691
使用实例
import matplotlib.pyplot as plt
listX = [] #保存X轴数据
listY = [] #保存Y轴数据
listY1 = [] #保存Y轴数据
file = file("../log.txt","r")#打开日志文件
while True:
line = file.readline()#读取一行日志
if len(line) == 0:#如果到达日志末尾,退出
break
paraList = line.split()
print paraList[2]
print paraList[3]
print paraList[4]
print paraList[5]
if paraList[2] == "Client0:": #在坐标图中添加两个点,它们的X轴数值是相同的
listX.append(float(paraList[3]))
listY.append(float(paraList[5]) - float(paraList[3]))
listY1.append(float(paraList[4]) - float(paraList[3]))
file.close()
plt.plot(listX,listY,'bo-',listX,listY1,'ro')#画图
plt.title('tile')#设置所绘图像的标题
plt.xlabel('time in sec')#设置x轴名称
plt.ylabel('delays in ms'')#设置y轴名称
plt.show()
㈢ 怎样用python实现深度学习
基于Python的深度学习库、深度学习方向、机器学习方向、自然语言处理方向的一些网站基本都是通过Python来实现的。
机器学习,尤其是现在火爆的深度学习,其工具框架大都提供了Python接口。Python在科学计算领域一直有着较好的声誉,其简洁清晰的语法以及丰富的计算工具,深受此领域开发者喜爱。
早在深度学习以及Tensorflow等框架流行之前,Python中即有scikit-learn,能够很方便地完成几乎所有机器学习模型,从经典数据集下载到构建模型只需要简单的几行代码。配合Pandas、matplotlib等工具,能很简单地进行调整。
而Tensorflow、PyTorch、MXNet、Keras等深度学习框架更是极大地拓展了机器学习的可能。使用Keras编写一个手写数字识别的深度学习网络仅仅需要寥寥数十行代码,即可借助底层实现,方便地调用包括GPU在内的大量资源完成工作。
值得一提的是,无论什么框架,Python只是作为前端描述用的语言,实际计算则是通过底层的C/C++实现。由于Python能很方便地引入和使用C/C++项目和库,从而实现功能和性能上的扩展,这样的大规模计算中,让开发者更关注逻辑于数据本身,而从内存分配等繁杂工作中解放出来,是Python被广泛应用到机器学习领域的重要原因。
㈣ 有大神会用python做网络评论文本的情感分析么有偿
这个自学一会就会了,给你一个模型,自己研究一下,没那么难。
importjieba
importnltk.classify.util
fromnltk.
fromnltk.corpusimportnames
defword_feats(words):
returndict([(word,True)forwordinwords])
text1=open(r"积极.txt","r").read()
seg_list=jieba.cut(text1)
result1="".join(seg_list)
text2=open(r"消极.txt","r").read()
seg_list=jieba.cut(text2)
result2="".join(seg_list)
#数据准备
positive_vocab=result1
negative_vocab=result2
#特征提取
positive_features=[(word_feats(pos),'pos')forposinpositive_vocab]
negative_features=[(word_feats(neg),'neg')forneginnegative_vocab]
train_set=negative_features+positive_features
#训练模型
classifier=NaiveBayesClassifier.train(train_set)
#实战测试
neg=0
pos=0
sentence=input("请输入一句你喜欢的话:")
sentence=sentence.lower()
seg_list=jieba.cut(sentence)
result1="".join(seg_list)
words=result1.split("")
forwordinwords:
classResult=classifier.classify(word_feats(word))
ifclassResult=='neg':
neg=neg+1
ifclassResult=='pos':
pos=pos+1
print('积极:'+str(float(pos)/len(words)))
print('消极:'+str(float(neg)/len(words)))
㈤ python 怎样进行社会网络分析
就目前来说python毕竟是一门脚本语言,很多企业不会直接招会Python的人。最多会说,招C++或者C#或者。。。然后最后补上一句,熟悉python为佳!
㈥ 如何使用python进行社交网络分析
建议在知乎上问,那里高手多,而且可能会有n个大神很详细地回答。
㈦ 想学习python中的networkx做复杂网络分析应该看那本啊 求介绍
跟楼主遇到的问题一样,找了很多python的书,没有详细介绍networkx,只能看下networkx文档了,http://networkx.github.io/documentation/latest/index.html。
另外这上面有一些networkx的学习笔记,可以借鉴。http://wenku..com/link?url=-vZ25Tkio_
㈧ 如何用python分析网站日志
#coding:utf-8
#file: FileSplit.py
import os,os.path,time
def FileSplit(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
number = 100000 #每个小文件中保存100000条数据
dataLine = sFile.readline()
tempData = [] #缓存列表
fileNum = 1
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
for row in range(number):
tempData.append(dataLine) #将一行数据添加到列表中
dataLine = sFile.readline()
if not dataLine :
break
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tempData) #将列表保存到文件中
tFile.close()
tempData = [] #清空缓存列表
print(tFilename + " 创建于: " + str(time.ctime()))
fileNum += 1 #文件编号
sFile.close()
if __name__ == "__main__" :
FileSplit("access.log","access")
#coding:utf-8
#file: Map.py
import os,os.path,re
def Map(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
dataLine = sFile.readline()
tempData = {} #缓存列表
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
p_re = re.compile(r'(GET|POST)\s(.*?)\sHTTP/1.[01]',re.IGNORECASE) #用正则表达式解析数据
match = p_re.findall(dataLine)
if match:
visitUrl = match[0][1]
if visitUrl in tempData:
tempData[visitUrl] += 1
else:
tempData[visitUrl] = 1
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Map("access\\access.log1.txt","access")
Map("access\\access.log2.txt","access")
Map("access\\access.log3.txt","access")
#coding:utf-8
#file: Rece.py
import os,os.path,re
def Rece(sourceFolder, targetFile):
tempData = {} #缓存列表
p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正则表达式解析数据
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #是rece文件
sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')
dataLine = sFile.readline()
while dataLine: #有数据
subdata = p_re.findall(dataLine) #用空格分割数据
#print(subdata[0][0]," ",subdata[0][1])
if subdata[0][0] in tempData:
tempData[subdata[0][0]] += int(subdata[0][1])
else:
tempData[subdata[0][0]] = int(subdata[0][1])
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Rece("access","access")
㈨ 如何用python进行大数据挖掘和分析
毫不夸张地说,大数据已经成为任何商业交流中不可或缺的一部分。桌面和移动搜索向全世界的营销人员和公司以空前的规模提供着数据,并且随着物联网的到来,大量用以消费的数据还会呈指数级增长。这种消费数据对于想要更好地定位目标客户、弄懂人们怎样使用他们的产品或服务,并且通过收集信息来提高利润的公司来说无疑是个金矿。
筛查数据并找到企业真正可以使用的结果的角色落到了软件开发者、数据科学家和统计学家身上。现在有很多工具辅助大数据分析,但最受欢迎的就是Python。
为什么选择Python?
Python最大的优点就是简单易用。这个语言有着直观的语法并且还是个强大的多用途语言。这一点在大数据分析环境中很重要,并且许多企业内部已经在使用Python了,比如Google,YouTube,迪士尼,和索尼梦工厂。还有,Python是开源的,并且有很多用于数据科学的类库。所以,大数据市场急需Python开发者,不是Python开发者的专家也可以以相当块速度学习这门语言,从而最大化用在分析数据上的时间,最小化学习这门语言的时间。
用Python进行数据分析之前,你需要从Continuum.io下载Anaconda。这个包有着在Python中研究数据科学时你可能需要的一切东西。它的缺点是下载和更新都是以一个单元进行的,所以更新单个库很耗时。但这很值得,毕竟它给了你所需的所有工具,所以你不需要纠结。
现在,如果你真的要用Python进行大数据分析的话,毫无疑问你需要成为一个Python开发者。这并不意味着你需要成为这门语言的大师,但你需要了解Python的语法,理解正则表达式,知道什么是元组、字符串、字典、字典推导式、列表和列表推导式——这只是开始。
各种类库
当你掌握了Python的基本知识点后,你需要了解它的有关数据科学的类库是怎样工作的以及哪些是你需要的。其中的要点包括NumPy,一个提供高级数学运算功能的基础类库,SciPy,一个专注于工具和算法的可靠类库,Sci-kit-learn,面向机器学习,还有Pandas,一套提供操作DataFrame功能的工具。
除了类库之外,你也有必要知道Python是没有公认的最好的集成开发环境(IDE)的,R语言也一样。所以说,你需要亲手试试不同的IDE再看看哪个更能满足你的要求。开始时建议使用IPython Notebook,Rodeo和Spyder。和各种各样的IDE一样,Python也提供各种各样的数据可视化库,比如说Pygal,Bokeh和Seaborn。这些数据可视化工具中最必不可少的就是Matplotlib,一个简单且有效的数值绘图类库。
所有的这些库都包括在了Anaconda里面,所以下载了之后,你就可以研究一下看看哪些工具组合更能满足你的需要。用Python进行数据分析时你会犯很多错误,所以得小心一点。一旦你熟悉了安装设置和每种工具后,你会发现Python是目前市面上用于大数据分析的最棒的平台之一。
希望能帮到你!