一、基本内容
链接
: 《数据挖掘》第七课笔记
二、code
题目
1.H矩阵
def to_H(self):
'''
H=np.zeros((self.n,self.n))
out_list=np.sum(self.start, axis=0)
for j in range(self.n):
for i in range(self.n):
if self.start[i][j] ==1:
H[i][j] = 1 / out_list[j]
'''
out_list = np.sum(self.start, axis=0)
H = np.where(out_list == 0, 0, self.start / out_list)
return H
2.A矩阵
# 求A矩阵
def to_A(self,H):
A=np.zeros((self.n,self.n))
a = 1 / n
for i in range(self.n):
if np.all(H[:, i] == 0):
A[:,i]=a
'''
return np.where(np.all(H == 0, axis=0), 1 / self.n, 0)
'''
return A
3.S矩阵
S = H+A
4.G矩阵
def to_G(self,S):
J=np.ones((self.n,self.n))
G=self.alpha*S+(1-self.alpha)*(1/self.n)*J
return G
5.幂法求解特征向量
'''
# 幂法求解主特征向量
def mifa(self,G):
x = np.ones((n, 1))/n
for i in range(self.epoch):
x_temp = np.dot(G, x)
if np.linalg.norm(x_temp - x) < 1e-8:
break
x=x_temp
return x
'''
# 幂法求解主特征向量
def mifa(self,G):
x = np.ones((n, 1))
for i in range(self.epoch):
x_temp = np.dot(G, x)
norm = np.linalg.norm(x_temp)#计算2范数,计算向量长度
if norm != 0:
x_temp= x_temp / norm
if np.linalg.norm(x_temp - x) < 1e-8:
break
x=x_temp
return x
'''
6.整体代码
import numpy as np
class important():
def __init__(self,start,n):
self.start=start
self.n=n
self.alpha=0.85
self.epoch=10000
pass
#求H矩阵
def to_H(self):
'''
H=np.zeros((self.n,self.n))
out_list=np.sum(self.start, axis=0)
for j in range(self.n):
for i in range(self.n):
if self.start[i][j] ==1:
H[i][j] = 1 / out_list[j]
'''
out_list = np.sum(self.start, axis=0)
H = np.where(out_list == 0, 0, self.start / out_list)
return H
# 求A矩阵
def to_A(self,H):
A=np.zeros((self.n,self.n))
a = 1 / n
for i in range(self.n):
if np.all(H[:, i] == 0):
A[:,i]=a
'''
return np.where(np.all(H == 0, axis=0), 1 / self.n, 0)
'''
return A
#求G矩阵
def to_G(self,S):
J=np.ones((self.n,self.n))
G=self.alpha*S+(1-self.alpha)*(1/self.n)*J
return G
# 幂法求解主特征向量
def mifa(self,G):
x = np.ones((n, 1))/n
for i in range(self.epoch):
x_temp = np.dot(G, x)
if np.linalg.norm(x_temp - x) < 1e-8:
break
x=x_temp
return x
'''
# 幂法求解主特征向量
def mifa(self,G):
x = np.ones((n, 1))
for i in range(self.epoch):
x_temp = np.dot(G, x)
norm = np.linalg.norm(x_temp)#计算2范数,计算向量长度
if norm != 0:
x_temp= x_temp / norm
if np.linalg.norm(x_temp - x) < 1e-8:
break
x=x_temp
return x
'''
if __name__ == '__main__':
start=[[0,1,1,1,0,0],[0,0,1,1,0,1],[0,0,0,1,0,0],[0,0,1,0,0,1],[0,0,0,0,0,1],[0,1,0,1,0,0]]
start = np.transpose(start)
n = len(start)
important = important(start,n)
H = important.to_H()
A = important.to_A(H)
S = H+A
G = important.to_G(S)
I = important.mifa(G)
print("H Matrix:\n", H)
print("A Matrix:\n", A)
print("S Matrix:\n", S)
print("G Matrix:\n", G)
print("I stable:\n", I)