Error: 0D or 1D target tensor expected, multi-target not supported

ifunayaScript: <p>import torch<br>
import torch.nn as nn<br>
from torch.utils.data import Dataset, DataLoader<br>
import numpy as np<br>
from sklearn.model_selection import train_test_split</p>
<h1>
<a name="from-sklearnpreprocessing-import-standardscaler-1" class="anchor" href="#from-sklearnpreprocessing-import-standardscaler-1"></a>from sklearn.preprocessing import StandardScaler</h1>
<p>class WineDataset(Dataset):<br>
def <strong>init</strong>(self):<br>
# data loading<br>
xy = np.loadtxt(r’C:\Users\USER\Desktop\MyDatasets\wine_data.csv’, delimiter=’,’, dtype=np.float32, skiprows=1)<br>
self.x = torch.from_numpy(xy[:, 1:])<br>
self.y = torch.from_numpy(xy[:, [0]])<br>
self.n_samples = xy.shape[0]<br>
def <strong>getitem</strong>(self, index):<br>
return self.x[index], self.y[index]<br>
def <strong>len</strong>(self):<br>
return self.n_samples</p>
<p>dataset = WineDataset()<br>
dataloader = DataLoader(dataset=dataset, batch_size=4, shuffle=True)</p>
<p>samples = iter(dataloader)<br>
features, targets = samples.next()</p>
<p>input_features = features.shape[1]<br>
hidden_size = 40<br>
num_classes = len(np.unique(targets))</p>
<p>class Model(nn.Module):<br>
def <strong>init</strong>(self, input_features, hidden_size, num_classes):<br>
super(Model, self).<strong>init</strong>()<br>
self.l1 = nn.Linear(input_features, hidden_size)<br>
self.relu = nn.ReLU()<br>
self.l2 = nn.Linear(hidden_size, num_classes)</p>
<pre><code>def forward(self, x):
    out = self.l1(x)
    out = self.relu(out)
    out = self.l2(out)
    return out
</code></pre>
<h1>
<a name="define-some-training-parameters-2" class="anchor" href="#define-some-training-parameters-2"></a>Define some training parameters</h1>
<p>model = Model(input_features, hidden_size, num_classes)<br>
learning_rate = 0.01<br>
epochs = 10<br>
criterion = nn.CrossEntropyLoss()<br>
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)</p>
<h1>
<a name="training-loop-3" class="anchor" href="#training-loop-3"></a>Training loop</h1>
<p>n_total_steps = len(dataloader)<br>
for epoch in range(epochs):<br>
for i, (features, targets) in enumerate(dataloader):<br>
# forward pass<br>
prediction = model(features)<br>
loss = criterion(prediction, targets)</p>
<pre><code>    # empty gradients and backward pass
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    
    if (i+1) % 100 == 0:
        print(f'epoch: {epoch+1}/{epochs}, step: {i+1}/{n_total_steps}, loss: {loss.item():.4f}')</code></pre>

ifunayaScript: <p>When I run this code it returns that error,<br>
Perhaps someone can go through the snippet and help out. Thanks</p>

ptrblck: <p>I guess the target shape is wrong as <code>nn.CrossEntropyLoss</code> would expect a model output in the shape <code>[batch_size, nb_classes]</code> and a target in the shape <code>[batch_size]</code> containing class indices in the range <code>[0, nb_classes-1]</code>.</p>
<p>PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=12" title=":wink:" class="emoji" alt=":wink:" loading="lazy" width="20" height="20"></p>

ifunayaScript: <p>So you mean instead of creating the dataset class. I could just load the data and use train_test_split, so that the the features and targets have the same sample size?</p>
<p>PS: thanks sir for the backticks <img src="https://discuss.pytorch.org/images/emoji/apple/smiley.png?v=12" title=":smiley:" class="emoji" alt=":smiley:" loading="lazy" width="20" height="20"></p>

ptrblck: <p>No, as described in the previous post the data and target have different shapes and you should make sure this is the case in your use case.</p>