1 线性回归
1.1 损失函数
1.2 优化函数
本文使用小批量梯度下降算法作为先线性回归的优化函数。
1.3 梯度下降算法介绍
1.3.1 批量梯度下降
批量梯度下降对所有样本进行梯度下降,求平均后对参数进行一次优化。优点:参数优化过程较为平稳,缺点:耗时。
1.3.2 随机梯度下降
随机梯度下降对单个样本点求梯度,单个样本点对参数进行一次更新。
1.3.3 小批量梯度下降
小批量梯度下降算法将样本分成小批量,对每个小批量的样本求梯度平均值,对参数进行一次更新。小批量梯度下降算法结合了批量梯度下降和随机梯度下降的优点。
1.3.4 梯度更新基本搜索步骤
1.4 使用pytorch从零实现线性回归
导入各种包
# import packages and modules
%matplotlib inline
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random
print(torch.__version__)
生成数据集
# 生成数据集,假设是二维线性模型
# set input feature number,2个特征
num_inputs = 2
# set example number,1000个样本点
num_examples = 1000
# set true weight and bias in order to generate corresponded label
true_w = [2, -3.4]
true_b = 4.2
# torch.randn(n1, n2)生成n1*n2大小的标准正态分布随机数
features = torch.randn(num_examples, num_inputs, dtype=torch.float32)
print(features.shape)
# 严格线性的标签
labels = true_w[0]