RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x6422528 and 100352x256)

vervit_khandelwal: <p>import os<br>
import pandas as pd<br>
from PIL import Image<br>
import torch<br>
import torch.nn as nn<br>
import torch.optim as optim<br>
from torch.utils.data import Dataset, DataLoader<br>
from torchvision.transforms import transforms</p>
<h1>
<a name="define-a-custom-dataset-class-1" class="anchor" href="#define-a-custom-dataset-class-1"></a>Define a custom dataset class</h1>
<p>class AllergyDataset(Dataset):<br>
def <strong>init</strong>(self, csv_file, image_folder, transform=None):<br>
self.data = pd.read_csv(csv_file)<br>
self.image_folder = image_folder<br>
self.transform = transform</p>
<pre><code>    # Filter out rows with missing values
    self.data = self.data.dropna(subset=['Chip_Image_Name', 'Present'])
    
def __len__(self):
    return len(self.data)

def __getitem__(self, idx):
    row = self.data.iloc[idx]
    image_name = row['Chip_Image_Name']
    
    image_path = os.path.join(self.image_folder, f'{image_name}.bmp')
    
    image = Image.open(image_path[:-4]).convert('RGB')
    
    label = row['Present']
    
    if self.transform is not None:
        image = self.transform(image)
    
    return image, label
</code></pre>
<h1>
<a name="set-the-path-to-your-dataset-csv-file-and-image-folder-2" class="anchor" href="#set-the-path-to-your-dataset-csv-file-and-image-folder-2"></a>Set the path to your dataset CSV file and image folder</h1>
<p>csv_file = ‘data/train.csv’<br>
image_folder = ‘data/images’</p>
<h1>
<a name="set-the-transformation-for-your-images-3" class="anchor" href="#set-the-transformation-for-your-images-3"></a>Set the transformation for your images</h1>
<p>transform = transforms.Compose([<br>
transforms.Resize((224, 224)),<br>
transforms.ToTensor(),<br>
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])<br>
])</p>
<h1>
<a name="create-the-dataset-4" class="anchor" href="#create-the-dataset-4"></a>Create the dataset</h1>
<p>dataset = AllergyDataset(csv_file, image_folder, transform=transform)</p>
<h1>
<a name="create-data-loaders-5" class="anchor" href="#create-data-loaders-5"></a>Create data loaders</h1>
<p>batch_size = 32<br>
train_ratio = 0.8<br>
train_size = int(train_ratio * len(dataset))<br>
val_size = len(dataset) - train_size</p>
<p>train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])</p>
<p>train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)<br>
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)</p>
<h1>
<a name="define-your-neural-network-model-6" class="anchor" href="#define-your-neural-network-model-6"></a>Define your neural network model</h1>
<p>class AllergyClassifier(nn.Module):<br>
def <strong>init</strong>(self):<br>
super(AllergyClassifier, self).<strong>init</strong>()<br>
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1)<br>
self.conv2 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)<br>
self.fc1 = nn.Linear(128 * 28 * 28, 256)  # Update the input size here<br>
self.fc2 = nn.Linear(256, 1)<br>
self.sigmoid = nn.Sigmoid()</p>
<pre><code>def forward(self, x):
    x = nn.functional.relu(self.conv1(x))
    x = nn.functional.relu(self.conv2(x))
    x = x.view(x.size(0), -1)
    x = nn.functional.relu(self.fc1(x))
    x = self.fc2(x)
    x = self.sigmoid(x)
    return x
</code></pre>
<h1>
<a name="create-an-instance-of-your-model-7" class="anchor" href="#create-an-instance-of-your-model-7"></a>Create an instance of your model</h1>
<p>model = AllergyClassifier()</p>
<h1>
<a name="define-the-loss-function-and-optimizer-8" class="anchor" href="#define-the-loss-function-and-optimizer-8"></a>Define the loss function and optimizer</h1>
<p>criterion = nn.BCELoss()<br>
optimizer = optim.Adam(model.parameters(), lr=0.001)</p>
<h1>
<a name="set-the-device-9" class="anchor" href="#set-the-device-9"></a>Set the device</h1>
<p>device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’)<br>
model.to(device)</p>
<h1>
<a name="training-loop-10" class="anchor" href="#training-loop-10"></a>Training loop</h1>
<p>num_epochs = 10<br>
for epoch in range(num_epochs):<br>
model.train()<br>
running_loss = 0.0</p>
<pre><code>for images, labels in train_loader:
    images = images.to(device)
    labels = labels.to(device)
    
    optimizer.zero_grad()
    
    outputs = model(images)
    loss = criterion(outputs.squeeze(), labels.float())
    
    loss.backward()
    optimizer.step()
    
    running_loss += loss.item() * images.size(0)

epoch_loss = running_loss / len(train_dataset)
print(f'Training Loss - Epoch {epoch+1}: {epoch_loss:.4f}')
</code></pre>
<h1>
<a name="validation-loop-11" class="anchor" href="#validation-loop-11"></a>Validation loop</h1>
<p>model.eval()<br>
num_correct = 0<br>
num_samples = 0</p>
<p>with torch.no_grad():<br>
for images, labels in val_loader:<br>
images = images.to(device)<br>
labels = labels.to(device)</p>
<pre><code>    outputs = model(images)
    predictions = (outputs &gt;= 0.5).squeeze().long()
    
    num_correct += (predictions == labels).sum().item()
    num_samples += labels.size(0)

accuracy = num_correct / num_samples
print(f'Validation Accuracy: {accuracy:.4f}')
</code></pre>
<p>facing some issue</p>

ptrblck: <p>The error is raised in <code>self.fc1</code> as its <code>in_features</code> do not match the number of features of the input activation. The error message shows the feature size of the activation, so change the <code>in_features</code> to this value and it should work.</p>