Binary Classification of MNIST with pytorch

username: Arhazf
cooked: <p>Hi,<br>
Here I have a simple 2-layers fully connected neural network, but I am not sure how I can convert input images to binary form in pytorch? Thank you in advance.</p>
<pre><code>Data_tr = datasets.MNIST('../data', train=True, download=True,
                         transform=transforms.Compose([
                             transforms.Grayscale(),
                             transforms.ToTensor(),
                             transforms.Normalize((0.1307,), (0.3081,))]))

train_set = torch.utils.data.DataLoader(Data_tr, batch_size=batch_size, shuffle=True)
Data_ts = datasets.MNIST('../data', train=False, transform=transforms.Compose([
    transforms.Grayscale(),
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))]))


test_set = torch.utils.data.DataLoader(Data_ts, batch_size=batch_size, shuffle=True)

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(28 * 28, 64)
        self.fc2 = nn.Linear(64, 10)
        #W1 = list(self.fc1.parameters())
        #print("w1:", len(W1[1]))
        nn.init.xavier_normal_(self.fc1.weight)
        nn.init.xavier_normal_(self.fc2.weight)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)

net = Net()
print(net)</code></pre>

username: mailcorahul
cooked: <p>By binary form, do you mean thresholding images(only 0 and 1) rather than using them as grayscale images?<br>
If that’s the case, I don’t think transforms has a function to threshold an image. You can write a custom dataset class which converts the image to binary form</p>
<pre><code class="lang-auto">class BinaryMNIST(Dataset):
    def __init__(self):
        self.images , self.labels = ##using datasets.MNIST
    def __getitem__(self, idx):
        image, label = self.images[idx], self.labels[idx]
        image[image &lt; 127] = 0
        image[image &gt;= 127] = 255
        # do the necessary transforms ...
        return image, label</code></pre>

username: Arhazf
cooked: <p>Thank you for your response.</p>
<p>Sorry I am a beginer and I have some additional questions:</p>
<ol>
<li>
<p>What is Dataset in the first line? Should I write the train_set instead? or should I define a new dataset?</p>
</li>
<li>
<p>What do you mean “using datasets.MNIST” in the def__init__ function? According to my code, I wrote  self.images , self.labels = Data_tr but I got an error.</p>
</li>
</ol>

username: mailcorahul
cooked: <ol>
<li>‘Dataset’ here is an abstract class defined in torch.utils.data which should be subclassed when creating a custom dataset class - <a href="https://pytorch.org/docs/stable/data.html?highlight=dataset#torch.utils.data.Dataset" rel="nofollow noopener">https://pytorch.org/docs/stable/data.html?highlight=dataset#torch.utils.data.Dataset</a>.</li>
</ol>
<pre><code class="lang-auto">binary_mnist = BinaryMNIST()
train_loader = torch.utils.data.DataLoader(binary_mnist, batch_size=batch_size, shuffle=True)
</code></pre>
<ol start="2">
<li>You can do dir(Data_tr) to check for the attributes. It has two variables - train_data and train_labels.<br>
Assign them accordingly inside init method.</li>
</ol>
<pre><code class="lang-auto">self.images, self.labels = Data_tr.train_data, Data_tr.train_labels
</code></pre>
<p>Check out this link for dataset/dataloader tutorial:<br>
<a href="https://pytorch.org/tutorials/beginner/data_loading_tutorial.html" class="onebox" target="_blank" rel="nofollow noopener">https://pytorch.org/tutorials/beginner/data_loading_tutorial.html</a></p>

username: Arhazf
cooked: <p>Thank you very much. It is solved.</p>

username: anu
cooked: <aside class="quote no-group" data-username="mailcorahul" data-post="2" data-topic="56416">
<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/mailcorahul/48/15919_2.png" class="avatar"> mailcorahul:</div>
<blockquote>
<pre><code class="lang-auto">class BinaryMNIST(Dataset):
    def __init__(self):
        self.images , self.labels = ##using datasets.MNIST
    def __getitem__(self, idx):
        image, label = self.images[idx], self.labels[idx]
        image[image &lt; 127] = 0
        image[image &gt;= 127] = 255
        # do the necessary transforms ...
        return image, label
</code></pre>
</blockquote>
</aside>
<p>hello <a class="mention" href="/u/mailcorahul">@mailcorahul</a></p>
<p>do you think normalizing would make sense if I binarize the MNIST set?</p>
<p>thanks in advance!</p>