1 year ago
#54480
tous
Convert python functions (shortestpath/ prediction function using nx.adamic_adar_index) into API
So in this project im trying to find the link prediction in the social networks.
I have done my test with some of the algorithms, and I decided to work with the Adamic radar algorithm.
And I wanted to do an HTML interface to get the prediction in.
so I dunno how to convert the python function into APIs, I tried with fastApi but nothing happened.
Can you please help me?
So here is my code.
import numpy as np
import random
import networkx as nx
from tqdm import tqdm
import re
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
from sklearn.metrics import roc_auc_score
# load nodes details
with open("/content/drive/MyDrive/fb-pages-food.nodes") as f:
fb_nodes = f.read().splitlines()
# load edges (or links)
with open("/content/drive/MyDrive/fb-pages-food.edges") as f:
fb_links = f.read().splitlines()
len(fb_nodes), len(fb_links)
# capture nodes in 2 separate lists
node_list_1 = []
node_list_2 = []
for i in tqdm(fb_links):
node_list_1.append(i.split(',')[0])
node_list_2.append(i.split(',')[1])
fb_df = pd.DataFrame({'node_1': node_list_1, 'node_2': node_list_2})
# create graph
G = nx.from_pandas_edgelist(fb_df, "node_1", "node_2")
# plot graph
plt.figure(figsize=(10,10))
pos = nx.random_layout(G, seed=23)
nx.draw(G, with_labels=True, pos = pos, node_size = 280, alpha = 0.6, width = 1)
from networkx.algorithms.shortest_paths.weighted import dijkstra_path
def dijkstrapath(source,target):
print('Returns the shortest path from source to target in a weighted graph G')
if (source and target) in G:
x = dijkstra_path(G , source= source, target= target, weight="weight")
print(x)
# else:
# print('nodes are not in the graph')
dij = dijkstrapath('0','54')
dij
# Remove 20% of the edges
proportion_edges = 0.2
edge_subset = random.sample(G.edges(), int(proportion_edges * G.number_of_edges()))
# Create a copy of the graph and remove the edges
G_train = G.copy()
G_train.remove_edges_from(edge_subset)
# Prediction using Adamic Adar
pred_adamic = list(nx.adamic_adar_index(G_train))
score_adamic, label_adamic = zip(*[(s, (u,v) in edge_subset) for (u,v,s) in pred_adamic])
pred_adamic*100
** so this is the function that I want to use in my HTML so I guess I need it as an API. HOW TO DO THIS . **
**BUT IF OF COURSE THERE IS ANOTHER IDEA PLEASE TELL ME, I AM A BEGINNER **
# Prediction using Adamic Adar
def prediction__(u,v):
if u in G and v in G:
preds = nx.adamic_adar_index(G, [(u, v)])
for u, v, p in preds:
print('(%d, %d) -> %.8f' % (u, v, p))
else:
print('nodes not found')
this what I have done in fastAPI but nothing works of course because it's wrong
from fastapi import FastAPI , Response, status
from colabcode import ColabCode
from pydantic import BaseModel
# Modeling
app = FastAPI(title="Link Prediction",
description="Prediction Model of Future Connections between Facebook Pages",
version="1.0")
app = FastAPI()
# class allNodes(BaseModel):
# node1: int
# node2 : int
# prediction = {}
@app.get("/")
def read_root():
return {"Hello": "World"}
# @app.get("/prediction")
# async def get_prediction(Node1, Node2) -> allNodes:
# if Node1 and Node2 in G:
# preds = nx.adamic_adar_index(G, Node1, Node2)
# for Node1, Node2, p in preds:
# print('(%d, %d) -> %.8f' % (Node1, Node2, p))
@app.get("/shortPath")
def dijkstrapath(source,target):
if (source and target) in G:
x = dijkstra_path(G , source= source, target= target, weight="weight")
return x
THANK YOU IN ADVANCE FOR YOUR HELP
python
graph
graph-algorithm
prediction
shortest-path
0 Answers
Your Answer