Run Time Error while Training

White_Devil: <h2><a name="runtimeerror-given-groups1-weight-of-size-64-3-7-7-expected-input64-500-1000-3-to-have-3-channels-but-got-500-channels-instead-1" class="anchor" href="#runtimeerror-given-groups1-weight-of-size-64-3-7-7-expected-input64-500-1000-3-to-have-3-channels-but-got-500-channels-instead-1"></a>RuntimeError: Given groups=1, weight of size [64, 3, 7, 7], expected input[64, 500, 1000, 3] to have 3 channels, but got 500 channels instead</h2>
<p>Tell me how to rectify the error</p>

ptrblck: <p>Permute your input as it seems you are trying to use a channels-last input image while channels-first is expected.</p>

White_Devil: <p>import torch<br>
import torch.nn as nn<br>
import torchvision.models as models<br>
import torch.optim as optim<br>
import torchvision.transforms as transforms<br>
from torch.utils.data import Dataset, DataLoader<br>
import os<br>
import numpy as np<br>
from PIL import Image</p>
<p>class ResNet18(nn.Module):<br>
def <strong>init</strong>(self, num_classes=5):<br>
super(ResNet18, self).<strong>init</strong>()<br>
self.resnet18 = models.resnet18(pretrained=False)<br>
in_features = self.resnet18.fc.in_features<br>
self.resnet18.fc = nn.Linear(in_features, num_classes)</p>
<pre><code>def forward(self, x):
    return self.resnet18(x)
</code></pre>
<h1><a name="create-an-instance-of-the-resnet-18-model-1" class="anchor" href="#create-an-instance-of-the-resnet-18-model-1"></a>Create an instance of the ResNet-18 model</h1>
<p>model = ResNet18(num_classes=5)</p>
<p>class CustomDataset(Dataset):<br>
def <strong>init</strong>(self, root_dir):<br>
self.root_dir = root_dir<br>
self.images = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
self.labels = <span class="chcklst-box fa fa-square-o fa-fw"></span></p>
<pre><code>    # Iterate over the folders and load the images and labels
    for folder in os.listdir(root_dir):
        folder_path = os.path.join(root_dir, folder)
        for image_path in os.listdir(folder_path):
            image = Image.open(os.path.join(folder_path, image_path))

            # Convert to RGB format if necessary
            if image.mode != 'RGB':
                image = image.convert('RGB')

            # Convert to torch tensor and keep only the first three channels
            image = torch.from_numpy(np.array(image)[:, :, :3])

            label = int(folder)

            self.images.append(image)
            self.labels.append(label)

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

def __getitem__(self, idx):
    image = self.images[idx]

    return image, self.labels[idx]
</code></pre>
<h1><a name="create-an-instance-of-the-customdataset-class-2" class="anchor" href="#create-an-instance-of-the-customdataset-class-2"></a>Create an instance of the CustomDataset class</h1>
<p>dataset = CustomDataset(root_dir=r"C:\Users\KESA VARDHAN\Desktop\Output Folder")<br>
print(“Data is loaded”)</p>
<h1><a name="split-the-dataset-into-train-validation-and-test-sets-3" class="anchor" href="#split-the-dataset-into-train-validation-and-test-sets-3"></a>Split the dataset into train, validation, and test sets</h1>
<p>train_size = int(0.8 * len(dataset))<br>
val_size = int(0.1 * len(dataset))<br>
test_size = len(dataset) - train_size - val_size</p>
<p>train_dataset, val_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, val_size, test_size])</p>
<h1><a name="create-data-loaders-4" class="anchor" href="#create-data-loaders-4"></a>Create data loaders</h1>
<p>train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)<br>
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=64, shuffle=False)<br>
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)</p>
<p>print(“Data is split”)</p>
<h1><a name="define-the-loss-and-optimizer-5" class="anchor" href="#define-the-loss-and-optimizer-5"></a>Define the loss and optimizer</h1>
<p>criterion = nn.CrossEntropyLoss()<br>
optimizer = optim.SGD(model.parameters(), lr=0.001)</p>
<h1><a name="train-the-model-6" class="anchor" href="#train-the-model-6"></a>Train the model</h1>
<p>for epoch in range(10):<br>
for inputs, labels in train_loader:<br>
outputs = model(inputs)<br>
loss = criterion(outputs, labels)</p>
<pre><code>    # Update the optimizer parameters
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# Evaluate the model on the validation set
with torch.no_grad():
    val_loss = 0.0
    val_acc = 0.0
    for inputs, labels in val_loader:
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        val_loss += loss.item()

        _, predicted = torch.max(outputs.data, 1)
        correct = (predicted == labels).sum().item()
        val_acc += correct / labels.size(0)

    val_loss /= len(val_loader)
    val_acc /= len(val_loader)

    # Print the training and validation losses and accuracies
    print('Epoch {}/{}: Train Loss {}, Val Loss {}, Train Acc {}, Val Acc {}'.format(
        epoch + 1, 10, loss.item(), val_loss, val_acc, val_acc
    ))
</code></pre>
<h1><a name="evaluate-the-model-on-the-test-set-7" class="anchor" href="#evaluate-the-model-on-the-test-set-7"></a>Evaluate the model on the test set</h1>
<p>with torch.no_grad():<br>
test_loss = 0.0<br>
test_acc = 0.0<br>
for inputs, labels in test_loader:<br>
outputs = model(inputs)<br>
loss = criterion(outputs, labels)<br>
test_loss += loss.item()</p>
<pre><code>    _, predicted = torch.max(outputs.data, 1)
    correct = (predicted == labels).sum().item()
    test_acc += correct / labels.size(0)

test_loss /= len(test_loader)
test_acc /= len(test_loader)

# Print the test loss and accuracy
print('Test Loss {}, Test Acc {}'.format(test_loss, test_acc))
</code></pre>
<h1><a name="save-the-trained-model-8" class="anchor" href="#save-the-trained-model-8"></a>Save the trained model</h1>
<p>torch.save(model.state_dict(), “trained_model.pt”)<br>
here is my entire code can you please say what change should make to the code so that the data comes in 3 channel</p>

J_Johnson: <aside class="quote no-group" data-username="White_Devil" data-post="3" data-topic="192192">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/white_devil/48/65609_2.png" class="avatar"> White_Devil:</div>
<blockquote>
<pre><code class="lang-auto">def __getitem__(self, idx):
    image = self.images[idx]

    return image, self.labels[idx]
</code></pre>
</blockquote>
</aside>
<p>Change this to:</p>
<pre><code class="lang-auto">def __getitem__(self, idx):
    image = self.images[idx]
    image = image.permute(0, 3, 1, 2)
    return image, self.labels[idx]
</code></pre>
<p>Your images are of size (batch, height, width, channels) when the Conv2d layers take (batch, channels, height, width) by default. See here:</p>
<p><a href="https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html" class="onebox" target="_blank" rel="noopener nofollow ugc">https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html</a></p>

White_Devil: <p>Thank You I did help me run the code</p>