Label | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|---|---|
Description | T-shirt | Trouser | Pullover | Dress | Coat | Sandal | Shirt | Sneaker | Bag | Ankle boot |
import time
import torch
import numpy as np
from torch import nn, optim
import torchvision
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
###################fashion mnist数据集加载######################
def load_data_fashion_mnist(batch_size, resize=None, root='./Datasets/FashionMNIST'):
"""Download the fashion mnist dataset and then load into memory."""
trans = []
if resize:
trans.append(torchvision.transforms.Resize(size=resize))
trans.append(torchvision.transforms.ToTensor())
transform = torchvision.transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(root=root, train=True, download=True, transform=transform)
mnist_test = torchvision.datasets.FashionMNIST(root=root, train=False, download=True, transform=transform)
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True)
test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False)
return train_iter, test_iter
#################################################################
batch_size = 32
train_iter, test_iter = load_data_fashion_mnist(batch_size)
num_inputs = 784
num_outputs = 10
class LinearNet(nn.Module):
def __init__(self, num_inputs, num_outputs):
super(LinearNet, self).__init__()
self.linear = nn.Linear(num_inputs, num_outputs)
def forward(self, x): # x 的形状: (batch, 1, 28, 28)
y = self.linear(x.view(x.shape[0], -1))
return y
class FlattenLayer(nn.Module):
def __init__(self):
super(FlattenLayer, self).__init__()
def forward(self, x): # x 的形状: (batch, *, *, ...)
return x.view(x.shape[0], -1)
from collections import OrderedDict
net = nn.Sequential(
OrderedDict([
('flatten', FlattenLayer()),
('linear', nn.Linear(num_inputs, num_outputs))])
)
print(net)
Sequential(
(flatten): FlattenLayer()
(linear): Linear(in_features=784, out_features=10, bias=True)
)
nn.init.normal_(net.linear.weight, mean=0, std=0.01)
nn.init.constant_(net.linear.bias, val=0)
Parameter containing:
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], requires_grad=True)
loss = nn.CrossEntropyLoss()
def execute(sql):
from tqdm.notebook import tqdm
from time import sleep
from IPython.display import display, HTML, clear_output
import pandas as pd
global _sql_execute_result, o
if "o" not in globals():
print("Please run odps configuration cell first")
return
if "_sql_execute_result" not in globals():
_sql_execute_result = {}
bar = tqdm(total=1, desc='Preparing sql query')
progress = None
instance = o.run_sql(sql)
bar.update(1)
display(
HTML(
f'Open LogView to checkout details'
)
)
finished_last_loop = 0
while not instance.is_terminated():
task_progress = instance.get_task_progress(instance.get_task_names())
stages = task_progress.stages
finished = sum(map(lambda x: x.terminated_workers, stages))
total = sum(map(lambda x: x.total_workers, stages))
if progress:
if len(stages) == 0:
progress.update(total)
else:
progress.update(finished - finished_last_loop)
finished_last_loop = finished
elif not progress and len(stages) == 0:
continue
else:
progress = tqdm(total=total, desc='executing sql query')
progress.update(finished - finished_last_loop)
finished_last_loop = finished
sleep(1)
print('The data is being formatted. If the amount of data is large, it will take a while')
df = instance.open_reader().to_pandas()
result_key = len(_sql_execute_result.keys())
_sql_execute_result[result_key] = df
pd.options.display.html.table_schema = True
pd.options.display.max_rows = None
clear_output()
print("you can find execute result in global variable: _sql_execute_result[{}]".format(result_key))
return df
execute('''''')
def accuracy(y_hat, y):
return (y_hat.argmax(dim=1) == y).float().mean().item()
def evaluate_accuracy(data_iter, net):
acc_sum, n = 0.0, 0
for X, y in data_iter:
acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()
n += y.shape[0]
return acc_sum / n
num_epochs = 5
def train_ch(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, optimizer=None):
for epoch in range(num_epochs):
train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
for X, y in train_iter:
y_hat = net(X)
l = loss(y_hat, y).sum()
# 梯度清零
if optimizer is not None:
optimizer.zero_grad()
elif params is not None and params[0].grad is not None:
for param in params:
param.grad.data.zero_()
l.backward()
optimizer.step()
train_l_sum += l.item()
train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
n += y.shape[0]
test_acc = evaluate_accuracy(test_iter, net)
print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
% (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))
train_ch(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)
epoch 1, loss 0.0185, train acc 0.799, test acc 0.822
选择题:
softmax([100, 101, 102])
的结果等于以下的哪一项
softmax([10.0, 10.1, 10.2])
softmax([-100, -101, -102])
softmax([-2, -1, 0])
softmax([1000, 1010, 1020])
答案:
通过将网络结构修改成上述的卷积形式。