一、线性回归
知识点记录
线性回归输出是一个连续值,因此适用于回归问题。如预测房屋价格、气温、销售额等连续值的问题。是单层神经网络。
线性判别模型
判别模型
性质:建模预测变量和观测变量之间的关系,亦称作条件模型
分类:确定性判别模型:y=fθ(x)
概率判别模型:pθ(y|x)
线性判别模型(linear regression)
y=fθ(x)= θo +【(d,i=1),加和】θjxj = θTx ,x= (x1,x2,x3,...,xd)
学习目标:
使预测值和真实值的距离越近越好, min 1((【N,i=1】)加和)&(yi,fθ(xi)))/N
损失函数:&(yi,fθ(xi))测量预测值与真实值之间的误差,越小越好(方差最小),
具体损失函数的定义依赖于具体数据和任务
最广泛使用的损失的回归函数:平方误差(squared loss),&(yi,fθ(xi)) = 1(yi-fθ(xi))*(yi-fθ(xi))/2
最小均方误差回归
优化目标是最小化训练数据上的均方误差 jθ = 1(【N,i=1】加和)(yi -fθ(xi))*(yi -fθ(xi))/2N min jθ
模型:
假设价格只取决于房屋状况的面积和房龄因素,加下来探索价格与此俩因素具体关系。线性回归假设输出与各个输入之间是线性关系: price = warea · area + wage · age + b
数据集:
收集一些真实数据(多栋房屋真实售价和它们对应的面积和房龄。我们在此数据上寻找模型参数是模型的预测价格与真实价格的误差最小,称为:训练数据集或者训练集,一栋房屋称为一个样本,真实售价叫做标签,用于预测的因素叫特征,特征用来表征样本的特点。
优化函数-随机梯度下降:
当模型和损失函数形式较为简单时,上面的误差最小化问题的解可以直接用公式表达出来。这类解叫作解析解,大多数深度学习模型并没有解析解,只能通过优化算法有限次迭代模型参数来尽可能降低损失函数的值。这类解叫作数值解。
总结一下,优化函数的有以下两个步骤:
- (i)初始化模型参数,一般来说使用随机初始化;
- (ii)我们在数据上迭代多次,通过在负梯度方向移动参数来更新每个参数
模型实例:线性回归从零实现
1 # import packages and modules 2 %matplotlib inline 3 import torch 4 from IPython import display 5 from matplotlib import pyplot as plt 6 import numpy as np 7 import random 8 9 print(torch.__version__)
生成数据集:
使用线性模型来生成数据集,生成一个1000样本的数据集,下面是用力来生成数据的线性关系:
price = warea · area + wage · age +b
1 # set input feature number 2 num_inputs = 2 3 # set example number 4 num_examples = 1000 5 6 # set true weight and bias in order to generate corresponded label 7 true_w = [2, -3.4] 8 true_b = 4.2 9 10 features = torch.randn(num_examples, num_inputs, 11 dtype=torch.float32) 12 labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b 13 labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), 14 dtype=torch.float32)
使用图像来展示生成的数据:
1 plt.scatter(features[:,1].numpy(), labels.numpy(), 1);
读取数据集:
1 def data_iter(batch_size, features, labels): 2 num_examples = len(features) 3 indices = list(range(num_examples)) 4 random.shuffle(indices) # random read 10 samples 5 for i in range(0, num_examples, batch_size): 6 j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch 7 yield features.index_select(0, j), labels.index_select(0, j)
1 batch_size = 10 2 3 for X, y in data_iter(batch_size, features, labels): 4 print(X, '\n', y) 5 break
初始化模型参数:
1 w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32) 2 b = torch.zeros(1, dtype=torch.float32) 3 4 w.requires_grad_(requires_grad=True) 5 b.requires_grad_(requires_grad=True)
定义模型:
定义用来训练参数的训练模型: price = warea · area + wage · age +b
1 def linreg(X, w, b): 2 return torch.mm(X, w) + b
定义损失函数:
使用均方误差损失函数: l(i)(w,b) = 1(ˆy帽(i)-y(i))2
1 def squared_loss(y_hat, y): 2 return (y_hat - y.view(y_hat.size())) ** 2 / 2
定义优化函数:
使用小批量随机梯度下降: (w,b)← (w,b) - 【η·∑i∂(w,b)l(i)(w,b)】/|β|
1 def sgd(params, lr, batch_size): 2 for param in params: 3 param.data -= lr * param.grad / batch_size # ues .data to operate param without gradient track
训练:
当数据集、模型、损失函数和优化函数定义之后即可以准备进行模型训练
1 # super parameters init 2 lr = 0.03 3 num_epochs = 5 4 5 net = linreg 6 loss = squared_loss 7 8 # training 9 for epoch in range(num_epochs): # training repeats num_epochs times 10 # in each epoch, all the samples in dataset will be used once 11 12 # X is the feature and y is the label of a batch sample 13 for X, y in data_iter(batch_size, features, labels): 14 l = loss(net(X, w, b), y).sum() 15 # calculate the gradient of batch sample loss 16 l.backward() 17 # using small batch random gradient descent to iter model parameters 18 sgd([w, b], lr, batch_size) 19 # reset parameter gradient 20 w.grad.data.zero_() 21 b.grad.data.zero_() 22 train_l = loss(net(features, w, b), labels) 23 print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))
1 w, true_w, b, true_b
二、softmax
与回归问题不同,分类问题中模型的最终输出是一个离散值,我们所说的图像分类,垃圾邮件识别,疾病监测等输出为离散值的问题都属于分类问题的范畴。softmax回归则适用于分类问题。也是单层神经网络。