02线性回归

08_P3  pycharm代码

import random  # 需要随机化梯度下降和随机初始化参数
import torch


# 定义模型 预测y 即y_hat
def linreg(X, w, b):
    """线性回归模型"""
    return torch.matmul(X, w) + b


# 定义合成数据的函数
def synthetic_data(w, b, num_examples):
    """生成y=Xw+b+噪声"""
    X = torch.normal(0, 1, (num_examples, len(w)))  # 生成均值为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))  # 列数为1,行数需要计算


# 小批量数据读取
def data_iter(batch_size, features, labels):
    num_examples = len(features)  # num_examples为X中的行数 即多少组数据
    indices = list(range(num_examples))  # 生成索引列表[1,2,3,....,500]
    random.shuffle(indices)  # 随机读取索引 [23,42,103,....,487]
    for i in range(0, num_examples, batch_size):  # 步长为batch_size
        batch_indices = torch.tensor(  # 生成数据块,从列表的第i个元素到i+batch_size的元素即每次取10个
            indices[i: min(i + batch_size, num_examples)])  # 例 第一次取到[23,42,103,....,368]
        yield features[batch_indices], labels[batch_indices]  # 不断返回features和batch_indices中第23,42,103,....,368行数据


# 定义损失函数
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  # 除不除batch_size变化不大
            param.grad.zero_()  # 避免梯度累计

if __name__ == '__main__':
    # 初始化模型参数
    w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)  # 生成均值为0方差为0.01的随机向量,2行1列
    b = torch.zeros(1, requires_grad=True)
    # 给出真实值true_w true_b
    true_w = torch.tensor([2, -3.4])
    true_b = 4.2
    # 构建数据集X作为features,并通过真实值true_w true_b算出y的真实值作为labels
    features, labels = synthetic_data(true_w, true_b, 1000)  # 生成特征和标注。features, labels分别接收函数的返回值X、y
    # 训练的超参数
    batch_size = 10
    lr = 0.03  # 学习率0.03
    num_epochs = 3  # 数据集扫三遍
    net = linreg  # 训练模型
    loss = squared_loss  # 均方损失

    for epoch in range(num_epochs):  # 扫三遍
        for X, y in data_iter(batch_size, features, labels):  # 拿出批量大小的赋给X,y。 每次拿10行,拿50次。
            # X和y的小批量损失
            l = loss(net(X, w, b), y)  # 把X, w, b放入linreg中做预测,并与真实的y做均方损失
            # 因为l形状是(batch_size,1),而不是一个标量。l中的所有元素被加到一起,
            # 并以此计算关于[w,b]的梯度
            l.sum().backward()  # 求和并算梯度
            sgd([w, b], lr, batch_size)  # 使用参数的梯度更新参数   对w,b进行更新
        with torch.no_grad():  # 做预测,不需要梯度
            train_l = loss(net(features, w, b), labels)  # 放入整个数据
            print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')  # .mean()求均值

    print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
    print(f'b的估计误差: {true_b - b}')

笔记

02线性回归_第1张图片

 02线性回归_第2张图片

 08_P4  pycharm代码

import torch
from torch.utils import data
from d2l import torch as d2l
from torch import nn


def load_array(data_arrays, batch_size, is_train=True):
    """用(features, labels)构造一个PyTorch数据迭代器"""
    dataset = data.TensorDataset(*data_arrays)  # 生成数据集dataset
    return data.DataLoader(dataset, batch_size, shuffle=is_train)  # 随机返回dataset的batch_size行数据

if __name__ == '__main__':
    true_w = torch.tensor([2, -3.4])
    true_b = 4.2
    features, labels = d2l.synthetic_data(true_w, true_b, 1000)

    batch_size = 10
    data_iter = load_array((features, labels), batch_size)     # 构造并得到小批量数据,是一个矩阵
    next(iter(data_iter))  # 将data_iter转成python的iter,通过next不断获取并返回iter的下一条数据,即矩阵的下一行
    # Sequential顺序容器,模块将按照在构造函数中传递的顺序添加到模块中。
    net = nn.Sequential(nn.Linear(2, 1))  # 导入线性回归模型,输入的维度为2(X的列数为2),输出y_hat维度为1
    net[0].weight.data.normal_(0, 0.01)  # 模型中第一层(net[0])用随机正态分布改写权重参数。可以不设,使用默认。
    net[0].bias.data.fill_(0)  # 偏差设为0
    loss = nn.MSELoss()  # 使用均方误差,也称为平方 L2 范数,默认情况下,它返回所有样本损失的平均值
    trainer = torch.optim.SGD(net.parameters(), lr=0.03)  # 传入所有待优化的参数(w,b)

    # 训练
    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}')

    w = net[0].weight.data
    print('w的估计误差:', true_w - w.reshape(true_w.shape))
    b = net[0].bias.data
    print('b的估计误差:', true_b - b)

09_P4  pycharm代码

import torch
from IPython import display
from d2l import torch as d2l

# 动画绘制
class 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):
        # 向图表中添加多个数据点
        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)

# 定义softmax操作
def softmax(X):
    X_exp = torch.exp(X)
    partition = X_exp.sum(1, keepdim=True)  # 按轴求和,keepdim=True保持原矩阵维度不变
    return X_exp / partition  # 这里应用了广播机制

# 定义模型
def net(X):
    return softmax(torch.matmul(X.reshape((-1, W.shape[0])), W) + b)  # -1自动算行数(256),W.shape[0]返回w的行数
'''
# 定义损失函数(交叉熵损失)
y = torch.tensor([0, 2])
y_hat = torch.tensor([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]])
#  z = y_hat[[0, 1], y]  # 从y_hat[0]中取出第y[0]个元素,y_hat[0][0].从y_hat[1]中取出第y[1]个元素,y_hat[1][2]
'''
def cross_entropy(y_hat, y):
    return - torch.log(y_hat[range(len(y_hat)), y])

# 将预测类别y_hat与真实的y元素进行比较
def accuracy(y_hat, y):
    """计算预测正确的数量"""
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:  # len(y_hat.shape)行数大于1,y_hat.shape[1]列数大于1.
        y_hat = y_hat.argmax(axis=1)    # 将y_hat每一行最大的值的索引取出放入y_hat
    cmp = y_hat.type(y.dtype) == y      # cmp为每个元素都为布尔值的张量
    return float(cmp.type(y.dtype).sum())  # 将cmp中数据类型转换成y中的数据类型,false=0.true=1.返回预测正确的个数


class Accumulator:
    """在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]
def evaluate_accuracy(net, data_iter):
    """计算在指定数据集上模型的精度"""
    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]

def updater(batch_size):
    return d2l.sgd([W, b], lr, batch_size)

# 训练  迭代一次的流程  .nn还是还是自定义
def train_epoch_ch3(net, train_iter, loss, updater):
    """训练模型一个迭代周期(定义见第3章)"""
    # 将模型设置为训练模式
    if isinstance(net, torch.nn.Module):
        net.train()
    # 长度为3的迭代器累加信息。   训练损失总和、训练准确度总和、样本数
    metric = Accumulator(3)
    for X, y in train_iter:    # 循环235次
        # 计算梯度并更新参数
        # print(X.shape) [256,1,28,28]
        # print(y.shape) [256]
        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())
    # 返回训练损失(所有loss的累加/样本总数)和训练精度(所有分类正确样本数/样本总数)
    return metric[0] / metric[2], metric[1] / metric[2]

#  训练
def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater):
    """训练模型(定义见第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):                                       # 扫10遍
        train_metrics = train_epoch_ch3(net, train_iter, loss, updater)   # train_metrics训练误差
        test_acc = evaluate_accuracy(net, test_iter)                      # test_acc在测试数据集上的精度
        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

# 预测
def predict_ch3(net, test_iter, n=12):
    """预测标签(定义见第3章)"""
    for X, y in test_iter:
        break
    trues = d2l.get_fashion_mnist_labels(y)
    preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1))
    titles = [true+pred for true, pred in zip(trues, preds)]
    d2l.show_images(
        X[0:n].reshape((n, 28, 28)), 1, n, titles=titles[0:n])
    d2l.plt.show()


if __name__ == '__main__':
    # 初始化参数模型
    batch_size = 256
    num_inputs = 784  # 把28*28的图片拉成一个784的向量
    num_outputs = 10  # 因为有10种类型,故输出为10
    # 权重将构成一个 784×10 的矩阵W, 偏置将构成一个 1×10 的行向量b
    W = torch.normal(0, 0.01, size=(num_inputs, num_outputs), requires_grad=True)
    b = torch.zeros(num_outputs, requires_grad=True)
    lr = 0.1
    num_epochs = 10
    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)  # 加载所有数据,每256个为一组
    # print(len(train_iter))  235
    train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
    d2l.plt.show()
    # 预测
    predict_ch3(net, test_iter)

 09_P5  pycharm代码

import torch
from torch import nn
from d2l import torch as d2l


# 初始化模型参数
def init_weights(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01)  # 将权重初始化为均值为0,方差0.01的随机值

if __name__ == '__main__':
    batch_size = 256
    num_epochs = 10
    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
    # PyTorch不会隐式地调整输入的形状。因此,我们在线性层前定义了展平层(flatten),来调整网络输入的形状
    # 把任何维度的tensor转成向量(二维)  线性层Linear输入784输出10   Sequential类构造器
    net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))
    net.apply(init_weights)  # 每一层都跑一下此函数
    # 交叉熵损失函数
    loss = nn.CrossEntropyLoss(reduction='none')
    # 优化算法
    trainer = torch.optim.SGD(net.parameters(), lr=0.1)
    # 训练
    d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
    d2l.plt.show()

你可能感兴趣的:(李沐_动手学pytorch,学习笔记,线性回归,深度学习,pytorch)