# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/tykimos/Keras/blob/master/Pytorch_Fashion_MNIST.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="pWWAuDqukdyj" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 651, "referenced_widgets": ["9a40d6298e5245b78b004bb9a2cd8ee7", "94f4c1242def40e79ceca38b68c950ee", "c52e0e0c7a1f4b2090c5f2ec11877c3e", "14f32865008644b49f67a1457b9c498a", "35af5368826a405381b1c2901deac07b", "f242f4292e5f4d6da5901c230f6d6697", "223aa01f04a6403584bc9e519d66e133", "0e25fe1acd0a48db8e3f3baf5e8948ae", "ee0ad9ec2fa5440e96ed515c862d9a00", "dc496a4b58ef4805aba9fd1911394cd7", "7d76865129ff4537b00974d835b39af6", "<KEY>", "9f193b4f02964be28897c653addab2e2", "<KEY>", "<KEY>", "f46723c9abe8433890783856f7e42d38", "<KEY>", "9be074cfd647476dbf0a6b396a43f04a", "89b0d5ef4a934ce1bdc9c9cd5cc6209e", "<KEY>", "<KEY>", "3083c2ba81b341ae8d9f7fed49bda3d9", "9f9d66f8acec45adb9856dccaf402686", "01284b3137e4401a879dd7b09df41ab7", "<KEY>", "<KEY>", "c1cba18894df4aa1a6e7fa33db5865a6", "<KEY>", "c50dd3f6415e4de3bb1e5a08ccc544da", "3ea02d1106bb4918b96f6de302a4911c", "8c19029135134492baf8e671e0d2b951", "a6e1b7dc02bb47f4a0bc77fa8d2affe2"]} outputId="ce69e049-5274-49a7-8502-0b0b167ae813"
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.init as init

import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data import DataLoader

batch_size = 256
learning_rate = 0.0002
num_epoch = 10

mnist_train = dset.FashionMNIST("../", train=True, transform=transforms.ToTensor(), target_transform=None, download=True)
mnist_test = dset.FashionMNIST("../", train=False, transform=transforms.ToTensor(), target_transform=None, download=True)

train_loader = torch.utils.data.DataLoader(mnist_train,batch_size=batch_size, shuffle=True,num_workers=2,drop_last=True)
test_loader = torch.utils.data.DataLoader(mnist_test,batch_size=batch_size, shuffle=False,num_workers=2,drop_last=False)

class Linear(nn.Module):
    def __init__(self):
        super(Linear,self).__init__()
        self.layer = nn.Sequential(
            nn.Linear(784,300),
            nn.ReLU(),
            nn.Linear(300,100),
            nn.ReLU(),
            nn.Linear(100,10)
        )       
        
    def forward(self,x):
        out = x.view(-1, 784)
        out = self.layer(out)
        return out

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

model = Linear().to(device)
loss_func = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

loss_arr =[]
for i in range(num_epoch):
    for j,[image,label] in enumerate(train_loader):
        x = image.to(device)
        y_= label.to(device)
        
        optimizer.zero_grad()
        output = model.forward(x)
        loss = loss_func(output,y_)
        loss.backward()
        optimizer.step()
        
        if j % 1000 == 0:
            print(loss)
            loss_arr.append(loss.cpu().detach().numpy())

correct = 0
total = 0

pred_labels = []

with torch.no_grad():
    for image,label in test_loader:
        x = image.to(device)
        y_= label.to(device)
        
        output = model.forward(x)
        _,output_index = torch.max(output,1)

        total += label.size(0)
        correct += (output_index == y_).sum().float()
        
        pred = output_index.to('cpu').numpy()
        pred_labels.extend(pred)

print("Accuracy of Test Data: {}".format(100*correct/total))
np.savetxt('submit.txt', pred_labels, fmt='%d')            

StarcoderdataJupyterScriptsDedupFiltered