Convert Torchaudio melspectograms for ResNet networks

Giuseppe_Sarno: <p>Hello,<br>
I am building a Sound classifier and using Torchaudio. The Wav file is loaded and then transformed this way:</p>
<pre><code class="lang-auto">mel_spectrogram = torchaudio.transforms.MelSpectrogram(
    sample_rate=SAMPLE_RATE,
    n_fft=1024,
    hop_length=512,
    n_mels=64
)
size=224
transform_spectra = T.Compose([
    mel_spectrogram,
    T.Resize(size),
    T.CenterCrop(size),
    T.ToTensor(),
    T.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225]),
])
</code></pre>
<p>I then created a network with ResNet</p>
<pre><code class="lang-auto">class Net(nn.Module):
    def __init__(self):
        super().__init__()
        # Use a pretrained model
        self.network = models.resnet34(pretrained=True)
        # Replace last layer
        num_ftrs = self.network.fc.in_features
        self.network.fc = nn.Linear(num_ftrs, 2)
    def forward(self, xb):
        return self.network(xb)
    def freeze(self):
        for param in self.network.parameters():
            param.require_grad = False
        for param in self.network.fc.parameters():
            param.require_grad = True
    def unfreeze(self):
        for param in self.network.parameters():
            param.require_grad = True
</code></pre>
<p>and just changed the last FC to only have 2 classes.</p>
<p>However I get this error when I run the training.</p>
<pre><code class="lang-auto">/opt/conda/lib/python3.8/site-packages/torchvision/transforms/functional.py in to_tensor(pic)
    112     """
    113     if not(F_pil._is_pil_image(pic) or _is_numpy(pic)):
--&gt; 114         raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))
    115 
    116     if _is_numpy(pic) and not _is_numpy_image(pic):

TypeError: pic should be PIL Image or ndarray. Got &lt;class 'torch.Tensor'&gt;

</code></pre>
<p>Can anybody help ?</p>
<p>P.S. Is there some tutorial for training data converted to melspectrograms with a ResNet ? I would think this is a standard problem for sound clarification but not many tutorial out there.</p>
<p>UPDATE:</p>
<p>I modified the transfor and removed the ToTensor</p>
<pre><code class="lang-auto">transform_spectra = T.Compose([
    mel_spectrogram,
    T.Resize(size),
    T.CenterCrop(size),
    #T.ToTensor(),
    T.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),
    T.Normalize((0.5,),(0.5,)),
])
</code></pre>
<p>but then I received the following error.</p>
<pre><code class="lang-auto">Given groups=1, weight of size [64, 3, 7, 7], expected input[1, 1, 224, 224] to have 3 channels, but got 1 channels instead
</code></pre>
<p>I then googled and a bit and then modified the net and changed the input size like below:</p>
<pre><code class="lang-auto">class Net(nn.Module):

    def __init__(self):
        super().__init__()
        # Use a pretrained model
        self.network = models.resnet34(pretrained=True)
        # Replace last layer
        self.network.conv1=nn.Conv2d(1, self.network.conv1.out_channels, 
                      kernel_size=self.network.conv1.kernel_size[0], 
                      stride=self.network.conv1.stride[0], 
                      padding=self.network.conv1.padding[0])
        num_ftrs = self.network.fc.in_features
        self.network.fc = nn.Linear(num_ftrs, 2)
    def forward(self, xb):
        return self.network(xb)
    def freeze(self):
        for param in self.network.parameters():
            param.require_grad = False
        for param in self.network.fc.parameters():
            param.require_grad = True
    def unfreeze(self):
        for param in self.network.parameters():
            param.require_grad = True
model_ft = Net() 
</code></pre>
<p>Is this right / normal in those circumstances ? or the model will work best if the input is of dimension 3 (color) and not grayscale ?<br>
I also freeze the weights before the training. I am sure this is correct for the FC layer but would this not have an effect on the Conv1 layer ?</p>
<p>Sorry just a novice and not looked into CNN in few years now.</p>
<p>Thanks in advance.</p>

ptrblck: <aside class="quote no-group" data-username="Giuseppe_Sarno" data-post="1" data-topic="163385">
<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/giuseppe_sarno/48/19617_2.png" class="avatar"> Giuseppe_Sarno:</div>
<blockquote>
<p>I also freeze the weights before the training. I am sure this is correct for the FC layer but would this not have an effect on the Conv1 layer ?</p>
</blockquote>
</aside>
<p>In your current approach you are replacing the pretrained <code>conv1</code> layer with a randomly initialized <code>nn.Conv2d</code> layer. Afterwards you are freezing its random parameters without any training, so you might want to consider training it too.<br>
Alternatively, you could also try to e.g. repeat the single channel of your input 3 times and pass it to the pretrained conv layer accepting inputs with 3 channels.</p>

Giuseppe_Sarno: <p>Thanks for your reply and sorry for asking.</p>
<ol>
<li>is there a away  I can easily do this ? I think I’d rather keep the Conv layer untouched to avoid the retraining.</li>
<li>Is there a version of mel spectrogram in RGB as it is displayed on the screen or does not make sense ?</li>
</ol>
<p>I am also now facing another issue with normalizing the input to the resnet.<br>
I do not want to crop the image as my algorithm is based on tagging images with the presence of the beep and cropping might remove beeps that are just entering the image.<br>
Is it ok if I just used the following compose and give the output to the ResNet ?</p>
<p>I assume based on the issues above, I will not be able to use what mentioned here <a href="https://pytorch.org/hub/pytorch_vision_resnet/" class="inline-onebox" rel="noopener nofollow ugc">ResNet | PyTorch</a><br>
as the spectrogram is not a simple image as in the example.</p>
<pre><code class="lang-auto">transform_spectra = T.Compose([
    mel_spectrogram,
    T.Resize((size,size)),
    T.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]),
])
</code></pre>

ptrblck: <ol>
<li>Yes, you could use <code>x = x.repeat(1, 3, 1, 1)</code> to repeat the single channel 3 times assuming <code>x</code> was in the shape <code>[batch_size, 1, height, width]</code>.</li>
<li>The visualization using a colormap and maps the single channel value to it. You could also try to use these colormap-encoded images, but I’m unsure if you would get any benefit from it.</li>
</ol>
<p>I’m unsure what the exact issue with the normalization is. Are you concerned about the <code>Resize</code> operation or the stats values?</p>

Giuseppe_Sarno: <aside class="quote no-group" data-username="ptrblck" data-post="4" data-topic="163385">
<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/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>I’m unsure what the exact issue with the normalization is. Are you concerned about the <code>Resize</code> operation or the stats values?</p>
</blockquote>
</aside>
<p>Hi I am mostly concerned with not providing the right value ranges for ResNet. It is not clear what the right conversion should be from the torchaudio.melspectrogram format to the the right format to input the ResNet. Most of the examples use PILImage and crop . I have not seen example taking torchaudio.melspectrogram and ingests into a resnet.</p>
<p>Thanks you.</p>

ptrblck: <p>The posted <code>mean</code> and <code>std</code> values are calculated from the ImageNet training dataset and normalize the input batches to have a zero mean and a unit variance. You could either calculate new stats from your training data or just try to use the normalized input tensors in the range <code>[0, 1]</code>.</p>

Giuseppe_Sarno: <p>Ok let’s see if I understood well. I only need to normalize with the published transform if my input data is the same (or similar) as the one used for training the model. Otherwise as long as my data is normalized to be between [0,1] than I do not need any further normalization.</p>
<p>Just one more clarification is the range with positive values between 0 and 1 or 0 is the mean and 1 is the variance so values are between -1 and 1 ? does it matter ?</p>
<p>Thanks very much in advance.</p>

ptrblck: <aside class="quote no-group" data-username="Giuseppe_Sarno" data-post="7" data-topic="163385">
<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/giuseppe_sarno/48/19617_2.png" class="avatar"> Giuseppe_Sarno:</div>
<blockquote>
<p>Otherwise as long as my data is normalized to be between [0,1] than I do not need any further normalization.</p>
</blockquote>
</aside>
<p>It depends on your use case, but generally normalizing the data helps in model convergence.<br>
The <code>Normalize</code> transformation subtracts the passed <code>mean</code> and divides by the <code>std</code> so that the samples have a zero mean and unit variance, which helps even more than a normalization via scaling.<br>
I would recommend to experiment with a few approaches to see which one works for your use case.</p>