You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hello. I used the following code to train my GCN model. I am training it with multiple graphs having different size of nodes and different size of shapes and want to test my model on some other graphs in the test part. I am using gnn_model_criterion = torch.nn.CrossEntropyLoss() as the criterion. However after running my code I get the following error:
gnn_output shape before adjustment: torch.Size([1042, 1])
gnn_output shape after adjustment: torch.Size([1042, 1])
label shape: torch.Size([1042])
Traceback (most recent call last):
File "/Users/Documents/conference-code/GNN-reinforcementlearning/GraphSAGE/Reinforcementmethod.py", line 1364, in <module>
train_rl_policy(policy_net, gnn_model, train_graphs, policy_net_optimizer, gnn_model_criterion, gnn_model_optimizer, num_epochs)
File "/Users/Documents/conference-code/GNN-reinforcementlearning/GraphSAGE/Reinforcementmethod.py", line 1299, in train_rl_policy
loss = gnn_model_criterion(gnn_output, label)
File "/Users/anaconda3/envs/temporal_GNN/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1532, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/Users/anaconda3/envs/temporal_GNN/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1541, in _call_impl
return forward_call(*args, **kwargs)
File "/Users/anaconda3/envs/temporal_GNN/lib/python3.10/site-packages/torch/nn/modules/loss.py", line 1185, in forward
return F.cross_entropy(input, target, weight=self.weight,
File "/Users/anaconda3/envs/temporal_GNN/lib/python3.10/site-packages/torch/nn/functional.py", line 3086, in cross_entropy
return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
IndexError: Target 1 is out of bounds.
Here is my code:
class GCN(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(GCN, self).__init__()
self.conv1 = GCNConv(input_dim, hidden_dim)
self.conv2 = GCNConv(hidden_dim, output_dim)
def forward(self, x, edge_index, aggregation_method=None):
x = F.relu(self.conv1(x, edge_index))
x = F.relu(self.conv2(x, edge_index))
x = F.log_softmax(x, dim=1)
return x
def train(gnn_model, graphs, gnn_model_criterion, gnn_model_optimizer, num_epochs):
num_classes = len(torch.unique(torch.cat([batch.y for batch in graphs], dim=0))) # Calculate num_classes based on all data in the loader
for epoch in range(num_epochs):
total_reward = 0
total_loss = 0 # Initialize total loss
for graph in graphs:
x, edge_index, label = graph.x, graph.edge_index, graph.y
gnn_model_optimizer.zero_grad() # Reset gradients for GNN
# Compute class weights
num_samples_in_class_1 = np.count_nonzero(label.cpu().numpy())
num_samples_in_class_0 = len(label) - num_samples_in_class_1
total_samples = len(label)
weight_for_class_0 = 1 if num_samples_in_class_0 == 0 else total_samples / (num_samples_in_class_0 * num_classes)
weight_for_class_1 = 1 if num_samples_in_class_1 == 0 else total_samples / (num_samples_in_class_1 * num_classes)
weights_tensor = torch.tensor([weight_for_class_0, weight_for_class_1]).to(device)
# Train GCN with the selected aggregation method
gnn_output = gnn_model(x, edge_index)
# Debugging the output shape of GNN model
print(f"gnn_output shape before adjustment: {gnn_output.shape}")
# Ensure gnn_output is of shape [1042, num_classes] or [1042]
if gnn_output.dim() > 1:
gnn_output = gnn_output # No adjustment needed here if it matches [1042, num_classes]
# Debugging the output shape of GNN model after adjustment
print(f"gnn_output shape after adjustment: {gnn_output.shape}")
print(f"label shape: {label.shape}")
# Calculate loss
loss = gnn_model_criterion(gnn_output, label)
# Debugging the loss value
print(f"Loss value: {loss.item()}")
weights = torch.where(label == 0, torch.tensor(weight_for_class_0).to(device), torch.tensor(weight_for_class_1).to(device))
weighted_loss = torch.mean(weights * loss)
total_loss += weighted_loss.item() * graph.num_graphs
# Backpropagate and update GNN
weighted_loss.backward()
gnn_model_optimizer.step()
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hello. I used the following code to train my GCN model. I am training it with multiple graphs having different size of nodes and different size of shapes and want to test my model on some other graphs in the test part. I am using gnn_model_criterion = torch.nn.CrossEntropyLoss() as the criterion. However after running my code I get the following error:
Here is my code:
Beta Was this translation helpful? Give feedback.
All reactions