arminmehrabian
commited on
Update README.md
Browse filesAdded load to pyG script.
README.md
CHANGED
@@ -219,3 +219,104 @@ To load the Cypher script, execute it directly using a command-line interface fo
|
|
219 |
```bash
|
220 |
neo4j-shell -file path/to/graph.cypher
|
221 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
219 |
```bash
|
220 |
neo4j-shell -file path/to/graph.cypher
|
221 |
```
|
222 |
+
|
223 |
+
### 4. Loading the Knowledge Graph into PyTorch Geometric (PyG)
|
224 |
+
|
225 |
+
This knowledge graph can be loaded into PyG (PyTorch Geometric) for further processing, analysis, or model training. Below is an example script that shows how to load the JSON data into a PyG-compatible `HeteroData` object.
|
226 |
+
|
227 |
+
The script first reads the JSON data, processes nodes and relationships, and then loads everything into a `HeteroData` object for use with PyG.
|
228 |
+
|
229 |
+
```python
|
230 |
+
import json
|
231 |
+
import torch
|
232 |
+
from torch_geometric.data import HeteroData
|
233 |
+
from collections import defaultdict
|
234 |
+
|
235 |
+
# Load JSON data from file
|
236 |
+
file_path = "path/to/graph.json" # Replace with your actual file path
|
237 |
+
graph_data = []
|
238 |
+
with open(file_path, "r") as f:
|
239 |
+
for line in f:
|
240 |
+
try:
|
241 |
+
graph_data.append(json.loads(line))
|
242 |
+
except json.JSONDecodeError as e:
|
243 |
+
print(f"Error decoding JSON line: {e}")
|
244 |
+
continue
|
245 |
+
|
246 |
+
# Initialize HeteroData object
|
247 |
+
data = HeteroData()
|
248 |
+
|
249 |
+
# Mapping for node indices per node type
|
250 |
+
node_mappings = defaultdict(dict)
|
251 |
+
|
252 |
+
# Temporary storage for properties to reduce concatenation cost
|
253 |
+
node_properties = defaultdict(lambda: defaultdict(list))
|
254 |
+
edge_indices = defaultdict(lambda: defaultdict(list))
|
255 |
+
|
256 |
+
# Process each item in the loaded JSON data
|
257 |
+
for item in graph_data:
|
258 |
+
if item['type'] == 'node':
|
259 |
+
node_type = item['labels'][0] # Assuming first label is the node type
|
260 |
+
node_id = item['id']
|
261 |
+
properties = item['properties']
|
262 |
+
|
263 |
+
# Store the node index mapping
|
264 |
+
node_index = len(node_mappings[node_type])
|
265 |
+
node_mappings[node_type][node_id] = node_index
|
266 |
+
|
267 |
+
# Store properties temporarily by type
|
268 |
+
for key, value in properties.items():
|
269 |
+
if isinstance(value, list) and all(isinstance(v, (int, float)) for v in value):
|
270 |
+
node_properties[node_type][key].append(torch.tensor(value, dtype=torch.float))
|
271 |
+
elif isinstance(value, (int, float)):
|
272 |
+
node_properties[node_type][key].append(torch.tensor([value], dtype=torch.float))
|
273 |
+
else:
|
274 |
+
node_properties[node_type][key].append(value) # non-numeric properties as lists
|
275 |
+
|
276 |
+
elif item['type'] == 'relationship':
|
277 |
+
start_type = item['start']['labels'][0]
|
278 |
+
end_type = item['end']['labels'][0]
|
279 |
+
start_id = item['start']['id']
|
280 |
+
end_id = item['end']['id']
|
281 |
+
edge_type = item['label']
|
282 |
+
|
283 |
+
# Map start and end node indices
|
284 |
+
start_idx = node_mappings[start_type][start_id]
|
285 |
+
end_idx = node_mappings[end_type][end_id]
|
286 |
+
|
287 |
+
# Append to edge list
|
288 |
+
edge_indices[(start_type, edge_type, end_type)]['start'].append(start_idx)
|
289 |
+
edge_indices[(start_type, edge_type, end_type)]['end'].append(end_idx)
|
290 |
+
|
291 |
+
# Finalize node properties by batch processing
|
292 |
+
for node_type, properties in node_properties.items():
|
293 |
+
data[node_type].num_nodes = len(node_mappings[node_type])
|
294 |
+
for key, values in properties.items():
|
295 |
+
if isinstance(values[0], torch.Tensor):
|
296 |
+
data[node_type][key] = torch.stack(values)
|
297 |
+
else:
|
298 |
+
data[node_type][key] = values # Keep non-tensor properties as lists
|
299 |
+
|
300 |
+
# Finalize edge indices in bulk
|
301 |
+
for (start_type, edge_type, end_type), indices in edge_indices.items():
|
302 |
+
edge_index = torch.tensor([indices['start'], indices['end']], dtype=torch.long)
|
303 |
+
data[start_type, edge_type, end_type].edge_index = edge_index
|
304 |
+
|
305 |
+
# Display statistics for verification
|
306 |
+
print("Nodes and Properties:")
|
307 |
+
for node_type in data.node_types:
|
308 |
+
print(f"\nNode Type: {node_type}")
|
309 |
+
print(f"Number of Nodes: {data[node_type].num_nodes}")
|
310 |
+
for key, value in data[node_type].items():
|
311 |
+
if key != 'num_nodes':
|
312 |
+
if isinstance(value, torch.Tensor):
|
313 |
+
print(f" - {key}: {value.shape}")
|
314 |
+
else:
|
315 |
+
print(f" - {key}: {len(value)} items (non-numeric)")
|
316 |
+
|
317 |
+
print("\nEdges and Types:")
|
318 |
+
for edge_type in data.edge_types:
|
319 |
+
edge_index = data[edge_type].edge_index
|
320 |
+
print(f"Edge Type: {edge_type} - Number of Edges: {edge_index.size(1)} - Shape: {edge_index.shape}")
|
321 |
+
|
322 |
+
```
|