Files
nn/chapter1-6.ipynb
T
2026-04-01 23:34:53 +08:00

634 KiB

In [1]:
import torch
import numpy
import pandas
In [2]:
torch.randn(3,4,2)
Out [2]:
tensor([[[-1.0244, -0.4164],
         [ 1.5765, -0.9106],
         [-1.6388, -0.7727],
         [-1.8594, -1.6634]],

        [[-0.3226,  0.6604],
         [ 0.4341, -0.9600],
         [ 0.2575,  2.0599],
         [ 0.6960,  0.7095]],

        [[-0.0242, -0.5866],
         [-0.8018, -0.3080],
         [-1.3225, -0.0591],
         [ 0.0322,  0.8251]]])
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+b
Out [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]])
B
Out [11]:
tensor([[1, 2, 3],
        [2, 0, 4],
        [3, 4, 5]])
In [12]:
B==B.T
Out [12]:
tensor([[True, True, True],
        [True, True, True],
        [True, True, True]])
In [13]:
X=torch.arange(24).reshape(2,3,4)
X
Out [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]:
(140069082123952, 140069083998928)

Hadamard乘积

In [15]:
A*B
Out [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).shape
Out [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_axis1
Out [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.000109秒
In [20]:
torch.norm(torch.ones((4, 9)))
Out [20]:
tensor(6.)
In [21]:
x =torch.arange(4.0,requires_grad=True)
x.grad
In [22]:
y=2*torch.dot(x,x)
y
Out [22]:
tensor(28., grad_fn=<MulBackward0>)
In [23]:
y.backward()
x.grad
Out [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.grad
Out [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==u
Out [27]:
tensor([True, True, True, True])
In [28]:
x.grad.zero_()
y.sum().backward()
x.grad==2*x
Out [28]:
tensor([True, True, True, True])
In [29]:
from torch.distributions import multinomial
fair_probs=torch.ones([6])
fair_probs
Out [29]:
tensor([1., 1., 1., 1., 1., 1.])
In [30]:
multinomial.Multinomial(1, fair_probs).sample()
Out [30]:
tensor([0., 0., 0., 1., 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.11861 sec'
In [35]:
timer.start()
d=a+b
f'{timer.stop():.5f} sec'
Out [35]:
'0.00074 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 0x7f645fd37d50>
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_loss
In [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)
    break
tensor([[ 0.0169, -0.3729],
        [ 0.2105, -1.0088],
        [-1.3548,  0.9556],
        [-0.0298,  0.4827],
        [ 1.5137, -2.4433],
        [ 0.0029,  0.6444],
        [ 0.5705,  1.1589],
        [ 0.3421, -0.5686],
        [-0.8094, -0.8650],
        [ 0.3897, -1.3542]]) 
 tensor([[ 5.5058],
        [ 8.0436],
        [-1.7624],
        [ 2.4937],
        [15.5411],
        [ 2.0171],
        [ 1.3941],
        [ 6.8340],
        [ 5.5124],
        [ 9.5840]])
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.040479
epoch 2, train loss: 0.000158
epoch 3, train loss: 0.000052
epoch 4, train loss: 0.000052
epoch 5, train loss: 0.000052
epoch 6, train loss: 0.000052
epoch 7, train loss: 0.000052
epoch 8, train loss: 0.000052
epoch 9, train loss: 0.000052
epoch 10, train loss: 0.000052
epoch 11, train loss: 0.000052
epoch 12, train loss: 0.000052
epoch 13, train loss: 0.000052
epoch 14, train loss: 0.000052
epoch 15, train loss: 0.000052
epoch 16, train loss: 0.000052
epoch 17, train loss: 0.000052
epoch 18, train loss: 0.000052
epoch 19, train loss: 0.000052
epoch 20, train loss: 0.000052
In [46]:
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
w的估计误差: tensor([ 0.0010, -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.546318
epoch 2, loss 0.009022
epoch 3, loss 0.000254
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].shape
Out [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 axes
In [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]:
'1.59 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)
    break
torch.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.1969, 0.2421, 0.2949, 0.1017, 0.1645],
         [0.2729, 0.1267, 0.0365, 0.2715, 0.2924]]),
 tensor([1., 1.]))
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.1045
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_acc
In [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)
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 [76]:
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 [77]:
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = torch.relu(x)
plot(x.detach(), y.detach(), 'x', 'relu(x)', figsize=(5, 2.5))
In [78]:
y.backward(torch.ones_like(x), retain_graph=True)
plot(x.detach(), x.grad, 'x', 'grad of relu', figsize=(5, 2.5))
In [79]:
y = torch.sigmoid(x)
plot(x.detach(), y.detach(), 'x', 'sigmoid(x)', figsize=(5, 2.5))
In [80]:
x.grad.data.zero_()
y.backward(torch.ones_like(x),retain_graph=True)
plot(x.detach(), x.grad, 'x', 'grad of sigmoid', figsize=(5, 2.5))
In [81]:
batch_size = 256
train_iter, test_iter = load_data_fashion_mnist(batch_size)
In [82]:
num_inputs,num_outputs,num_hiddens = 784, 10, 256
W1=nn.Parameter(torch.randn(num_inputs,num_hiddens,requires_grad=True)*0.01)
b1=nn.Parameter(torch.zeros(num_hiddens,requires_grad=True))
W2 = nn.Parameter(torch.randn(num_hiddens,num_outputs,requires_grad=True)*0.01)
b2=nn.Parameter(torch.zeros(num_outputs,requires_grad=True))
params=[W1,b1,W2,b2]
In [83]:
def relu(X):
    a = torch.zeros_like(X)
    return torch.max(X,a)
def net(X):
    X = X.reshape((-1,num_inputs))
    H = relu(X@W1+b1)
    return (H@W2+b2)
loss = nn.CrossEntropyLoss(reduction='none')
num_epochs,lr=10,0.05
updater=torch.optim.SGD(params,lr=lr)
#train_ch3(net,train_iter,test_iter,loss,num_epochs,updater)
In [84]:
predict_ch3(net, test_iter)
In [85]:
net = nn.Sequential(nn.Flatten(),
                    nn.Linear(784,256),
                    nn.ReLU(),
                    nn.Linear(256,10))
def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight,std=0.01)

net.apply(init_weights)
Out [85]:
Sequential(
  (0): Flatten(start_dim=1, end_dim=-1)
  (1): Linear(in_features=784, out_features=256, bias=True)
  (2): ReLU()
  (3): Linear(in_features=256, out_features=10, bias=True)
)
In [86]:
batch_size,lr, num_epochs=256,0.1,10
loss = nn.CrossEntropyLoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(),lr=lr)
train_iter, test_iter = load_data_fashion_mnist(batch_size)
#train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
In [ ]: