533 KiB
533 KiB
In [1]:
import torch
import numpy
import pandas
from sympy.physics.control.control_plots import matplotlib
from torch.distributed.algorithms.ddp_comm_hooks.powerSGD_hook import batched_powerSGD_hook
In [2]:
torch.randn(3,4,2)Out [2]:
tensor([[[ 0.5509, -1.6216],
[ 0.1083, 0.4464],
[ 1.8819, 0.4029],
[-0.0733, 2.6961]],
[[-2.0316, 0.7172],
[-0.3774, 0.5248],
[-0.0134, 0.3256],
[ 0.3433, 0.1697]],
[[ 1.1434, 0.6595],
[ 0.2386, -0.6560],
[ 1.3177, -0.6876],
[-1.0916, -0.6199]]])In [3]:
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)Out [3]:
(tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 2., 1., 4., 3.],
[ 1., 2., 3., 4.],
[ 4., 3., 2., 1.]]),
tensor([[ 0., 1., 2., 3., 2., 1., 4., 3.],
[ 4., 5., 6., 7., 1., 2., 3., 4.],
[ 8., 9., 10., 11., 4., 3., 2., 1.]]))In [4]:
a = torch.arange(3).reshape((3, 1))
b = torch.arange(2).reshape((1, 2))
a, b
a+bOut [4]:
tensor([[0, 1],
[1, 2],
[2, 3]])In [5]:
X[-1], X[1:3]
Out [5]:
(tensor([ 8., 9., 10., 11.]),
tensor([[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]))In [6]:
A = X.numpy()
B = torch.tensor(A)
type(A), type(B)Out [6]:
(numpy.ndarray, torch.Tensor)
In [7]:
import os
os.makedirs(os.path.join("..","data"),exist_ok=True)
data_file = os.path.join(os.path.join("..","data","data.csv"))
with open(data_file, "w") as f:
f.write('NumRooms,Alley,Price\n') # 列名
f.write('NA,Pave,127500\n') # 每行表示一个数据样本
f.write('2,NA,106000\n')
f.write('4,NA,178100\n')
f.write('NA,NA,140000\n')
In [8]:
import pandas as pd
data = pd.read_csv(data_file)
print(data)
NumRooms Alley Price 0 NaN Pave 127500 1 2.0 NaN 106000 2 4.0 NaN 178100 3 NaN NaN 140000
In [9]:
inputs, outputs = data.iloc[:, 0:2], data.iloc[:, 2]
inputs = pd.get_dummies(inputs, dummy_na=True)
print(inputs)
inputs = inputs.fillna(inputs.mean())
print(inputs)
NumRooms Alley_Pave Alley_nan 0 NaN True False 1 2.0 False True 2 4.0 False True 3 NaN False True NumRooms Alley_Pave Alley_nan 0 3.0 True False 1 2.0 False True 2 4.0 False True 3 3.0 False True
In [10]:
X = torch.tensor(inputs.to_numpy(dtype=float))
y = torch.tensor(outputs.to_numpy(dtype=float))
X, y
Out [10]:
(tensor([[3., 1., 0.],
[2., 0., 1.],
[4., 0., 1.],
[3., 0., 1.]], dtype=torch.float64),
tensor([127500., 106000., 178100., 140000.], dtype=torch.float64))In [11]:
B=torch.tensor([[1,2,3],[2,0,4],[3,4,5]])
BOut [11]:
tensor([[1, 2, 3],
[2, 0, 4],
[3, 4, 5]])In [12]:
B==B.TOut [12]:
tensor([[True, True, True],
[True, True, True],
[True, True, True]])In [13]:
X=torch.arange(24).reshape(2,3,4)
XOut [13]:
tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])In [14]:
A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
B = A.clone() # 通过分配新内存,将A的一个副本分配给B
A, A + B
#A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
#B = A # 通过分配新内存,将A的一个副本分配给B
id(A),id(B)Out [14]:
(140556050244048, 140556050244432)
In [15]:
A*BOut [15]:
tensor([[ 0., 1., 4., 9.],
[ 16., 25., 36., 49.],
[ 64., 81., 100., 121.],
[144., 169., 196., 225.],
[256., 289., 324., 361.]])In [16]:
a=2
X=torch.arange(24).reshape(2,3,4)
a+X,(a*X).shapeOut [16]:
(tensor([[[ 2, 3, 4, 5],
[ 6, 7, 8, 9],
[10, 11, 12, 13]],
[[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 25]]]),
torch.Size([2, 3, 4]))In [17]:
print(A)
A_sum_axis0=A.sum(axis=0)
A_sum_axis1=A.sum(axis=1)
A_sum_axis0,A_sum_axis1Out [17]:
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.],
[16., 17., 18., 19.]])
(tensor([40., 45., 50., 55.]), tensor([ 6., 22., 38., 54., 70.]))
In [18]:
x=torch.arange(4,dtype=torch.float32)
torch.mv(A,x)Out [18]:
tensor([ 14., 38., 62., 86., 110.])
In [19]:
import time
def showtime(func):
def wrapper():
start = time.time()
result = func() # 执行原始函数
end = time.time()
print(f"执行时间: {end - start:.6f}秒")
return result
return wrapper # 返回包装函数
@showtime
def fun():
print("I am silly")
fun()
I am silly 执行时间: 0.000183秒
In [20]:
torch.norm(torch.ones((4, 9)))Out [20]:
tensor(6.)
In [21]:
x =torch.arange(4.0,requires_grad=True)
x.gradIn [22]:
y=2*torch.dot(x,x)
yOut [22]:
tensor(28., grad_fn=<MulBackward0>)
In [23]:
y.backward()
x.gradOut [23]:
tensor([ 0., 4., 8., 12.])
In [24]:
x.grad.zero_()
y = x.sum()
y.backward()
x.grad
Out [24]:
tensor([1., 1., 1., 1.])
In [25]:
# 对非标量调用backward需要传入一个gradient参数,该参数指定微分函数关于self的梯度。
# 本例只想求偏导数的和,所以传递一个1的梯度是合适的
x.grad.zero_()
y = x * x
# 等价于y.backward(torch.ones(len(x)))
print(y)
y.sum().backward()
x.gradOut [25]:
tensor([0., 1., 4., 9.], grad_fn=<MulBackward0>)
tensor([0., 2., 4., 6.])
In [26]:
torch.ones(len(x))Out [26]:
tensor([1., 1., 1., 1.])
In [27]:
x.grad.zero_()
y=x*x
u=y.detach()
z=u*x
z.sum().backward()
x.grad==uOut [27]:
tensor([True, True, True, True])
In [28]:
x.grad.zero_()
y.sum().backward()
x.grad==2*xOut [28]:
tensor([True, True, True, True])
In [29]:
from torch.distributions import multinomial
fair_probs=torch.ones([6])
fair_probsOut [29]:
tensor([1., 1., 1., 1., 1., 1.])
In [30]:
multinomial.Multinomial(1, fair_probs).sample()Out [30]:
tensor([0., 1., 0., 0., 0., 0.])
In [31]:
counts = multinomial.Multinomial(10, fair_probs).sample((500,))
cum_counts = counts.cumsum(dim=0)
cum_counts.size()Out [31]:
torch.Size([500, 6])
In [32]:
import matplotlib.pyplot as plt
# 假设 estimates 是你的数据张量
estimates = cum_counts / cum_counts.sum(dim=1, keepdims=True)
# 设置图形大小 (等效于 d2l.set_figsize)
plt.figure(figsize=(6, 4.5))
# 绘制每条概率曲线
for i in range(6):
plt.plot(estimates[:, i].numpy(),
label=f"P(die={i + 1})") # 使用 f-string 更简洁
# 添加理论概率水平线
plt.axhline(y=0.167, color='black', linestyle='dashed', label='Theoretical probability')
# 设置坐标轴标签
plt.xlabel('Groups of experiments')
plt.ylabel('Estimated probability')
# 添加图例
plt.legend()
# 显示图形
plt.show()
#plt.savefig('dice_probability.png', bbox_inches='tight')In [33]:
import numpy as np
class Timer:
"""记录多次运行时间"""
def __init__(self):
self.times = []
self.start()
def start(self):
"""启动计时器"""
self.tik = time.time()
def stop(self):
"""停止计时器并将时间记录在列表中"""
self.times.append(time.time() - self.tik)
return self.times[-1]
def avg(self):
"""返回平均时间"""
return sum(self.times) / len(self.times)
def sum(self):
"""返回时间总和"""
return sum(self.times)
def cumsum(self):
"""返回累计时间"""
return np.array(self.times).cumsum().tolist()In [34]:
n = 10000
a = torch.ones([n])
b = torch.ones([n])
c=torch.zeros(n)
timer = Timer()
for i in range(n):
c[i]=a[i]+b[i]
f'{timer.stop():.5f} sec'Out [34]:
'0.03117 sec'
In [35]:
timer.start()
d=a+b
f'{timer.stop():.5f} sec'Out [35]:
'0.00041 sec'
In [36]:
import math
def normal(x, mu, sigma):
p = 1 / math.sqrt(2 * math.pi * sigma**2)
return p * np.exp(-0.5 / sigma**2 * (x - mu)**2)In [37]:
from matplotlib_inline import backend_inline
def use_svg_display(): #@save
"""使用svg格式在Jupyter中显示绘图"""
backend_inline.set_matplotlib_formats('svg')
def set_figsize(figsize=(3.5, 2.5)): #@save
"""设置matplotlib的图表大小"""
use_svg_display()
plt.rcParams['figure.figsize'] = figsize
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
"""设置matplotlib的轴"""
axes.set_xlabel(xlabel)
axes.set_ylabel(ylabel)
axes.set_xscale(xscale)
axes.set_yscale(yscale)
axes.set_xlim(xlim)
axes.set_ylim(ylim)
if legend:
axes.legend(legend)
axes.grid()
def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):
"""绘制数据点"""
if legend is None:
legend = []
set_figsize(figsize)
axes = axes if axes else plt.gca()
# 如果X有一个轴,输出True
def has_one_axis(X):
return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list)
and not hasattr(X[0], "__len__"))
if has_one_axis(X):
X = [X]
if Y is None:
X, Y = [[]] * len(X), X
elif has_one_axis(Y):
Y = [Y]
if len(X) != len(Y):
X = X * len(Y)
axes.cla()
for x, y, fmt in zip(X, Y, fmts):
if len(x):
axes.plot(x, y, fmt)
else:
axes.plot(y, fmt)
set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)In [38]:
# 再次使用numpy进行可视化
x = np.arange(-7, 7, 0.01)
# 均值和标准差对
params = [(0, 1), (0, 2), (3, 1)]
plot(x, [normal(x, mu, sigma) for mu, sigma in params], xlabel='x',
ylabel='p(x)', figsize=(4.5, 2.5),
legend=[f'mean {mu}, std {sigma}' for mu, sigma in params])In [39]:
#注意一下matmul做向量乘上矩阵的时候不用考虑转置的情况
def synthetic_data(w, b, num_examples): #@save
"""生成y=Xw+b+噪声"""
X = torch.normal(0, 1, (num_examples, len(w)))
y = torch.matmul(X, w) + b
y += torch.normal(0, 0.01, y.shape)
return X, y.reshape((-1, 1))
In [40]:
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)In [41]:
set_figsize()
plt.scatter(features[:, (1)].detach().numpy(), labels.detach().numpy(), 1)Out [41]:
<matplotlib.collections.PathCollection at 0x7fd5c02b8830>
In [42]:
w=torch.normal(0,0.01,size=(2,1),requires_grad=True)
b=torch.zeros(1,requires_grad=True)
def linreg(X, w, b):
return torch.matmul(X,w)+b
def squared_loss(y_hat,y):
return (y_hat-y.reshape(y_hat.shape))**2/2
def sgd(params,lr,batch_size):
with torch.no_grad():
for param in params:
param-=lr*param.grad/batch_size
param.grad.zero_()
lr = 0.03
num_epochs =20
net = linreg
loss = squared_lossIn [43]:
import random
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
# 这些样本是随机读取的,没有特定的顺序
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
batch_indices = torch.tensor(
indices[i: min(i + batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices]In [44]:
batch_size =10
for X,y in data_iter(batch_size, features, labels):
print(X,'\n',y)
breaktensor([[-1.8455, -0.9126],
[-0.0299, 1.6530],
[-2.3513, 0.6457],
[ 0.1707, 0.8342],
[ 0.2096, -0.4362],
[ 0.6160, 1.7403],
[ 0.4242, 0.0484],
[-1.4459, 0.7434],
[ 0.5302, -0.5594],
[-0.5957, -1.5179]])
tensor([[ 3.6056],
[-1.4872],
[-2.6965],
[ 1.6980],
[ 6.1001],
[-0.4750],
[ 4.9009],
[-1.2270],
[ 7.1486],
[ 8.1680]])
In [45]:
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
l=loss(net(X, w, b), y)
l.sum().backward()
sgd([w,b],lr,batch_size)
with torch.no_grad():
train_l =loss(net(features, w, b), labels)
print(f'epoch {epoch+1}, train loss: {float(train_l.mean()):3f}')epoch 1, train loss: 0.030682 epoch 2, train loss: 0.000100 epoch 3, train loss: 0.000049 epoch 4, train loss: 0.000049 epoch 5, train loss: 0.000049 epoch 6, train loss: 0.000049 epoch 7, train loss: 0.000049 epoch 8, train loss: 0.000049 epoch 9, train loss: 0.000049 epoch 10, train loss: 0.000049 epoch 11, train loss: 0.000049 epoch 12, train loss: 0.000049 epoch 13, train loss: 0.000049 epoch 14, train loss: 0.000049 epoch 15, train loss: 0.000049 epoch 16, train loss: 0.000049 epoch 17, train loss: 0.000049 epoch 18, train loss: 0.000049 epoch 19, train loss: 0.000049 epoch 20, train loss: 0.000049
In [46]:
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')w的估计误差: tensor([-0.0002, 0.0003], grad_fn=<SubBackward0>) b的估计误差: tensor([0.0002], grad_fn=<RsubBackward1>)
In [47]:
from torch.utils import data
true_w = torch.tensor([2,-3.4])
true_b = 4.2
features,labels=synthetic_data(true_w, true_b, 1000)
def load_array(data_arrays,batch_size,is_train=True):
dataset = data.TensorDataset(*data_arrays)
return data.DataLoader(dataset,batch_size,shuffle=is_train)
batch_size = 10
data_iter = load_array((features,labels),batch_size)In [48]:
from torch import nn
net = nn.Sequential(nn.Linear(2, 1))
net[0].weight.data.normal_(0,0.001)
net[0].bias.data.fill_(0)Out [48]:
tensor([0.])
In [49]:
loss = nn.MSELoss()
trainer = torch.optim.SGD(net.parameters(), lr=0.01)
num_epochs = 3
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X) ,y)
trainer.zero_grad()
l.backward()
trainer.step()
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l:f}')
epoch 1, loss 0.599957 epoch 2, loss 0.011503 epoch 3, loss 0.000325
In [50]:
import torchvision
from torchvision import transforms
trans =transforms.ToTensor()
mnist_train = torchvision.datasets.FashionMNIST(root="./data",train=True,transform=trans,download=False)
mnist_test = torchvision.datasets.FashionMNIST(root="./data",train=False,transform=trans,download=False)
In [51]:
use_svg_display()
len(mnist_train),len(mnist_test)Out [51]:
(60000, 10000)
In [52]:
mnist_train[0][0].shapeOut [52]:
torch.Size([1, 28, 28])
In [53]:
def get_fashion_mnist_labels(labels):
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels]
In [54]:
def show_images(imgs, num_rows, num_cols, titles=None, scale=1): #@save
"""绘制图像列表"""
figsize = (num_cols * scale, num_rows * scale)
_, axes = plt.subplots(num_rows, num_cols, figsize=figsize)
axes = axes.flatten()
for i, (ax, img) in enumerate(zip(axes, imgs)):
if torch.is_tensor(img):
# 图片张量
ax.imshow(img.numpy())
else:
# PIL图片
ax.imshow(img)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if titles:
ax.set_title(titles[i])
return axesIn [55]:
X, y = next(iter(data.DataLoader(mnist_train, batch_size=18)))
print(X.shape)
show_images(X.reshape(18, 28, 28), 2, 9, titles=get_fashion_mnist_labels(y));torch.Size([18, 1, 28, 28])
In [56]:
batch_size = 256
def get_dataloader_workers():
"""使用4个进程来读取数据"""
return 4
train_iter = data.DataLoader(mnist_train, batch_size, shuffle=True,
num_workers=get_dataloader_workers())
timer = Timer()
for X, y in train_iter:
continue
f'{timer.stop():.2f} sec'Out [56]:
'2.26 sec'
In [57]:
def load_data_fashion_mnist(batch_size, resize=None):
"""下载Fashion-MNIST数据集,然后将其加载到内存中"""
trans = [transforms.ToTensor()]
if resize:
trans.insert(0, transforms.Resize(resize))
trans = transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(
root="./data", train=True, transform=trans, download=False)
mnist_test = torchvision.datasets.FashionMNIST(
root="./data", train=False, transform=trans, download=False)
return (data.DataLoader(mnist_train, batch_size, shuffle=True,
num_workers=get_dataloader_workers()),
data.DataLoader(mnist_test, batch_size, shuffle=False,
num_workers=get_dataloader_workers()))In [58]:
train_iter, test_iter = load_data_fashion_mnist(32, resize=64)
for X, y in train_iter:
print(X.shape, X.dtype, y.shape, y.dtype)
breaktorch.Size([32, 1, 64, 64]) torch.float32 torch.Size([32]) torch.int64
In [59]:
from IPython import display
batch_size = 256
train_iter, test_iter = load_data_fashion_mnist(32)
num_inputs = 784
num_outputs = 10
W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True)
b = torch.zeros(num_outputs, requires_grad=True)
X = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
X.sum(0, keepdim=True), X.sum(1, keepdim=True)
Out [59]:
(tensor([[5., 7., 9.]]),
tensor([[ 6.],
[15.]]))In [60]:
def softmax(X):
X_exp = torch.exp(X)
partition = X_exp.sum(1, keepdim=True)
return X_exp / partition # 这里应用了广播机制
X = torch.normal(0, 1, (2, 5))
X_prob = softmax(X)
X_prob, X_prob.sum(1)Out [60]:
(tensor([[0.4360, 0.2195, 0.2044, 0.0829, 0.0571],
[0.0678, 0.3243, 0.2988, 0.0572, 0.2519]]),
tensor([1.0000, 1.0000]))In [61]:
def net(X):
return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)In [62]:
y = torch.tensor([0, 2])
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
y_hat[[0, 1], y]Out [62]:
tensor([0.1000, 0.5000])
In [63]:
def cross_entropy(y_hat, y):
return - torch.log(y_hat[range(len(y_hat)), y])
cross_entropy(y_hat, y)Out [63]:
tensor([2.3026, 0.6931])
In [64]:
def accuracy(y_hat, y): #@save
"""计算预测正确的数量"""
if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
y_hat = y_hat.argmax(axis=1)
cmp = y_hat.type(y.dtype) == y
return float(cmp.type(y.dtype).sum())
accuracy(y_hat, y)/len(y)Out [64]:
0.5
In [65]:
class Accumulator: #@save
"""在n个变量上累加"""
def __init__(self, n):
self.data = [0.0] * n
def add(self, *args):
self.data = [a + float(b) for a, b in zip(self.data, args)]
def reset(self):
self.data = [0.0] * len(self.data)
def __getitem__(self, idx):
return self.data[idx]
In [66]:
def evaluate_accuracy(net, data_iter): #@save
"""计算在指定数据集上模型的精度"""
if isinstance(net, torch.nn.Module):
net.eval() # 将模型设置为评估模式
metric = Accumulator(2) # 正确预测数、预测总数
with torch.no_grad():
for X, y in data_iter:
metric.add(accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
In [67]:
evaluate_accuracy(net, test_iter)Out [67]:
0.0498
In [68]:
def train_epoch_ch3(net, train_iter, loss, updater): #@save
"""训练模型一个迭代周期(定义见第3章)"""
# 将模型设置为训练模式
if isinstance(net, torch.nn.Module):
net.train()
# 训练损失总和、训练准确度总和、样本数
metric = Accumulator(3)
for X, y in train_iter:
# 计算梯度并更新参数
y_hat = net(X)
l = loss(y_hat, y)
if isinstance(updater, torch.optim.Optimizer):
# 使用PyTorch内置的优化器和损失函数
updater.zero_grad()
l.mean().backward()
updater.step()
else:
# 使用定制的优化器和损失函数
l.sum().backward()
updater(X.shape[0])
metric.add(float(l.sum()), accuracy(y_hat, y), y.numel())
# 返回训练损失和训练精度
return metric[0] / metric[2], metric[1] / metric[2]In [69]:
class Animator: #@save
"""在动画中绘制数据"""
def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
ylim=None, xscale='linear', yscale='linear',
fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
figsize=(3.5, 2.5)):
# 增量地绘制多条线
if legend is None:
legend = []
use_svg_display()
self.fig, self.axes = plt.subplots(nrows, ncols, figsize=figsize)
if nrows * ncols == 1:
self.axes = [self.axes, ]
# 使用lambda函数捕获参数
self.config_axes = lambda: set_axes(
self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
self.X, self.Y, self.fmts = None, None, fmts
def add(self, x, y):
# 向图表中添加多个数据点
if not hasattr(y, "__len__"):
y = [y]
n = len(y)
if not hasattr(x, "__len__"):
x = [x] * n
if not self.X:
self.X = [[] for _ in range(n)]
if not self.Y:
self.Y = [[] for _ in range(n)]
for i, (a, b) in enumerate(zip(x, y)):
if a is not None and b is not None:
self.X[i].append(a)
self.Y[i].append(b)
self.axes[0].cla()
for x, y, fmt in zip(self.X, self.Y, self.fmts):
self.axes[0].plot(x, y, fmt)
self.config_axes()
display.display(self.fig)
display.clear_output(wait=True)
In [70]:
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): #@save
"""训练模型(定义见第3章)"""
animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9],
legend=['train loss', 'train acc', 'test acc'])
for epoch in range(num_epochs):
train_metrics = train_epoch_ch3(net, train_iter, loss, updater)
test_acc = evaluate_accuracy(net, test_iter)
animator.add(epoch + 1, train_metrics + (test_acc,))
train_loss, train_acc = train_metrics
assert train_loss < 0.5, train_loss
assert train_acc <= 1 and train_acc > 0.7, train_acc
assert test_acc <= 1 and test_acc > 0.7, test_accIn [71]:
lr = 0.1
def updater(batch_size):
return sgd([W, b], lr, batch_size)In [72]:
num_epochs = 10
train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)[31m---------------------------------------------------------------------------[39m [31mKeyboardInterrupt[39m Traceback (most recent call last) [36mCell[39m[36m [39m[32mIn[72][39m[32m, line 2[39m [32m 1[39m num_epochs = [32m10[39m [32m----> [39m[32m2[39m [43mtrain_ch3[49m[43m([49m[43mnet[49m[43m,[49m[43m [49m[43mtrain_iter[49m[43m,[49m[43m [49m[43mtest_iter[49m[43m,[49m[43m [49m[43mcross_entropy[49m[43m,[49m[43m [49m[43mnum_epochs[49m[43m,[49m[43m [49m[43mupdater[49m[43m)[49m [36mCell[39m[36m [39m[32mIn[70][39m[32m, line 6[39m, in [36mtrain_ch3[39m[34m(net, train_iter, test_iter, loss, num_epochs, updater)[39m [32m 3[39m animator = Animator(xlabel=[33m'[39m[33mepoch[39m[33m'[39m, xlim=[[32m1[39m, num_epochs], ylim=[[32m0.3[39m, [32m0.9[39m], [32m 4[39m legend=[[33m'[39m[33mtrain loss[39m[33m'[39m, [33m'[39m[33mtrain acc[39m[33m'[39m, [33m'[39m[33mtest acc[39m[33m'[39m]) [32m 5[39m [38;5;28;01mfor[39;00m epoch [38;5;129;01min[39;00m [38;5;28mrange[39m(num_epochs): [32m----> [39m[32m6[39m train_metrics = [43mtrain_epoch_ch3[49m[43m([49m[43mnet[49m[43m,[49m[43m [49m[43mtrain_iter[49m[43m,[49m[43m [49m[43mloss[49m[43m,[49m[43m [49m[43mupdater[49m[43m)[49m [32m 7[39m test_acc = evaluate_accuracy(net, test_iter) [32m 8[39m animator.add(epoch + [32m1[39m, train_metrics + (test_acc,)) [36mCell[39m[36m [39m[32mIn[68][39m[32m, line 10[39m, in [36mtrain_epoch_ch3[39m[34m(net, train_iter, loss, updater)[39m [32m 7[39m metric = Accumulator([32m3[39m) [32m 8[39m [38;5;28;01mfor[39;00m X, y [38;5;129;01min[39;00m train_iter: [32m 9[39m [38;5;66;03m# 计算梯度并更新参数[39;00m [32m---> [39m[32m10[39m y_hat = [43mnet[49m[43m([49m[43mX[49m[43m)[49m [32m 11[39m l = loss(y_hat, y) [32m 12[39m [38;5;28;01mif[39;00m [38;5;28misinstance[39m(updater, torch.optim.Optimizer): [32m 13[39m [38;5;66;03m# 使用PyTorch内置的优化器和损失函数[39;00m [36mCell[39m[36m [39m[32mIn[61][39m[32m, line 2[39m, in [36mnet[39m[34m(X)[39m [32m 1[39m [38;5;28;01mdef[39;00m[38;5;250m [39m[34mnet[39m(X): [32m----> [39m[32m2[39m [38;5;28;01mreturn[39;00m softmax([43mtorch[49m[43m.[49m[43mmatmul[49m[43m([49m[43mX[49m[43m.[49m[43mreshape[49m[43m([49m[43m([49m[43m-[49m[32;43m1[39;49m[43m,[49m[43m [49m[43mW[49m[43m.[49m[43mshape[49m[43m[[49m[32;43m0[39;49m[43m][49m[43m)[49m[43m)[49m[43m,[49m[43m [49m[43mW[49m[43m)[49m + b) [31mKeyboardInterrupt[39m:
In [73]:
def predict_ch3(net, test_iter, n=6): #@save
"""预测标签(定义见第3章)"""
for (X, y),i in zip(test_iter,range(1)):
trues = get_fashion_mnist_labels(y)
preds = get_fashion_mnist_labels(net(X).argmax(axis=1))
titles = [true +'\n' + pred for true, pred in zip(trues, preds)]
show_images(
X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n])
predict_ch3(net, test_iter)
In [74]:
batch_size = 256
train_iter, test_iter = load_data_fashion_mnist(batch_size)In [ ]:
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net.apply(init_weights);
loss = nn.CrossEntropyLoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(), lr=0.1)
num_epochs = 10
train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)In [ ]: