赞
踩
本文章为个人学习使用,版面观感若有不适请谅解,文中知识仅代表个人观点,若出现错误,欢迎各位批评指正。
使用以下公式为例做演示:
y = 0.05 + ∑ i = 1 d 0.01 x i + ε w h e r e ε ~ N ( 0 , 0.0 1 2 ) y = 0.05 + \sum_{i=1}^{d} 0.01x_i + \varepsilon \quad where \quad \varepsilon \; ~ \; N ( 0 , 0.01^2 ) y=0.05+i=1∑d0.01xi+εwhereε~N(0,0.012)
import torch from torch import nn from d2l import torch as d2l from IPython import display def synthetic_data(w, b, num_examples): """生成 y = Xw + b + 噪声。""" X = torch.normal(0, 1, (num_examples, len(w))).cuda() # 均值为 0,方差为 1,有 num_examples 个样本,列数为 w 长度 y = torch.matmul(X, w).cuda() + b # y = Xw + b y += torch.normal(0, 0.01, y.shape).cuda() # 随机噪音 return X, y.reshape((-1, 1)) # x,y作为列向量返回 class Animator: # 定义一个在动画中绘制数据的实用程序类 Animator """在动画中绘制数据""" 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 = [] d2l.use_svg_display() self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize) if nrows * ncols == 1: self.axes = [self.axes, ] # 使用lambda函数捕获参数 self.config_axes = lambda: d2l.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): # Add multiple data points into the figure 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) # 通过以下两行代码实现了在PyCharm中显示动图 d2l.plt.draw() d2l.plt.pause(interval=0.001) display.clear_output(wait=True) d2l.plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5 true_w, true_b = torch.ones((num_inputs, 1)).cuda() * 0.01, 0.05 train_data = synthetic_data(true_w, true_b, n_train) train_iter = d2l.load_array(train_data, batch_size) test_data = synthetic_data(true_w, true_b, n_test) test_iter = d2l.load_array(test_data, batch_size, is_train=False) ############## 权重衰减的实现 ############# def init_params(): """ 初始化参数 """ w = torch.normal(0, 1, size=(num_inputs, 1)).cuda() b = torch.zeros(1).cuda() w.requires_grad_(True) b.requires_grad_(True) return [w, b] def l2_penalty(w): """ 定义 L2 范数惩罚 """ return (torch.sum(w.pow(2)) / 2).cuda() def train(lambd): flag_button = "使用" w, b = init_params() net, loss = lambda X: d2l.linreg(X, w, b), d2l.squared_loss num_epochs, lr = 150, 0.005 animator = Animator(xlabel='epochs', ylabel='loss', yscale='log', xlim=[5, num_epochs], legend=['train', 'test']) for epoch in range(num_epochs): for X, y in train_iter: # 增加了 L2 范数惩罚项,、 # 广播机制使 l2_penalty(w) 成为一个长度为 batch_size 的向量 l = loss(net(X), y) + lambd * l2_penalty(w) l.sum().backward() d2l.sgd([w, b], lr, batch_size) if (epoch + 1) % 5 == 0: animator.add(epoch + 1, (d2l.evaluate_loss(net, train_iter, loss), d2l.evaluate_loss(net, test_iter, loss))) # print('w的L2范数是:', torch.norm(w).item()) if lambd == 0:flag_button = "禁用" d2l.plt.title(f"{flag_button}权重衰减 (lambda = {lambd})\nw 的 L2 范数是:{torch.norm(w).item()}") d2l.plt.show() train(lambd=0) train(lambd=15)
import torch from torch import nn from d2l import torch as d2l from IPython import display def synthetic_data(w, b, num_examples): """生成 y = Xw + b + 噪声。""" X = torch.normal(0, 1, (num_examples, len(w))).cuda() # 均值为 0,方差为 1,有 num_examples 个样本,列数为 w 长度 y = torch.matmul(X, w).cuda() + b # y = Xw + b y += torch.normal(0, 0.01, y.shape).cuda() # 随机噪音 return X, y.reshape((-1, 1)) # x,y作为列向量返回 class Animator: # 定义一个在动画中绘制数据的实用程序类 Animator """在动画中绘制数据""" 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 = [] d2l.use_svg_display() self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize) if nrows * ncols == 1: self.axes = [self.axes, ] # 使用lambda函数捕获参数 self.config_axes = lambda: d2l.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): # Add multiple data points into the figure 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) # 通过以下两行代码实现了在PyCharm中显示动图 d2l.plt.draw() d2l.plt.pause(interval=0.001) display.clear_output(wait=True) d2l.plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] n_train, n_test, num_inputs, batch_size = 20, 100, 200, 5 true_w, true_b = torch.ones((num_inputs, 1)).cuda() * 0.01, 0.05 train_data = synthetic_data(true_w, true_b, n_train) train_iter = d2l.load_array(train_data, batch_size) test_data = synthetic_data(true_w, true_b, n_test) test_iter = d2l.load_array(test_data, batch_size, is_train=False) ############## 权重衰减的简洁实现 ############# def train_concise(wd): flag_button = "使用" net = nn.Sequential(nn.Linear(num_inputs, 1)).cuda() for param in net.parameters(): param.data.normal_().cuda() loss = nn.MSELoss(reduction='none').cuda() num_epochs, lr = 150, 0.005 # 偏置参数没有衰减 trainer = torch.optim.SGD([ {"params":net[0].weight,'weight_decay': wd}, {"params":net[0].bias}], lr=lr) animator = Animator(xlabel='epochs', ylabel='loss', yscale='log', xlim=[5, num_epochs], legend=['train', 'test']) for epoch in range(num_epochs): for X, y in train_iter: trainer.zero_grad() l = loss(net(X), y) l.mean().backward() trainer.step() if (epoch + 1) % 5 == 0: animator.add(epoch + 1, (d2l.evaluate_loss(net, train_iter, loss), d2l.evaluate_loss(net, test_iter, loss))) # print('w的L2范数:', net[0].weight.norm().item()) if wd == 0:flag_button = "禁用" d2l.plt.title(f"{flag_button}权重衰减 (lambda = {wd})\nw 的 L2 范数是:{net[0].weight.norm().item()}") d2l.plt.show() train_concise(0) train_concise(-2)
文中部分知识参考:B 站 —— 跟李沐学AI;百度百科
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。