RuntimeError: Expected target size [12, 12], got [12]

taehyoung_Kim: <p>Hi, I’m a graduate student trying to do GNN semi-supervised learning using pytorch.</p>
<p>The structure of all my data is 100x100 in size,<br>
supervised learning data is 12.</p>
<p>Below is the corresponding code.<br>
I think the size is correct, but I want to know why I get the above error.</p>
<p>If you need more information, please leave a comment and I’ll get back to you.</p>
<p>I’m not an expert, so my question may be lacking in many areas. I’ll try to provide the best information I can.</p>
<p>Thank you</p>
<p>import os<br>
import pickle<br>
import pandas as pd<br>
from torch.utils.data import Dataset, DataLoader<br>
import torch.nn as nn<br>
import torch.optim as optim<br>
import torch</p>
<h1><a name="h-1-custom-dataset-1" class="anchor" href="#h-1-custom-dataset-1"></a>1. Custom Dataset</h1>
<p>class CustomGraphDataset(Dataset):<br>
def <strong>init</strong>(self, drug_pkl_folder_path, disease_pkl_folder_path, csv_path=None):<br>
self.drug_file_paths = [os.path.join(drug_pkl_folder_path, file) for file in os.listdir(drug_pkl_folder_path) if file.endswith(‘.pkl’)]<br>
self.disease_file_paths = [os.path.join(disease_pkl_folder_path, file) for file in os.listdir(disease_pkl_folder_path) if file.endswith(‘.pkl’)]<br>
self.labels = {}  # drug to index mapping<br>
self.label_to_index = {}  # disease to index mapping<br>
self.index_to_label = {}  # index to disease mapping</p>
<pre><code>    if csv_path:
        df = pd.read_csv(csv_path)
        unique_labels = df['disease'].unique().tolist()
        for idx, unique_label in enumerate(unique_labels):
            self.label_to_index[unique_label] = idx
            self.index_to_label[idx] = unique_label

        for idx, row in df.iterrows():
            drug = row['drug']
            disease = row['disease']
            self.labels[drug] = self.label_to_index[disease]

def __len__(self):
    return len(self.drug_file_paths)

def __getitem__(self, idx):
    with open(self.drug_file_paths[idx], 'rb') as f:
        drug_data = pickle.load(f)
    with open(self.disease_file_paths[idx], 'rb') as f:
        disease_data = pickle.load(f)

    drug_name = os.path.basename(self.drug_file_paths[idx]).replace('.pkl', '')

    if drug_name in self.labels:
        label = self.labels[drug_name]
        return drug_data, disease_data, torch.tensor(label, dtype=torch.long)
    else:
        return drug_data, disease_data, None
</code></pre>
<h1><a name="h-2-dataloader-2" class="anchor" href="#h-2-dataloader-2"></a>2. DataLoader</h1>
<p>supervised_dataset = CustomGraphDataset(‘model data set/supervised drug’, ‘model data set/supervised disease’, ‘C:/Users/tae97/Desktop/linkinfo/model data set/supervised.csv’)<br>
unsupervised_drug_dataset = CustomGraphDataset(‘model data set/unsupervised drug’, ‘model data set/unsupervised disease’)<br>
unsupervised_disease_dataset = CustomGraphDataset(‘model data set/unsupervised drug’, ‘model data set/unsupervised disease’)</p>
<p>supervised_loader = DataLoader(supervised_dataset, batch_size=32, shuffle=True)<br>
unsupervised_drug_loader = DataLoader(unsupervised_drug_dataset, batch_size=32, shuffle=True)<br>
unsupervised_disease_loader = DataLoader(unsupervised_disease_dataset, batch_size=32, shuffle=True)</p>
<h1><a name="h-3-model-3" class="anchor" href="#h-3-model-3"></a>3. Model</h1>
<p>num_classes = len(supervised_dataset.label_to_index)</p>
<p>class SimpleGNN(nn.Module):<br>
def <strong>init</strong>(self, num_classes):<br>
super(SimpleGNN, self).<strong>init</strong>()<br>
self.fc = nn.Linear(100, num_classes)</p>
<pre><code>def forward(self, x):
    return self.fc(x)
</code></pre>
<h1><a name="h-4-training-4" class="anchor" href="#h-4-training-4"></a>4. Training</h1>
<p>model = SimpleGNN(num_classes)<br>
print(model)</p>
<p>optimizer = optim.Adam(model.parameters(), lr=0.001)<br>
loss_function = nn.CrossEntropyLoss()</p>
<p>epochs = 10<br>
for epoch in range(epochs):<br>
for drug_data, disease_data, label in supervised_loader:<br>
if label is None:<br>
continue<br>
drug_data = drug_data.float()<br>
label = label.long()<br>
optimizer.zero_grad()<br>
outputs = model(drug_data)<br>
loss = loss_function(outputs, label)<br>
loss.backward()<br>
optimizer.step()</p>