模型选择拟合

1.通过多项式拟合交互探索概念

复制代码
import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l

2.使用三阶多项式来生成训练和测试数据的标签

复制代码
max_degree = 20  # 多项式的最大阶数
n_train, n_test = 100, 100  # 训练和测试数据集大小
true_w = np.zeros(max_degree)  # 分配大量的空间
true_w[0:4] = np.array([5, 1.2, -3.4, 5.6])

features = np.random.normal(size=(n_train + n_test, 1))
np.random.shuffle(features)
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))
for i in range(max_degree):
    poly_features[:, i] /= math.gamma(i + 1)  # gamma(n)=(n-1)!
# labels的维度:(n_train+n_test,)
labels = np.dot(poly_features, true_w)
labels += np.random.normal(scale=0.1, size=labels.shape)

3.查看样本

复制代码
true_w, features, poly_features, labels = [torch.tensor(x, dtype=
    torch.float32) for x in [true_w, features, poly_features, labels]]

features[:2], poly_features[:2, :], labels[:2]

4.实现函数来评估模型在给定数据集的损失

复制代码
def evaluate_loss(net, data_iter, loss):
    """评估给定数据集上模型的损失"""
    metric = d2l.Accumulator(2)
    for X, y in data_iter:
        out = net(X)
        y = y.reshape(out.shape)
        l = loss(out, y)
        metric.add(l.sum(), l.numel())
    return metric[0] / metric[1]

5.定义训练函数

复制代码
def train(train_features, test_features, train_labels, test_labels,
          num_epochs=400):
    loss = nn.MSELoss()
    input_shape = train_features.shape[-1]
    net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
    batch_size = min(10, train_labels.shape[0])
    train_iter = d2l.load_array((train_features, train_labels.reshape(-1,1)),
                                batch_size)
    test_iter = d2l.load_array((test_features, test_labels.reshape(-1,1)),
                               batch_size, is_train=False)
    trainer = torch.optim.SGD(net.parameters(), lr=0.01)
    animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log',
                            xlim=[1, num_epochs], ylim=[1e-3, 1e2],
                            legend=['train', 'test'])
    for epoch in range(num_epochs):
        d2l.train_epoch_ch3(net, train_iter, loss, trainer)
        if epoch == 0 or (epoch + 1) % 20 == 0:
            animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss),
                                     evaluate_loss(net, test_iter, loss)))
    print('weight:', net[0].weight.data.numpy())
相关推荐
不辉放弃2 分钟前
零基础讲解pandas
开发语言·python
databook12 分钟前
线性判别分析(LDA):降维与分类的完美结合
python·机器学习·scikit-learn
慕丹13 分钟前
虫洞数观系列三 | 数据分析全链路实践:Pandas清洗统计 + Navicat可视化呈现
python·mysql·数据挖掘·数据分析·pandas
ZHW_AI课题组26 分钟前
调用阿里云API实现运营商实名认证
python·阿里云·云计算·api
闲人编程28 分钟前
图像插值算法(最近邻/双线性/立方卷积)
python·opencv·图像识别
Caramel_biscuit34 分钟前
STM32 CAN学习
stm32·嵌入式硬件·学习
创新技术阁1 小时前
FastAPI 的两大核心组件:Starlette 和 Pydantic 详解
后端·python
关山月1 小时前
被低估的服务器发送事件(SSE)
python
DeepLink1 小时前
Python小练习系列:学生信息排序(sorted + key函数)
python·求职
项目申报小狂人1 小时前
CUDA详细安装及环境配置——环境配置指南 – CUDA+cuDNN+PyTorch 安装
人工智能·pytorch·python