RuntimeError: Expected target size [25, 10], got [25].
I have a sensors data and I want to perform node level classification using GCN. I have k nodes (sensors). Each node has m observations (node features) and each observation is a n dimensional vector. Shape of my dataset is k,m,n, its a 3d dataset. I used DGL to convert data to graph form.
k = 25
m = 2000
n = 6
num_classes = 10
node_features = torch.randn((k, m, n)) #Generate node features.
node_labels = torch.tensor([i for i in range (k)]) #Create tensor of labels
#Create graph
nodes= [i for i in range(k)]
edges = []
for node1, node2 in combinations(nodes, 2):
edges.append([node1, node2])
a = np.array(edges)
src = a[:,0]
dst = a[:,1]
g = dgl.graph((src , dst)) # create graph
g.ndata['features'] = node_features # Assign node features
g.ndata['labels'] = node_labels # Assign labels
Above code creates a graph. Below is graph structure.
Graph(num_nodes=25, num_edges=300,
ndata_schemes={‘features’: Scheme(shape=(2000, 6), dtype=torch.float32), ‘labels’: Scheme(shape=(), dtype=torch.int64)}
edata_schemes={})
Next, I build the GCN model.
import torch.nn as nn
import torch.nn.functional as F
from dgl.nn import GraphConv
class GCN(nn.Module):
def __init__(self, in_feats, h_feats, num_classes):
super(GCN, self).__init__()
self.conv1 = GraphConv(in_feats, h_feats)
self.conv2 = GraphConv(h_feats, num_classes)
def forward(self, g, in_feat):
h = self.conv1(g, in_feat)
h = F.relu(h)
h = self.conv2(g, h)
return h
Training of model is:
num_epochs = 50
hidden_size = 64
features = g.ndata["features"]
labels = g.ndata["labels"]
model = GCN(n, hidden_size , num_classes)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()
# Train model
for epoch in range(num_epochs):
logits = model(g, g.ndata['features'])
loss = criterion(logits, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"Epoch {epoch + 1}, loss: {loss.item()}")
On line loss = criterion(logits, labels)
, following error occurs.
RuntimeError: Expected target size [25, 10], got [25].
How I can solve this problem? If I pass 2 dimensional data to this model, it works fine but my data is 3 dimensional.
Note: Shape of logits is torch.Size([k, m, num_classes ]) while shape of labels is torch.Size([k])
.