[cs231n Query] output with shape [1, 32, 32] doesn't match the broadcast shape [3, 32, 32]

VDzungsignature: <p><strong>Hello every one. I doing cs231n 's last assignment: Self supervised learning and have a trouble:</strong><br>
<strong>Here is the code:</strong></p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/7/7/77fb98bf10eacd96d988c76464b9b78617b0842f.png" data-download-href="https://discuss.pytorch.org/uploads/default/77fb98bf10eacd96d988c76464b9b78617b0842f" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/7/7/77fb98bf10eacd96d988c76464b9b78617b0842f.png" alt="image" data-base62-sha1="h7pRsST4XqlSjBHzOUPEl4oeTLx" width="690" height="284" data-dominant-color="2A2C2C"><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">994×410 25.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>
<p><strong>The error is:</strong><br>
…<br>
return F.normalize(tensor, self.mean, self.std, self.inplace)<br>
File “c:\Users\Admin\Anaconda3\lib\site-packages\torchvision\transforms\functional.py”, line 363, in normalize<br>
tensor.sub_(mean).div_(std)<br>
RuntimeError: output with shape [1, 32, 32] doesn’t match the broadcast shape [3, 32, 32]<br>
…</p>
<p><strong>I know this issue relates to the transform: here is the transform (also the required solution of assignment so I dont want to change it)</strong><br>
…<br>
def compute_train_transform(seed=123456):<br>
“”"<br>
This function returns a composition of data augmentations to a single training image.<br>
Complete the following lines. Hint: look at available functions in torchvision.transforms<br>
“”"<br>
torch.random.seed(seed)<br>
random.manual_seed(seed)<br>
# Transformation that applies color jitter with brightness=0.4, contrast=0.4, saturation=0.4, and hue=0.1<br>
color_jitter = transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)<br>
train_transform = transforms.Compose ([<br>
# Step 1: Randomly resize and crop to 32x32.<br>
transforms.RandomResizedCrop(32),<br>
# Step 2: Horizontally flip the image with probability 0.5<br>
transforms.RandomHorizontalFlip(p=0.5),<br>
# Step 3: With a probability of 0.8, apply color jitter (you can use “color_jitter” defined above.<br>
transforms.RandomApply(torch.nn.ModuleList([color_jitter]), p=0.8),<br>
# Step 4: With a probability of 0.2, convert the image to grayscale<br>
transforms.RandomApply(torch.nn.ModuleList([transforms.Grayscale()]), p=0.2),<br>
transforms.ToTensor(),<br>
transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])])<br>
return train_transform<br>
…</p>
<p><strong>I dont have this issue before. My current version is:</strong><br>
<strong>The torch version is 1.11.0</strong><br>
<strong>and torchvision version is 0.12.0</strong></p>
<p><strong>Could any one know how to solve this issue?</strong></p>
<p><strong>Thank you very much</strong></p>

ptrblck: <p>The issue is raised in the <code>Noemalize</code> transformation as it expects an input with 3 channels (since the stats contain 3 values each) while the previous <code>GrayScale</code> transformation will create an output containing a single channel.<br>
You could use <code>Grayscale(num_output_channels=3)</code> to repeat the gray color channel, but would then have to consider changing the stats of <code>Normalize</code> as you are currently using different values for each (RGB) channel.</p>

VDzungsignature: <p>I have tried transforms.Grayscale(num_output_channels=3) this method and it work .<br>
When I train the model with the following code, I get another issue. I guess it is related to mentioned transform function:</p>
<p>…</p>
<h3>
<a name="prepare-the-data-1" class="anchor" href="#prepare-the-data-1"></a>#  Prepare the data.</h3>
<p>train_transform = compute_train_transform(seed=2147483647)</p>
<p>train_data = CIFAR10Pair(root=‘E:/ALL_COURSE/CS231n/Lecture 12/assignment3/cs231n/datasets/CIFA10’, train=True, transform=train_transform, download=True)</p>
<p>train_data = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))</p>
<p>train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=2, pin_memory=True, drop_last=True)</p>
<h3>
<a name="set-up-the-model-and-optimizer-config-2" class="anchor" href="#set-up-the-model-and-optimizer-config-2"></a>#  Set up the model and optimizer config.</h3>
<p>model = Model(feature_dim)</p>
<p>model.load_state_dict(torch.load(pretrained_path, map_location=‘cpu’), strict=False)</p>
<p>model = model.to(device)</p>
<p>flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))</p>
<p>flops, params = clever_format([flops, params])</p>
<p>optimizer = optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-6)</p>
<p>c = len(memory_data.classes)</p>
<h3>
<a name="training-loop-3" class="anchor" href="#training-loop-3"></a>#  Training loop.</h3>
<p>results = {‘train_loss’: [], ‘test_acc@1’: [], ‘test_acc@5’: []} #&lt;&lt; – output</p>
<p>best_acc = 0.0</p>
<p>for epoch in range(1, epochs + 1):</p>
<p>train_loss = train(model, train_loader, optimizer, epoch, epochs, batch_size=batch_size, temperature=temperature, device=device) ==&gt;  <strong>this is where I get the error</strong></p>
<p>…</p>
<p><strong>I go the following errors:</strong></p>
<p><em>TypeError: default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found &lt;class ‘torchvision.transforms.transforms.Compose’&gt;</em></p>
<p><strong>This errors come as when it loops the data loader as bellow:</strong></p>
<p>…</p>
<p>total_loss, total_num, train_bar = 0.0, 0, tqdm(data_loader)</p>
<p>for data_pair in train_bar: è this is when the error comes</p>
<p>……</p>
<p><strong>Where my train_transform would be like:</strong></p>
<p>…<br>
def compute_train_transform(seed=123456):<br>
“”"<br>
This function returns a composition of data augmentations to a single training image.<br>
Complete the following lines. Hint: look at available functions in torchvision.transforms<br>
“”"<br>
torch.random.seed(seed)<br>
random.manual_seed(seed)<br>
color_jitter = transforms.ColorJitter(0.4, 0.4, 0.4, 0.1)<br>
train_transform = transforms.Compose ([<br>
transforms.RandomResizedCrop(32),<br>
transforms.RandomHorizontalFlip(p=0.5),<br>
transforms.RandomApply(torch.nn.ModuleList([color_jitter]), p=0.8),<br>
transforms.RandomApply(torch.nn.ModuleList([transforms.Grayscale(num_output_channels=3)]), p=0.2),<br>
transforms.ToTensor(),<br>
transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])])<br>
return train_transform<br>
…</p>
<p><strong>I have tried several ways to such as include the transforms.ToTensor() into the function, howerver, it does not work.</strong><br>
<strong>Note: this is not what I want to ask for solution of the assignment. It is that the given code does not work with my environment (such as pytorch version, torch version, …) and it takes me quite a lot of time to fix it.</strong></p>

ptrblck: <p>Your <code>CIFAR10Pair</code> dataset seems to return a <code>torchvision.transforms.transforms.Compose</code> instead of the transformed samples.</p>
<p>PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier.</p>

VDzungsignature: <p>Thank you,<br>
The above problem solved. When I run training (with same code above), I got the following error:<br>
“PicklingError: Can’t pickle &lt;class ‘cs231n.simclr.data_utils.CIFAR10Pair’&gt;: it’s not the same object as cs231n.simclr.data_utils.CIFAR10Pair”?<br>
Could you help me to solve this issue?</p>