<jupyter_start><jupyter_text>$example$<jupyter_code>logits = torch.rand(4,10)
pred = F.softmax(logits,dim = 1)
pred.shape
pred_label = pred.argmax(dim = 1)
pred_label
logits.argmax(dim = 1)
label = torch.tensor([5,4,3,9])
correct = torch.eq(pred_label,label)
correct
correct.sum().float().sum()/4<jupyter_output><empty_output><jupyter_text>$When\space to\space test$- $test\space once\space per \space several \space batch$- $test\space once\space per \space epoch$- $epoch\space V.S.\space step$<jupyter_code>learning_rate = 1e-2
batch_size = 64
epochs = 10
train_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('datasets/mnist_data',
                train=True,
                download=True,
                transform=torchvision.transforms.Compose([
                torchvision.transforms.ToTensor(),                       # 数据类型转化
                torchvision.transforms.Normalize((0.1307, ), (0.3081, )) # 数据归一化处理
    ])), batch_size=batch_size,shuffle=True)

test_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST('datasets/mnist_data/',
                train=False,
                download=True,
                transform=torchvision.transforms.Compose([
                torchvision.transforms.ToTensor(),
                torchvision.transforms.Normalize((0.1307, ), (0.3081, ))
    ])),batch_size=batch_size,shuffle=False)
class MLP(nn.Module):
    def __init__(self):
        super(MLP,self).__init__()
        self.model = nn.Sequential(
            nn.Linear(784,200),
            nn.LeakyReLU(inplace = True),
            nn.Linear(200,200),
            nn.LeakyReLU(inplace = True),
            nn.Linear(200,10),
            nn.LeakyReLU(inplace = True)
        )
        
    def forward(self,x):
        x = self.model(x)
        
        return x
device = torch.device('cuda:0')
net = MLP().to(device)
optimizer = optim.SGD(net.parameters(),lr = learning_rate)
criteon = nn.CrossEntropyLoss().to(device)
for epoch in range(epochs):
    for batch_idx,(data,target) in enumerate(train_loader):
        data = data.view(-1,28*28)
        data,target = data.to(device),target.to(device)
        
        logits = net(data)
        loss = criteon(logits,target)
        
        optimizer.zero_grad()
        loss.backward()
        
        optimizer.step()
        
        if batch_idx % 100 == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                       100. * batch_idx / len(train_loader), loss.item()))
            
    test_loss = 0
    correct = 0
    for data, target in test_loader:
        data = data.view(-1, 28 * 28)
        data, target = data.to(device), target.cuda()
        logits = net(data)
        test_loss += criteon(logits, target).item()

        pred = logits.data.max(1)[1]
        correct += pred.eq(target.data).sum()

    test_loss /= len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))<jupyter_output>Train Epoch: 0 [0/60000 (0%)]	Loss: 2.300152
Train Epoch: 0 [6400/60000 (11%)]	Loss: 2.038405
Train Epoch: 0 [12800/60000 (21%)]	Loss: 1.609878
Train Epoch: 0 [19200/60000 (32%)]	Loss: 0.948645
Train Epoch: 0 [25600/60000 (43%)]	Loss: 0.578279
Train Epoch: 0 [32000/60000 (53%)]	Loss: 0.397320
Train Epoch: 0 [38400/60000 (64%)]	Loss: 0.392897
Train Epoch: 0 [44800/60000 (75%)]	Loss: 0.433338
Train Epoch: 0 [51200/60000 (85%)]	Loss: 0.350583
Train Epoch: 0 [57600/60000 (96%)]	Loss: 0.291713

Test set: Average loss: 0.0053, Accuracy: 9023/10000 (90%)

Train Epoch: 1 [0/60000 (0%)]	Loss: 0.703412
Train Epoch: 1 [6400/60000 (11%)]	Loss: 0.318359
Train Epoch: 1 [12800/60000 (21%)]	Loss: 0.486072
Train Epoch: 1 [19200/60000 (32%)]	Loss: 0.137833
Train Epoch: 1 [25600/60000 (43%)]	Loss: 0.274568
Train Epoch: 1 [32000/60000 (53%)]	Loss: 0.239691
Train Epoch: 1 [38400/60000 (64%)]	Loss: 0.116818
Train Epoch: 1 [44800/60000 (75%)]	Loss: 0.272905
Train Epoch: 1 [51200/60000 (85%)]	Loss: 0.426216
T[...]
{'fraction_non_alphanumeric': 0.15488215488215487, 'fraction_numerical': 0.11231361231361231, 'mean_word_length': 2.770625566636446, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '539250', 'license': 'MIT', 'n_tokens_mistral': 1868, 'n_tokens_neox': 1530, 'n_words': 308, 'path': 'Pytorch/Pytorch_learn_by_dragen1860/lesson26-MNIST测试.ipynb', 'repo_name': 'tsuirak/skills', 'size': '4158'}