I am getting my accuracy '0.0' at each epoch. Anybody help me to resolve this. Thankyou in advance

luci: <p>class tabular_model(nn.Module):<br>
def <strong>init</strong>(self):<br>
super().<strong>init</strong>()<br>
self.input = nn.Linear(13, 250)<br>
self.hidden1 = nn.Linear(250, 250)<br>
self.hidden2 = nn.Linear(250, 500)<br>
self.output = nn.Linear(500, 1)<br>
self.relu = nn.ReLU()<br>
self.dropout = nn.Dropout(p=0.25)</p>
<p>def forward(self, x):<br>
x = self.relu(self.input(x))<br>
x = self.dropout(x)<br>
x = self.relu(self.hidden1(x))<br>
x = self.dropout(x)<br>
x = self.relu(self.hidden2(x))<br>
x = self.dropout(x)<br>
x = self.output(x)<br>
return x</p>
<p>net = tabular_model()<br>
optimizer = torch.optim.SGD(net.parameters(), lr=0.01, momentum = 0.9)<br>
loss_func = nn.MSELoss()</p>
<p>def functiontotrain():</p>
<p>theBestModel = {“Accuracy”:0, “net”:None}<br>
losses = np.zeros(numepochs)<br>
trainAcc = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
testAcc = <span class="chcklst-box fa fa-square-o fa-fw"></span></p>
<p>for epochi in range(numepochs):</p>
<pre><code>net.to(device)
net.train()

for X,y in train_dataloaders:

  X = X.to(device)
  y = y.to(device)

  batchLoss = []
  batchAcc = []

  yHat = net(X)
  loss = loss_func(yHat, y)

  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

  batchLoss.append(loss.item())
  batchAcc = (100*torch.mean((yHat == y).float()).item())

trainAcc.append(np.mean(batchAcc))

losses[epochi] = np.mean(batchLoss)

if trainAcc[-1] &gt; theBestModel['Accuracy']:
  theBestModel['net'] = trainAcc[-1].item()

  theBestModel['net'] = copy.deepcopy(net.state_dict())
</code></pre>
<p>return trainAcc, losses, theBestModel</p>
<p>Accuracy graph:<br>
<img src="https://discuss.pytorch.org/uploads/default/original/3X/b/4/b44b87fc63bd79b5c9b940bfdf536d1efee05c7d.png" alt="image" data-base62-sha1="pIXLI246rK9orey4nvQ5a48UlAN" width="580" height="417"></p>

AbdulsalamBande: <p>It looks like the main issue is that you’re using a regression loss function (MSELoss) for a classification task. Since your model is predicting a continuous value, comparing this directly with the ground truth class labels using <code>yHat == y</code> will almost always result in a false condition, leading to 0.0 accuracy.</p>
<ol>
<li>Change the output layer to output 2 values instead of 1 (assuming binary classification):</li>
</ol>
<pre><code class="lang-auto">self.output = nn.Linear(500, 2)
</code></pre>
<ol start="2">
<li>Use <code>nn.CrossEntropyLoss()</code> as your loss function:</li>
</ol>
<pre><code class="lang-auto">loss_function = nn.CrossEntropyLoss()
</code></pre>

luci: <p>This post was flagged by the community and is temporarily hidden.</p>

AbdulsalamBande: <p>Try</p>
<pre><code class="lang-auto">class tabular_model(nn.Module):
    def __init__(self):
        super().__init__()
        self.input = nn.Linear(13, 250)
        self.hidden1 = nn.Linear(250, 250)
        self.hidden2 = nn.Linear(250, 500)
        self.output = nn.Linear(500, 2)  # Change output to match number of classes
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(p=0.25)

    def forward(self, x):
        x = self.relu(self.input(x))
        x = self.dropout(x)
        x = self.relu(self.hidden1(x))
        x = self.dropout(x)
        x = self.relu(self.hidden2(x))
        x = self.dropout(x)
        x = self.output(x)
        return x

net = tabular_model()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
loss_func = nn.CrossEntropyLoss()  # Use CrossEntropyLoss for classification

def functiontotrain():
    theBestModel = {"Accuracy": 0, "net": None}
    losses = np.zeros(numepochs)
    trainAcc = []
    testAcc = []

    for epochi in range(numepochs):
        net.to(device)
        net.train()

        for X, y in train_dataloaders:
            X = X.to(device)
            y = y.to(device)

            batchLoss = []
            batchAcc = []

            yHat = net(X)
            loss = loss_func(yHat, y)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            batchLoss.append(loss.item())
            _, preds = torch.max(yHat, 1)  # Get class predictions
            batchAcc = (100 * torch.mean((preds == y).float()).item())  # Calculate accuracy based on class predictions

            trainAcc.append(np.mean(batchAcc))

        losses[epochi] = np.mean(batchLoss)

        if trainAcc[-1] &gt; theBestModel['Accuracy']:
            theBestModel['net'] = trainAcc[-1].item()
            theBestModel['net'] = copy.deepcopy(net.state_dict())

    return trainAcc, losses, theBestModel

</code></pre>

luci: <p>This post was flagged by the community and is temporarily hidden.</p>

AbdulsalamBande: <p>Make sure to adjust the output layer size if you have more than two classes, and also ensure that your target labels are in the format <code>[0, 1, 2, ..., num_classes-1]</code> for compatibility with CrossEntropyLoss.</p>

luci: <p>This post was flagged by the community and is temporarily hidden.</p>

ptrblck: <p>Is this a double post from <a href="https://discuss.pytorch.org/t/i-am-getting-accuracy-0-0-each-time-why-thankyou-in-advance/176533">here</a> from another account?</p>

AbdulsalamBande: <p>It seems so. <a class="mention" href="/u/ptrblck">@ptrblck</a></p>

luci: <p>This post was flagged by the community and is temporarily hidden.</p>

luci: <p>This post was flagged by the community and is temporarily hidden.</p>

AbdulsalamBande: <p>Based on the data you provided, it seems that you are using a regression model to predict the sale price of a house. However, you are calculating the accuracy as if it were a classification problem. This is probably the reason you are getting an accuracy of 0.0.</p>
<p>In regression tasks, accuracy is not the right metric to measure the performance of your model. Instead, you should use metrics such as Mean Squared Error (MSE), Root Mean Squared Error (RMSE), Mean Absolute Error (MAE), or R-squared (Coefficient of Determination).</p>
<p>To calculate these metrics, you can use <code>sklearn.metrics</code>. Try this code block</p>
<pre><code class="lang-auto">import torch
import torch.nn as nn
import numpy as np
from sklearn.metrics import mean_squared_error
import copy

class TabularModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.input = nn.Linear(13, 250)
        self.hidden1 = nn.Linear(250, 250)
        self.hidden2 = nn.Linear(250, 500)
        self.output = nn.Linear(500, 1)
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(p=0.25)

    def forward(self, x):
        x = self.relu(self.input(x))
        x = self.dropout(x)
        x = self.relu(self.hidden1(x))
        x = self.dropout(x)
        x = self.relu(self.hidden2(x))
        x = self.dropout(x)
        x = self.output(x)
        return x

net = TabularModel()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
loss_func = nn.MSELoss()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

num_epochs = 10

def train_model():
    best_model = {"RMSE": float("inf"), "net": None}
    losses = np.zeros(num_epochs)
    train_RMSEs = []

    for epoch in range(num_epochs):
        net.to(device)
        net.train()

        batch_losses = []
        batch_RMSEs = []

        for X, y in train_dataloaders:
            X = X.to(device)
            y = y.to(device)

            y_hat = net(X)
            loss = loss_func(y_hat, y)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            batch_losses.append(loss.item())

            y_hat_rounded = y_hat.detach().cpu().numpy().round()
            y_cpu = y.cpu().numpy()
            batch_RMSE = mean_squared_error(y_cpu, y_hat_rounded, squared=False)
            batch_RMSEs.append(batch_RMSE)

        train_RMSEs.append(np.mean(batch_RMSEs))
        losses[epoch] = np.mean(batch_losses)

        if train_RMSEs[-1] &lt; best_model["RMSE"]:
            best_model["RMSE"] = train_RMSEs[-1]
            best_model["net"] = copy.deepcopy(net.state_dict())

    return train_RMSEs, losses, best_model

</code></pre>

luci: <p>This post was flagged by the community and is temporarily hidden.</p>

luci: <p>This post was flagged by the community and is temporarily hidden.</p>

upendra: <p>I have followed your suggestions and finally my model started to train. But i am getting hude accuracy ald losses values.</p>
<p>The following represents the train accuracy and losses:</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/9/d/9d96db4a1758a540dc6aaa846b30405c219f4130.png" data-download-href="https://discuss.pytorch.org/uploads/default/9d96db4a1758a540dc6aaa846b30405c219f4130" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/9/d/9d96db4a1758a540dc6aaa846b30405c219f4130_2_690x386.png" alt="image" data-base62-sha1="mu6aDL9BwamLfXEuDPxhZMrxmec" width="690" height="386" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/9/d/9d96db4a1758a540dc6aaa846b30405c219f4130_2_690x386.png, https://discuss.pytorch.org/uploads/default/optimized/3X/9/d/9d96db4a1758a540dc6aaa846b30405c219f4130_2_1035x579.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/9/d/9d96db4a1758a540dc6aaa846b30405c219f4130.png 2x" data-dominant-color="94BDD9"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">1035×579 42.7 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

ptrblck: <p><a class="mention" href="/u/upendra">@upendra</a> <a class="mention" href="/u/luci">@luci</a> I would recommend using a single account and delete the other one as our system flags your posts as spam.</p>