Synthetic dataset of text attribute graph data, compiled by Du Enjun
Browse filesFiles changed (20)
- .gitattributes+5
- .gitattributes copyAdded+59
- Children.jsonAdded+3
- History.jsonAdded+3
- README copy.mdAdded+3
- SubChildren.jsonAdded
- SubCiteseer.jsonAdded
- SubCora.jsonAdded
- SubHistory.jsonAdded
- SubWikics.jsonAdded
- Subarxiv2023.jsonAdded
- arxiv2023.jsonAdded+3
- citeseer.jsonAdded
- cora.jsonAdded
- data_clear.pyAdded+52
- data_statistics.pyAdded+67
- few_shot.pyAdded+77
- sample.pyAdded+396
- wikics.jsonAdded+3
- wikics_cleaned.jsonAdded+3
56 unmodified lines57585956 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text56 unmodified lines575859606162636456 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textChildren.json filter=lfs diff=lfs merge=lfs -textHistory.json filter=lfs diff=lfs merge=lfs -textarxiv2023.json filter=lfs diff=lfs merge=lfs -textwikics.json filter=lfs diff=lfs merge=lfs -textwikics_cleaned.json filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859*.7z filter=lfs diff=lfs merge=lfs -text
*.arrow filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.ckpt filter=lfs diff=lfs merge=lfs -text
*.ftz filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.h5 filter=lfs diff=lfs merge=lfs -text
*.joblib filter=lfs diff=lfs merge=lfs -text
*.lfs.* filter=lfs diff=lfs merge=lfs -text
*.lz4 filter=lfs diff=lfs merge=lfs -text
*.mds filter=lfs diff=lfs merge=lfs -text
*.mlmodel filter=lfs diff=lfs merge=lfs -text
*.model filter=lfs diff=lfs merge=lfs -text
*.msgpack filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.ot filter=lfs diff=lfs merge=lfs -text
*.parquet filter=lfs diff=lfs merge=lfs -text
*.pb filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.pt filter=lfs diff=lfs merge=lfs -text
*.pth filter=lfs diff=lfs merge=lfs -text
*.rar filter=lfs diff=lfs merge=lfs -text
*.safetensors filter=lfs diff=lfs merge=lfs -text
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.tar.* filter=lfs diff=lfs merge=lfs -text
*.tar filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text
*.tgz filter=lfs diff=lfs merge=lfs -text
*.wasm filter=lfs diff=lfs merge=lfs -text
*.xz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
# Audio files - uncompressed
*.pcm filter=lfs diff=lfs merge=lfs -text
*.sam filter=lfs diff=lfs merge=lfs -text
*.raw filter=lfs diff=lfs merge=lfs -text
# Audio files - compressed
*.aac filter=lfs diff=lfs merge=lfs -text
*.flac filter=lfs diff=lfs merge=lfs -text
*.mp3 filter=lfs diff=lfs merge=lfs -text
*.ogg filter=lfs diff=lfs merge=lfs -text
*.wav filter=lfs diff=lfs merge=lfs -text
# Image files - uncompressed
*.bmp filter=lfs diff=lfs merge=lfs -text
*.gif filter=lfs diff=lfs merge=lfs -text
*.png filter=lfs diff=lfs merge=lfs -text
*.tiff filter=lfs diff=lfs merge=lfs -text
# Image files - compressed
*.jpg filter=lfs diff=lfs merge=lfs -text
*.jpeg filter=lfs diff=lfs merge=lfs -text
*.webp filter=lfs diff=lfs merge=lfs -text
# Video files - compressed
*.mp4 filter=lfs diff=lfs merge=lfs -text
*.webm filter=lfs diff=lfs merge=lfs -text123version https://git-lfs.github.com/spec/v1oid sha256:3bbfa9e9ddf60d5bde95425c1713dde2087224bd1080e9e1b2c7a8087c286097size 125909900123version https://git-lfs.github.com/spec/v1oid sha256:0226010aa829e8f2f723bc625920e92d7cd462d1a628f5479f0ea672f90531e8size 68660141123---
license: mit
---123version https://git-lfs.github.com/spec/v1oid sha256:ae1fb88d617182abedf2c8a01dd54288471499e0c2921a7c39981d86bafb31dasize 6648758712345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import json
def clean_graph_data(input_file, output_file):
"""
Clean graph data by removing nodes with mask="None", ensuring sequential node_ids,
and updating all neighbor references accordingly.
"""
# Load the JSON data
with open(input_file, 'r', encoding='utf-8') as f:
data = json.load(f)
# Identify valid nodes (mask != "None") and their IDs
valid_nodes = []
valid_node_ids = set()
for node in data:
if 'mask' in node and node['mask'] != "None":
valid_nodes.append(node)
valid_node_ids.add(node['node_id'])
# Create mapping from old node_id to new node_id
old_to_new_mapping = {}
new_id = 0
for node in sorted(valid_nodes, key=lambda x: x['node_id']):
old_to_new_mapping[node['node_id']] = new_id
new_id += 1
# Update node_ids and neighbors based on the mapping
for node in valid_nodes:
# Update neighbors first (while node_id is still the old one)
new_neighbors = []
for neighbor in node['neighbors']:
if neighbor in valid_node_ids: # Only keep neighbors that weren't removed
new_neighbors.append(old_to_new_mapping[neighbor])
node['neighbors'] = new_neighbors
# Update node_id
node['node_id'] = old_to_new_mapping[node['node_id']]
# Sort nodes by new node_id for better readability
valid_nodes.sort(key=lambda x: x['node_id'])
# Save the cleaned data
with open(output_file, 'w') as f:
json.dump(valid_nodes, f, indent=2)
return f"Successfully cleaned the graph data. Removed {len(data) - len(valid_nodes)} nodes with mask='None'."
# Usage
result = clean_graph_data('wikics.json', 'wikics_cleaned.json')
print(result)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import json
import networkx as nx
import community as community_louvain # You may need to install this package using: pip install python-louvain
def main():
# Load the JSON file
with open('arxiv2023_1624-10.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# Initialize counters and sets
nodes_count = len(data)
classes = set()
train_nodes_count = 0
validation_nodes_count = 0
test_nodes_count = 0
# Build an undirected graph
G = nx.Graph()
# Iterate over each element in the dataset
for entry in data:
node_id = entry['node_id']
label = entry['label']
mask = entry['mask']
# Add label to the classes set
classes.add(label)
# Add the node with its attributes to the graph
G.add_node(node_id, label=label, mask=mask)
# Count nodes by mask type
if mask == 'Train':
train_nodes_count += 1
elif mask == 'Validation':
validation_nodes_count += 1
elif mask == 'Test':
test_nodes_count += 1
# Process neighbors and add edges (using set to remove duplicates)
neighbors = set(entry['neighbors'])
for neighbor in neighbors:
# Avoid self-loop if desired (optional)
if neighbor != node_id:
G.add_edge(node_id, neighbor)
# If you want to add self-loops, remove the above condition
# Compute the number of edges in the graph
edge_count = G.number_of_edges()
classes_count = len(classes)
# Perform Louvain community detection
partition = community_louvain.best_partition(G)
communities = set(partition.values())
community_count = len(communities)
# Print out the statistics
print("Nodes count:", nodes_count)
print("Edges count:", edge_count)
print("Classes count:", classes_count)
print("Train nodes count:", train_nodes_count)
print("Validation nodes count:", validation_nodes_count)
print("Test nodes count:", test_nodes_count)
print("Louvain community count:", community_count)
if __name__ == '__main__':
main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import json
import random
path = r"C:\Code_Compiling\02_bit_Li\07_LLM4GDA\data\arxiv2023_label_16_10.json"
# 读取reddit.json
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
# 统计每个label的节点个数
label_counts = {}
for node in data:
label = node['label']
if node['mask'] == 'Train':
if label not in label_counts:
label_counts[label] = 0
label_counts[label] += 1
# 输出每个label的节点个数
print("Train Label counts:", label_counts)
# 获取用户输入的x和y
x = int(input("Enter label value (x): "))
y = int(input("Enter number of nodes to keep (y): "))
# 先将所有mask为'train'且label为x的节点收集到一个列表中
train_x_nodes = [node for node in data if node['label'] == x and node['mask'] == 'Train']
# 确保train_x_nodes列表的长度至少为y
if len(train_x_nodes) < y:
print(f"Warning: There are fewer than {y} nodes with label {x} and mask 'train'. All {len(train_x_nodes)} nodes will be kept.")
selected_nodes = train_x_nodes # 如果不足y个节点,则保留所有该label和mask条件的节点
else:
# 随机选择y个节点
selected_nodes = random.sample(train_x_nodes, y)
# 创建一个删除节点的集合
deleted_nodes = set(node['node_id'] for node in train_x_nodes if node not in selected_nodes)
# 创建新数据列表,保留随机选择的label为x且mask为'train'的节点,其他节点不变
new_data = []
for node in data:
# 保留所有的节点,mask非'train'的节点不做任何更改
if node['label'] != x or (node['mask'] != 'Train' or node in selected_nodes):
new_data.append(node)
# 遍历所有节点的neighbors,删除已经删除的节点
for node in new_data:
if 'neighbors' in node:
# 过滤掉已经删除的节点
node['neighbors'] = [neighbor for neighbor in node['neighbors'] if neighbor not in deleted_nodes]
# 重新调整node_id,使其从0开始连续
id_mapping = {}
new_node_id = 0
# 对new_data中的所有节点进行重排
for node in new_data:
id_mapping[node['node_id']] = new_node_id
node['node_id'] = new_node_id
new_node_id += 1
# 更新所有节点的neighbors,使用新的node_id
for node in new_data:
if 'neighbors' in node:
# 使用id_mapping更新neighbors中的node_id
updated_neighbors = []
for neighbor in node['neighbors']:
if neighbor in id_mapping: # 只更新存在id_mapping中的邻居
updated_neighbors.append(id_mapping[neighbor])
node['neighbors'] = updated_neighbors
# 将修改后的数据保存为reddit_label:{x}_{y}.json
output_filename = f"arxiv2023_label_{x}_{y}.json"
with open(output_filename, 'w', encoding='utf-8') as f:
json.dump(new_data, f, indent=4)
print(f"Modified data saved to {output_filename}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396import json
import numpy as np
import networkx as nx
from collections import Counter, defaultdict
import random
import scipy.sparse as sp
from scipy.sparse.linalg import eigsh
import sys
import os
try:
import community as community_louvain
except ImportError:
print("Warning: python-louvain package not found. Installing...")
import subprocess
subprocess.check_call([sys.executable, "-m", "pip", "install", "python-louvain"])
import community as community_louvain
def load_graph_from_json(json_file):
"""Load graph from a JSON file with nodes."""
nodes = []
try:
# First try to parse as a single JSON array or object
with open(json_file, 'r', encoding='utf-8') as f:
content = f.read().strip()
try:
data = json.loads(content)
if isinstance(data, list):
nodes = data
else:
nodes = [data]
except json.JSONDecodeError:
# Reset and try parsing line by line
nodes = []
with open(json_file, 'r') as f:
for line in f:
line = line.strip()
if line: # Skip empty lines
try:
node_data = json.loads(line)
nodes.append(node_data)
except json.JSONDecodeError:
continue
except Exception as e:
print(f"Error loading graph: {e}")
return []
return nodes
def build_networkx_graph(nodes):
"""Build a NetworkX graph from the loaded node data."""
G = nx.Graph()
# Add nodes with attributes
for node in nodes:
G.add_node(
node['node_id'],
label=node['label'],
text=node['text'],
mask=node['mask']
)
# Add edges
for node in nodes:
node_id = node['node_id']
for neighbor_id in node['neighbors']:
if G.has_node(neighbor_id): # Only add edge if both nodes exist
G.add_edge(node_id, neighbor_id)
return G
def analyze_graph_properties(G):
"""Analyze the properties of the graph as specified in the requirements."""
properties = {}
# Mask distribution (Train/Validation/Test)
masks = [G.nodes[n]['mask'] for n in G.nodes]
mask_distribution = Counter(masks)
properties['mask_distribution'] = {k: v/len(G.nodes) for k, v in mask_distribution.items()}
# Label distribution
labels = [G.nodes[n]['label'] for n in G.nodes]
label_distribution = Counter(labels)
properties['label_distribution'] = {k: v/len(G.nodes) for k, v in label_distribution.items()}
# Graph density
properties['density'] = nx.density(G)
# Degree distribution
degrees = [d for n, d in G.degree()]
degree_counts = Counter(degrees)
properties['degree_distribution'] = {k: v/len(G.nodes) for k, v in degree_counts.items()}
# Community structure (using Louvain algorithm)
try:
communities = community_louvain.best_partition(G)
community_counts = Counter(communities.values())
properties['community_distribution'] = {k: v/len(G.nodes) for k, v in community_counts.items()}
except:
properties['community_distribution'] = {}
# Spectral characteristics
if len(G) > 1:
try:
laplacian = nx.normalized_laplacian_matrix(G)
if sp.issparse(laplacian) and laplacian.shape[0] > 1:
try:
k = min(5, laplacian.shape[0]-1)
if k > 0:
eigenvalues = eigsh(laplacian, k=k, which='SM', return_eigenvectors=False)
properties['spectral_eigenvalues'] = sorted(eigenvalues.tolist())
else:
properties['spectral_eigenvalues'] = []
except:
properties['spectral_eigenvalues'] = []
else:
properties['spectral_eigenvalues'] = []
except:
properties['spectral_eigenvalues'] = []
else:
properties['spectral_eigenvalues'] = []
# Connectivity characteristics
properties['connected_components'] = nx.number_connected_components(G)
largest_cc = max(nx.connected_components(G), key=len)
properties['largest_cc_ratio'] = len(largest_cc) / len(G.nodes)
return properties
def sample_graph_preserving_properties(G, percentage, original_properties):
"""Sample a percentage of nodes while preserving graph properties."""
num_nodes = len(G.nodes)
num_nodes_to_sample = max(1, int(num_nodes * percentage / 100))
# If the graph is too small, just return it
if num_nodes <= num_nodes_to_sample:
return G, {n: n for n in G.nodes}
# 1. Preserve label and mask distribution (top priority per requirements)
mask_label_groups = defaultdict(list)
for node in G.nodes:
mask = G.nodes[node]['mask']
label = G.nodes[node]['label']
mask_label_groups[(mask, label)].append(node)
# Calculate how many nodes to sample from each mask-label group
group_counts = {}
for (mask, label), nodes in mask_label_groups.items():
mask_ratio = original_properties['mask_distribution'].get(mask, 0)
label_ratio = original_properties['label_distribution'].get(label, 0)
# Calculate joint probability
joint_ratio = mask_ratio * label_ratio / sum(
original_properties['mask_distribution'].get(m, 0) *
original_properties['label_distribution'].get(l, 0)
for m in original_properties['mask_distribution']
for l in original_properties['label_distribution']
)
target_count = int(num_nodes_to_sample * joint_ratio)
# Ensure at least one node from non-empty groups
group_counts[(mask, label)] = max(1, target_count) if nodes else 0
# Adjust to match the exact sample size
total_count = sum(group_counts.values())
if total_count != num_nodes_to_sample:
diff = num_nodes_to_sample - total_count
groups = list(group_counts.keys())
if diff > 0:
# Add nodes to groups proportionally to their size
group_sizes = [len(mask_label_groups[g]) for g in groups]
group_probs = [s/sum(group_sizes) for s in group_sizes]
for _ in range(diff):
group = random.choices(groups, weights=group_probs)[0]
if len(mask_label_groups[group]) > group_counts[group]:
group_counts[group] += 1
else:
# Remove nodes from groups with excess
groups_with_excess = [(g, c) for g, c in group_counts.items()
if c > 1 and c > len(mask_label_groups[g]) * 0.2]
groups_with_excess.sort(key=lambda x: x[1], reverse=True)
for i in range(min(-diff, len(groups_with_excess))):
group_counts[groups_with_excess[i][0]] -= 1
# 2. Sample nodes from each group, prioritizing connectivity and community structure
sampled_nodes = []
# First try to get community structure
try:
communities = community_louvain.best_partition(G)
except:
communities = {node: 0 for node in G.nodes} # Fallback if community detection fails
# Sample from each mask-label group
for (mask, label), count in group_counts.items():
candidates = mask_label_groups[(mask, label)]
if len(candidates) <= count:
# Take all nodes in this group
sampled_nodes.extend(candidates)
else:
# Score nodes based on degree and community representation
node_scores = {}
for node in candidates:
# Higher score for higher degree nodes (connectivity)
degree_score = G.degree(node) / max(1, max(d for n, d in G.degree()))
# Higher score for nodes in underrepresented communities
comm = communities.get(node, 0)
comm_sampled = sum(1 for n in sampled_nodes if communities.get(n, -1) == comm)
comm_total = sum(1 for n in G.nodes if communities.get(n, -1) == comm)
comm_score = 1 - (comm_sampled / max(1, comm_total))
# Combined score (prioritize connectivity slightly more)
node_scores[node] = 0.6 * degree_score + 0.4 * comm_score
# Sort candidates by score and select the top ones
sorted_candidates = sorted(candidates, key=lambda n: node_scores.get(n, 0), reverse=True)
sampled_nodes.extend(sorted_candidates[:count])
# 3. Create the sampled subgraph
sampled_G = G.subgraph(sampled_nodes).copy()
# 4. Improve connectivity if needed
if nx.number_connected_components(sampled_G) > original_properties['connected_components']:
# Try to improve connectivity by swapping nodes
non_sampled = [n for n in G.nodes if n not in sampled_nodes]
# Calculate betweenness centrality for non-sampled nodes
betweenness = {}
for node in non_sampled:
# Count how many different components this node would connect
neighbors = list(G.neighbors(node))
sampled_neighbors = [n for n in neighbors if n in sampled_nodes]
if not sampled_neighbors:
continue
components_connected = set()
for n in sampled_neighbors:
for comp_idx, comp in enumerate(nx.connected_components(sampled_G)):
if n in comp:
components_connected.add(comp_idx)
break
betweenness[node] = len(components_connected)
# Sort non-sampled nodes by how many components they would connect
connector_nodes = [(n, b) for n, b in betweenness.items() if b > 1]
connector_nodes.sort(key=lambda x: x[1], reverse=True)
# Try to improve connectivity by swapping nodes
for connector, _ in connector_nodes:
# Find a node to swap out (prefer low degree nodes from well-represented groups)
mask = G.nodes[connector]['mask']
label = G.nodes[connector]['label']
# Find nodes with the same mask and label
same_group = [n for n in sampled_nodes
if G.nodes[n]['mask'] == mask and G.nodes[n]['label'] == label]
if not same_group:
continue
# Sort by degree (ascending)
same_group.sort(key=lambda n: sampled_G.degree(n))
# Swap the node with lowest degree
to_remove = same_group[0]
sampled_nodes.remove(to_remove)
sampled_nodes.append(connector)
# Update the sampled subgraph
sampled_G = G.subgraph(sampled_nodes).copy()
# Stop if we've reached the desired connectivity
if nx.number_connected_components(sampled_G) <= original_properties['connected_components']:
break
# 5. Relabel nodes to have consecutive IDs starting from 0
node_mapping = {old_id: new_id for new_id, old_id in enumerate(sorted(sampled_nodes))}
relabeled_G = nx.relabel_nodes(sampled_G, node_mapping)
# Return the sampled graph and the inverse mapping (new_id -> original_id)
inverse_mapping = {new_id: old_id for old_id, new_id in node_mapping.items()}
return relabeled_G, inverse_mapping
def graph_to_json_format(G):
"""Convert a NetworkX graph to the required JSON format."""
result = []
for node_id in sorted(G.nodes):
node_data = {
"node_id": int(node_id),
"label": G.nodes[node_id]['label'],
"text": G.nodes[node_id]['text'],
"neighbors": sorted([int(n) for n in G.neighbors(node_id)]),
"mask": G.nodes[node_id]['mask']
}
result.append(node_data)
return result
def sample_text_attribute_graph(input_file, output_file, percentage):
"""Main function to sample a text attribute graph and preserve its properties."""
# Load the graph data
print(f"Loading graph from {input_file}...")
nodes = load_graph_from_json(input_file)
if not nodes:
print("Failed to load nodes from the input file.")
return None, None, None
print(f"Loaded {len(nodes)} nodes.")
# Build the NetworkX graph
print("Building graph...")
G = build_networkx_graph(nodes)
print(f"Built graph with {len(G.nodes)} nodes and {len(G.edges)} edges.")
# Analyze the original graph properties
print("Analyzing original graph properties...")
original_properties = analyze_graph_properties(G)
# Sample the graph
print(f"Sampling {percentage}% of the nodes...")
sampled_G, inverse_mapping = sample_graph_preserving_properties(G, percentage, original_properties)
print(f"Sampled graph has {len(sampled_G.nodes)} nodes and {len(sampled_G.edges)} edges.")
# Convert the sampled graph to JSON format
print("Converting sampled graph to JSON format...")
sampled_data = graph_to_json_format(sampled_G)
# Save the sampled graph
print(f"Saving sampled graph to {output_file}...")
with open(output_file, 'w') as f:
json.dump(sampled_data, f, indent=2)
# Analyze the sampled graph properties
print("Analyzing sampled graph properties...")
sampled_properties = analyze_graph_properties(sampled_G)
# Print comparison of original and sampled properties
print("\nComparison of Graph Properties:")
print(f"{'Property':<25} {'Original':<15} {'Sampled':<15}")
print("-" * 55)
print(f"{'Number of nodes':<25} {len(G.nodes):<15} {len(sampled_G.nodes):<15}")
print(f"{'Number of edges':<25} {len(G.edges):<15} {len(sampled_G.edges):<15}")
print(f"{'Density':<25} {original_properties['density']:.4f}{'':>10} {sampled_properties['density']:.4f}{'':>10}")
print("\nMask Distribution:")
print(f"{'Mask':<10} {'Original %':<15} {'Sampled %':<15}")
print("-" * 40)
for mask in sorted(set(original_properties['mask_distribution'].keys()) | set(sampled_properties['mask_distribution'].keys())):
orig_pct = original_properties['mask_distribution'].get(mask, 0) * 100
sampled_pct = sampled_properties['mask_distribution'].get(mask, 0) * 100
print(f"{mask:<10} {orig_pct:.2f}%{'':>9} {sampled_pct:.2f}%{'':>9}")
print("\nLabel Distribution:")
print(f"{'Label':<10} {'Original %':<15} {'Sampled %':<15}")
print("-" * 40)
for label in sorted(set(original_properties['label_distribution'].keys()) | set(sampled_properties['label_distribution'].keys())):
orig_pct = original_properties['label_distribution'].get(label, 0) * 100
sampled_pct = sampled_properties['label_distribution'].get(label, 0) * 100
print(f"{label:<10} {orig_pct:.2f}%{'':>9} {sampled_pct:.2f}%{'':>9}")
print("\nConnectivity:")
print(f"Connected components: {original_properties['connected_components']} (original) vs {sampled_properties['connected_components']} (sampled)")
return sampled_G, original_properties, sampled_properties
def main():
"""Command-line interface."""
if len(sys.argv) != 4:
print("Usage: python sample_graph.py input_file output_file percentage")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
try:
percentage = float(sys.argv[3])
if percentage <= 0 or percentage > 100:
raise ValueError("Percentage must be between 0 and 100")
except ValueError:
print("Error: Percentage must be a number between 0 and 100")
sys.exit(1)
sample_text_attribute_graph(input_file, output_file, percentage)
if __name__ == "__main__":
main()123version https://git-lfs.github.com/spec/v1oid sha256:ba9dd08bf0b5b50f3170d8e1ef794d1f6948d0a38be407a3217f3a830c483d65size 44635743123version https://git-lfs.github.com/spec/v1oid sha256:4567da141dd5c2f64e6b059bdc4db24bf974e655c803d3787ce3b569b392f406size 29728898.gitattributes+5
.gitattributes copyAdded+59
Children.jsonAdded+3
History.jsonAdded+3
README copy.mdAdded+3
SubChildren.jsonAdded
SubCiteseer.jsonAdded
SubCora.jsonAdded
SubHistory.jsonAdded
SubWikics.jsonAdded
Subarxiv2023.jsonAdded
arxiv2023.jsonAdded+3
citeseer.jsonAdded
cora.jsonAdded
data_clear.pyAdded+52
data_statistics.pyAdded+67
few_shot.pyAdded+77
sample.pyAdded+396
wikics.jsonAdded+3
wikics_cleaned.jsonAdded+3