0% found this document useful (0 votes)
4 views

graph_analysis_code

Uploaded by

Bhavan Gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

graph_analysis_code

Uploaded by

Bhavan Gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

graph_analysis.

py

1 import numpy as np
2 import pandas as pd
3 import networkx as nx
4 from sklearn.metrics import mean_squared_error, r2_score
5 import matplotlib.pyplot as plt
6 from mpl_toolkits.mplot3d import Axes3D
7 import scipy.stats as stats
8 from sklearn.model_selection import train_test_split
9 from sklearn.ensemble import RandomForestRegresso­
r
10
11 def generate_graphs(num_nodes=10):
12 graphs = {
13 "Erdos-Renyi": nx.erdos_renyi_graph(num_nodes, 0.5),
14 "Preferential Attachment": nx.barabasi_albert_grap­
h(num_nodes, 3),
15 "Watts-Strogatz": nx.watts_strogatz_graph­
(num_nodes, 4, 0.1),
16 "1D Lattice": nx.grid_graph(dim=[num_nodes]),
17 }
18 return graphs
19
20 def visualize_and_save(graph, name):
21 pos = nx.spring_layout(graph, dim=3, seed=42)
22 fig = plt.figure()
23 ax = fig.add_subplot(111, projection='3d')
24 for node, (x, y, z) in pos.items():
25 ax.scatter(x, y, z, label=node, s=50)
26 for neighbor in graph.neighbors(node):
27 nx_, ny_, nz_ = pos[neighbor] # Avoid naming conflict
28 ax.plot([x, nx_], [y, ny_], [z, nz_], color='black', alpha=0.5)
29 ax.set_title(name)
30 plt.show()
31
32 adj_matrix = nx.adjacency_matrix(graph).todense()
33 print(f"Adjacency Matrix for {name}:\n", adj_matrix)
34 return adj_matrix
35
36 def create_dataset(graph):
37 features = [
38 (graph.degree[node], nx.clustering(graph, node)) for node in graph.nodes()
39 ]
40 target = [np.random.uniform(0.1, 1.0) for _ in graph.nodes()] # Random target values
41 return pd.DataFrame(features, columns=["Degree", "Clustering"]), np.array(target)
42
43 def train_and_evaluate(graphs):
44 results = {}
45 for name, graph in graphs.items():
46 print(f"\nProcessing {name} graph...")
47
48 adj_matrix = visualize_and_save(graph, name)
49
50 X, y = create_dataset(graph)
51
52 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
53
54 model = RandomForestRegresso­
r(n_estimators=100, random_state=42)
55 model.fit(X_train, y_train)
56
57 y_pred = model.predict(X_test)
58 mse = mean_squared_error(y_test, y_pred)
59 r2 = r2_score(y_test, y_pred)
60
61 _, p_value = stats.ttest_ind(y_test, y_pred)
62
63 results[name] = {
64 "MSE": mse,
65 "R2": r2,
66 "P-value": p_value,
67 "Adjacency Matrix": adj_matrix
68 }
69
70 print(f"Results for {name}: MSE={mse:.4f}, R2={r2:.4f}, P-value={p_value:.4f}")
71
72 return results
73
74 if __name__ == "__main__":
75 graphs = generate_graphs(num_nodes=10)
76
77 results = train_and_evaluate(graphs)
78
79 print("\nORBIT - Orbiter, Radar, Ballistic, Inertial, Trajectory Final Results:")
80 for graph, metrics in results.items():
81 print(f"{graph}: {metrics}")
82

You might also like