-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabc_1.py
More file actions
156 lines (119 loc) · 5.51 KB
/
abc_1.py
File metadata and controls
156 lines (119 loc) · 5.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
'''
import numpy as np
import pandas as pd
import networkx as nx
import random
import matplotlib.pyplot as plt
import scipy as sp
# Step 1: Read the CSV file
data = pd.read_csv('modified_impression_network.csv')
# Step 2: Create a directed graph
G = nx.DiGraph()
for index, row in data.iterrows():
source = row.iloc[0] # Assuming the first column is the source node
targets = row.iloc[1:].dropna().tolist() # Assuming the rest are target nodes
G.add_node(source) # Add source node if not already added
for target in targets:
G.add_edge(source, target)
def predict_missing_edges(adj_matrix):
predicted_weights = np.zeros_like(adj_matrix, dtype=float)
missing_links = []# Initialize array for predicted weights
for i in range(adj_matrix.shape[0]):
for j in range(adj_matrix.shape[1]):
if adj_matrix[i, j] == 0:
predicted_edge_weight = predict_missing_edge(adj_matrix, i, j)
if predicted_edge_weight > 0.5:
missing_links.append((i, j))
# Add edge if predicted weight is greater than 0.5
G.add_edge(i, j)
predicted_weights[i, j] = predicted_edge_weight
else:
predicted_weights[i, j] = adj_matrix[i, j]
return predicted_weights, missing_links
def predict_missing_edge(adj_matrix, missing_edge_row, missing_edge_col):
# Remove the corresponding row and column
reduced_matrix = np.delete(np.delete(adj_matrix, missing_edge_row, axis=0), missing_edge_col, axis=1)
# Extract the removed column
removed_column = adj_matrix[:, missing_edge_col]
removed_column = np.delete(removed_column, missing_edge_row, axis=0)
# Append a column of ones to the reduced matrix
reduced_matrix_with_ones = np.column_stack((reduced_matrix, np.ones(reduced_matrix.shape[0])))
# Perform least squares approximation
coefficients = np.linalg.lstsq(reduced_matrix_with_ones, removed_column, rcond=None)[0]
# Predict the missing edge weight
predicted_edge_weight = np.dot((adj_matrix[missing_edge_row, :]), coefficients)
return predicted_edge_weight
# Example adjacency matrix
adjacency_matrix = nx.adjacency_matrix(G).todense()
predicted_weights = predict_missing_edges(adjacency_matrix)
pagerank_scores = nx.pagerank(G)
# Find the top 10 leaders using PageRank
top_leaders_pagerank = sorted(pagerank_scores.items(), key=lambda x: x[1], reverse=True)[:10]
print("\nTop 10 Leaders (PageRank):")
for leader, score in top_leaders_pagerank:
print(f"Node: {leader}, PageRank Score: {score}")
for link in missing_links:
print(f"Missing Link: {link}")
'''
import numpy as np
import pandas as pd
import networkx as nx
# Step 1: Read the CSV file
data = pd.read_csv('modified_impression_network.csv')
# Step 2: Create a directed graph
G = nx.DiGraph()
for index, row in data.iterrows():
source = row.iloc[0] # Assuming the first column is the source node
targets = row.iloc[1:].dropna().tolist() # Assuming the rest are target nodes
G.add_node(source) # Add source node if not already added
for target in targets:
G.add_edge(source, target)
def predict_missing_edges(adj_matrix):
predicted_weights = np.zeros_like(adj_matrix, dtype=float)
missing_links = [] # Initialize array for predicted weights
total = adj_matrix.shape[0]*adj_matrix.shape[1]
done = 0
loaded = -1
for i in range(adj_matrix.shape[0]):
for j in range(adj_matrix.shape[1]):
done += 1
if adj_matrix[i, j] == 0:
predicted_edge_weight = predict_missing_edge(adj_matrix, i, j)
if predicted_edge_weight > 0.5:
missing_links.append((i, j))
# Add edge if predicted weight is greater than 0.5
G.add_edge(i, j)
predicted_weights[i, j] = predicted_edge_weight
else:
predicted_weights[i, j] = adj_matrix[i, j]
load = int(100*done/total)
if load > loaded:
print("Completed:", load, "%")
loaded = load
return predicted_weights, missing_links
def predict_missing_edge(adj_matrix, missing_edge_row, missing_edge_col):
# Remove the corresponding row and column
reduced_matrix = np.delete(np.delete(adj_matrix, missing_edge_row, axis=0), missing_edge_col, axis=1)
# Extract the removed column
removed_column = adj_matrix[:, missing_edge_col]
removed_column = np.delete(removed_column, missing_edge_row, axis=0)
# Append a column of ones to the reduced matrix
reduced_matrix_with_ones = np.column_stack((reduced_matrix, np.ones(reduced_matrix.shape[0])))
# Perform least squares approximation
coefficients = np.linalg.lstsq(reduced_matrix_with_ones, removed_column, rcond=None)[0]
# Predict the missing edge weight
predicted_edge_weight = np.dot((adj_matrix[missing_edge_row, :]), coefficients)
return predicted_edge_weight
# Example adjacency matrix
adjacency_matrix = nx.adjacency_matrix(G).todense()
predicted_weights, missing_links = predict_missing_edges(adjacency_matrix)
pagerank_scores = nx.pagerank(G)
# Find the top 10 leaders using PageRank
top_leaders_pagerank = sorted(pagerank_scores.items(), key=lambda x: x[1], reverse=True)[:10]
print("\nTop 10 Leaders (PageRank):")
for leader, score in top_leaders_pagerank:
print(f"Node: {leader}, PageRank Score: {score}")
# Print missing links
print("\nMissing Links:")
for link in missing_links:
print(f"Missing Link: {link}")