第3章 线性分类
3.1 基于Logistic回归的二分类任务
实现一个Logistic回归模型,并对一个简单的数据集进行二分类实验。
3.1.1 数据集构建
构建一个简单的分类任务,并构建训练集、验证集和测试集。
本任务的数据来自带噪音的两个弯月形状函数,每个弯月对一个类别。我们采集1000条样本,每个样本包含2个特征。
随机采集1000个样本,并进行可视化。
将1000条样本数据拆分成训练集、验证集和测试集,其中训练集640条、验证集160条、测试集200条。
import math
import copy
import torch
def make_moons(n_samples=1000,shuffle=True,noise=None):
'''
生成带噪音的弯月形状数据
:param n_samples: 数据量大小,数据类型为int
:param shuffle: 是否打乱数据,数据类型为bool
:param noise: 以多大程度增加噪声,数据类型为None或float
:return: X:特征数据,shape=[n_samples,2]
y:标签数据,shape=[n_samples]
'''
n_samples_out=n_samples//2
n_samples_in=n_samples-n_samples_out
#采集第1类数据,特征为(x,y)
#使用‘torch.linspace'在0到pi上均匀取n_samples_out个值
#使用'torch.cos'计算上述取值的余弦值作为特征1,使用'torch.sin'计算上述取值的正弦值作为特征2
outer_circ_x= torch.cos(torch.linspace(0,math.pi,n_samples_out))
outer_circ_y=torch.sin(torch.linspace(0,math.pi,n_samples_out))
inner_circ_x=1-torch.cos(torch.linspace(0,math.pi,n_samples_in))
inner_circ_y=0.5-torch.sin(torch.linspace(0,math.pi,n_samples_in))
print('outer_circ_x.shape:',outer_circ_x.shape,'outer_circ_y.shape:',outer_circ_y.shape)
print('inner_circ_x.shape:',inner_circ_x.shape,'inner_circ_y.shape:',inner_circ_y.shape)
#使用'torch.concat'将两类数据的特征1和特征2分别延维度0拼接在一起,得到全部特征1和特征2
#使用'torch.stack'将两类特征延维度1堆叠在一起
X=torch.stack(
[torch.cat([outer_circ_x,inner_circ_x]),
torch.cat([outer_circ_y,inner_circ_y])],
dim=1
)
print('after concat shape:',torch.cat([outer_circ_x,
inner_circ_x]).shape)
print('X shape:',X.shape)
#使用'torch.zeros'将第一类数据的标签设为0
#使用'torch.ones'将第一类数据的标签设为1
y=torch.cat(
[torch.zeros(size=[n_samples_out]),torch.ones(size=[n_samples_in])]
)
print('y shape:',y.shape)
# 如果shuffle为True,将所有数据打乱
if shuffle:
# 使用'torch.randperm'生成一个数值在0到X.shape[0],随机排列的一维Tensor做索引值,用于打乱数据
idx = torch.randperm(X.shape[0])
X = X[idx]
y = y[idx]
# 如果noise不为None,则给特征值加入噪声
if noise is not None:
# 使用'torch.normal'生成符合正态分布的随机Tensor作为噪声,并加到原始特征上
X += torch.normal(mean=0.0, std=noise, size=X.shape)
return X, y
# 采样1000个样本
n_samples = 1000
X,y=make_moons(n_samples=n_samples, shuffle=True, noise=0.5)
# 可视化生产的数据集,不同颜色代表不同类别
import matplotlib.pyplot as plt
plt.figure(figsize=(5,5))
plt.scatter(x=X[:, 0].tolist(), y=X[:, 1].tolist(), marker='*', c=y.tolist())
plt.xlim(-3,4)
plt.ylim(-3,4)
plt.savefig('linear-dataset-vis.pdf')
plt.show()
num_train=640
num_dev=160
num_test=200
X_train,y_train=X[:num_train],y[:num_train]
X_dev,y_dev=X[num_train:num_train+num_dev],y[num_train:num_train+num_dev]
X_test,y_test=X[num_train+num_dev:],y[num_train+num_dev:]
y_train=y_train.reshape([-1,1])
y_dev=y_dev.reshape([-1, 1])
y_test=y_test.reshape([-1, 1])
# 打印X_train和y_train的维度
print("X_train shape: ", X_train.shape, "y_train shape: ", y_train.shape)
# 打印一下前5个数据的标签
print (y_train[:5])
3.1.2 模型构建
Logistic回归是一种常用的处理二分类问题的线性模型。与线性回归一样,Logistic回归也会将输入特征与权重做线性叠加。不同之处在于,Logistic回归引入了非线性函数g:RD→(0,1)g:RD→(0,1),预测类别标签的后验概率 p(y=1|x)p(y=1|x) ,从而解决连续的线性函数不适合进行分类的问题。
其中判别函数σ(⋅)σ(⋅)为Logistic函数,也称为激活函数,作用是将线性函数f(x;w,b)f(x;w,b)的输出从实数区间“挤压”到(0,1)之间,用来表示概率。Logistic函数定义为:
import torch
import matplotlib.pyplot as plt
def logistic(x):
return 1/(1+torch.exp(-x))
x=torch.linspace(-10,10,1000)
plt.figure()
plt.plot(x.tolist(),logistic(x).tolist(),color="#e4007f",label="Logistic Function")
#设置坐标轴
ax=plt.gca()
#取消右侧和上侧坐标轴
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
#设置默认的x轴和y轴方向
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#设置坐标原点为(0,0)
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
#添加图例
plt.legend()
plt.savefig('linear-logistic.pdf')
plt.show()
问题1:Logistic回归在不同的书籍中,有许多其他的称呼,具体有哪些?你认为哪个称呼最好?
Logistic回归属于对数线性模型,也被称为对数几率回归。我认为对数几率回归更好,可以直截了当的看出其所用函数。
问题2:什么是激活函数?为什么要用激活函数?常见激活函数有哪些?
激活函数对于人工神经网络模型去学习、理解非常复杂和非线性的函数来说具有十分重要的作用。它们将非线性特性引入到我们的网络中。在神经元中,输入的 inputs 通过加权,求和后,还被作用了一个函数,这个函数就是激活函数。
激活函数给神经元引入了非线性因素,使得神经网络可以任意逼近任何非线性函数,这样神经网络就可以应用到众多非线性模型中。
sigmoid函数:
ReLu函数:
3.1.3 损失函数
交叉熵损失函数
import torch
def logistic(x):
return 1 / (1 + torch.exp(-x))
class model_LR():
def __init__(self, input_dim):
super(model_LR, self).__init__()
self.params = {}
# 将线性层的权重参数全部初始化为0
self.params['w'] = torch.zeros(size=[input_dim, 1])
# self.params['w'] = paddle.normal(mean=0, std=0.01, shape=[input_dim, 1])
# 将线性层的偏置参数初始化为0
self.params['b'] = torch.zeros(size=[1])
def __call__(self, inputs):
return self.forward(inputs)
def forward(self, inputs):
"""
输入:
- inputs: shape=[N,D], N是样本数量,D为特征维度
输出:
- outputs:预测标签为1的概率,shape=[N,1]
"""
# 线性计算
score = torch.matmul(inputs, self.params['w']) + self.params['b']
# Logistic 函数
outputs = logistic(score)
return outputs
# 固定随机种子,保持每次运行结果一致
torch.seed()
# 随机生成3条长度为4的数据
inputs = torch.randn(size=[3,4])
# 实例化模型
model = model_LR(4)
outputs = model(inputs)
# 实现交叉熵损失函数
class BinaryCrossEntropyLoss():
def __init__(self):
self.predicts = None
self.labels = None
self.num = None
def __call__(self, predicts, labels):
return self.forward(predicts, labels)
def forward(self, predicts, labels):
"""
输入:
- predicts:预测值,shape=[N, 1],N为样本数量
- labels:真实标签,shape=[N, 1]
输出:
- 损失值:shape=[1]
"""
self.predicts = predicts
self.labels = labels
self.num = self.predicts.shape[0]
loss = -1. / self.num * (torch.matmul(self.labels.t(), torch.log(self.predicts)) + torch.matmul((1-self.labels.t()), torch.log(1-self.predicts)))
loss = torch.squeeze(loss, axis=1)
return loss
# 测试一下
# 生成一组长度为3,值为1的标签数据
labels = torch.ones(size=[3,1])
# 计算风险函数
bce_loss = BinaryCrossEntropyLoss()
print(bce_loss(outputs, labels))
3.1.4 模型优化
不同于线性回归中直接使用最小二乘法即可进行模型参数的求解,Logistic回归需要使用优化算法对模型参数进行有限次地迭代来获取更优的模型,从而尽可能地降低风险函数的值。
在机器学习任务中,最简单、常用的优化算法是梯度下降法。
使用梯度下降法进行模型优化,首先需要初始化参数W和 b,然后不断地计算它们的梯度,并沿梯度的反方向更新参数。
def logistic(x):
return 1 / (1 + torch.exp(-x))
class model_LR():
def __init__(self, input_dim):
super(model_LR, self).__init__()
# 存放线性层参数
self.params = {}
# 将线性层的权重参数全部初始化为0
self.params['w'] = torch.zeros(size=[input_dim, 1])
# self.params['w'] = paddle.normal(mean=0, std=0.01, shape=[input_dim, 1])
# 将线性层的偏置参数初始化为0
self.params['b'] = torch.zeros(size=[1])
# 存放参数的梯度
self.grads = {}
self.X = None
self.outputs = None
def __call__(self, inputs):
return self.forward(inputs)
def forward(self, inputs):
self.X = inputs
# 线性计算
score = torch.matmul(inputs, self.params['w']) + self.params['b']
# Logistic 函数
self.outputs = logistic(score)
return self.outputs
def backward(self, labels):
"""
输入:
- labels:真实标签,shape=[N, 1]
"""
N = labels.shape[0]
# 计算偏导数
self.grads['w'] = -1 / N * torch.matmul(self.X.t(), (labels - self.outputs))
self.grads['b'] = -1 / N * torch.sum(labels - self.outputs)
from abc import abstractmethod
# 优化器基类
class Optimizer(object):
def __init__(self, init_lr, model):
"""
优化器类初始化
"""
# 初始化学习率,用于参数更新的计算
self.init_lr = init_lr
# 指定优化器需要优化的模型
self.model = model
@abstractmethod
def step(self):
"""
定义每次迭代如何更新参数
"""
pass
class SimpleBatchGD(Optimizer):
def __init__(self, init_lr, model):
super(SimpleBatchGD, self).__init__(init_lr=init_lr, model=model)
def step(self):
# 参数更新
# 遍历所有参数,按照公式(3.8)和(3.9)更新参数
if isinstance(self.model.params, dict):
for key in self.model.params.keys():
self.model.params[key] = self.model.params[key] - self.init_lr * self.model.grads[key]
3.1.5 评价指标
在分类任务中,通常使用准确率(Accuracy)作为评价指标。
def accuracy(preds, labels):
"""
输入:
- preds:预测值,二分类时,shape=[N, 1],N为样本数量,多分类时,shape=[N, C],C为类别数量
- labels:真实标签,shape=[N, 1]
输出:
- 准确率:shape=[1]
"""
# 判断是二分类任务还是多分类任务,preds.shape[1]=1时为二分类任务,preds.shape[1]>1时为多分类任务
if preds.shape[1] == 1:
# 二分类时,判断每个概率值是否大于0.5,当大于0.5时,类别为1,否则类别为0
preds = (preds>=0.5).to(torch.float32)
else:
# 多分类时,使用'torch.argmax'计算最大元素索引作为类别
preds = torch.argmax(preds,dim=1)
return torch.mean((preds == labels).float())
# 假设模型的预测值为[[0.],[1.],[1.],[0.]],真实类别为[[1.],[1.],[0.],[0.]],计算准确率
preds = torch.tensor([[0.],[1.],[1.],[0.]])
labels = torch.tensor([[1.],[1.],[0.],[0.]])
print("accuracy is:", accuracy(preds, labels))
3.1.6 完善Runner类
基于RunnerV1,本章的RunnerV2类在训练过程中使用梯度下降法进行网络优化,模型训练过程中计算在训练集和验证集上的损失及评估指标并打印,训练过程中保存最优模型。
# 用RunnerV2类封装整个训练过程
class RunnerV2(object):
def __init__(self, model, optimizer, metric, loss_fn):
self.model = model
self.optimizer = optimizer
self.loss_fn = loss_fn
self.metric = metric
# 记录训练过程中的评价指标变化情况
self.train_scores = []
self.dev_scores = []
# 记录训练过程中的损失函数变化情况
self.train_loss = []
self.dev_loss = []
def train(self, train_set, dev_set, **kwargs):
# 传入训练轮数,如果没有传入值则默认为0
num_epochs = kwargs.get("num_epochs", 0)
# 传入log打印频率,如果没有传入值则默认为100
log_epochs = kwargs.get("log_epochs", 100)
# 传入模型保存路径,如果没有传入值则默认为"best_model.pdparams"
save_path = kwargs.get("save_path", "best_model.pdparams")
# 梯度打印函数,如果没有传入则默认为"None"
print_grads = kwargs.get("print_grads", None)
# 记录全局最优指标
best_score = 0
# 进行num_epochs轮训练
for epoch in range(num_epochs):
X, y = train_set
# 获取模型预测
logits = self.model(X)
# 计算交叉熵损失
trn_loss = self.loss_fn(logits, y).item()
self.train_loss.append(trn_loss)
# 计算评价指标
trn_score = self.metric(logits, y).item()
self.train_scores.append(trn_score)
# 计算参数梯度
self.model.backward(y)
if print_grads is not None:
# 打印每一层的梯度
print_grads(self.model)
# 更新模型参数
self.optimizer.step()
dev_score, dev_loss = self.evaluate(dev_set)
# 如果当前指标为最优指标,保存该模型
if dev_score > best_score:
self.save_model(save_path)
print(f"best accuracy performence has been updated: {best_score:.5f} --> {dev_score:.5f}")
best_score = dev_score
if epoch % log_epochs == 0:
print(f"[Train] epoch: {epoch}, loss: {trn_loss}, score: {trn_score}")
print(f"[Dev] epoch: {epoch}, loss: {dev_loss}, score: {dev_score}")
def evaluate(self, data_set):
X, y = data_set
# 计算模型输出
logits = self.model(X)
# 计算损失函数
loss = self.loss_fn(logits, y).item()
self.dev_loss.append(loss)
# 计算评价指标
score = self.metric(logits, y).item()
self.dev_scores.append(score)
return score, loss
def predict(self, X):
return self.model(X)
def save_model(self, save_path):
torch.save(self.model.params, save_path)
def load_model(self, model_path):
self.model.params = torch.load(model_path)
3.1.7 模型训练
Logistic回归模型的训练,使用交叉熵损失函数和梯度下降法进行优化。
使用训练集和验证集进行模型训练,共训练 500个epoch,每隔50个epoch打印出训练集上的指标。
# 固定随机种子,保持每次运行结果一致
torch.manual_seed(102)
# 特征维度
input_dim = 2
# 学习率
lr = 0.1
n_samples=1000
n_samples_out = n_samples // 2
n_samples_in = n_samples - n_samples_out
# 采集第1类数据,特征为(x,y)
# 使用'torch.linspace'在0到pi上均匀取n_samples_out个值
# 使用'torch.cos'计算上述取值的余弦值作为特征1,使用'torch.sin'计算上述取值的正弦值作为特征2
outer_circ_x = torch.cos(torch.linspace(0, math.pi, n_samples_out))
outer_circ_y = torch.sin(torch.linspace(0, math.pi, n_samples_out))
inner_circ_x = 1 - torch.cos(torch.linspace(0, math.pi, n_samples_in))
inner_circ_y = 0.5 - torch.sin(torch.linspace(0, math.pi, n_samples_in))
num_train = 640
num_dev = 160
num_test = 200
X = torch.stack(
[torch.concat([outer_circ_x, inner_circ_x]),
torch.concat([outer_circ_y, inner_circ_y])],
axis=1
)
y = torch.concat(
[torch.zeros(size=[n_samples_out]), torch.ones(size=[n_samples_in])]
)
X_train, y_train = X[:num_train], y[:num_train]
X_dev, y_dev = X[num_train:num_train + num_dev], y[num_train:num_train + num_dev]
X_test, y_test = X[num_train + num_dev:], y[num_train + num_dev:]
y_train = y_train.reshape([-1,1])
y_dev = y_dev.reshape([-1,1])
y_test = y_test.reshape([-1,1])
# 实例化模型
model = model_LR(input_dim=input_dim)
# 指定优化器
optimizer = SimpleBatchGD(init_lr=lr, model=model)
# 指定损失函数
loss_fn = BinaryCrossEntropyLoss()
# 指定评价方式
metric = accuracy
# 实例化RunnerV2类,并传入训练配置
runner = RunnerV2(model, optimizer, metric, loss_fn)
runner.train([X_train, y_train], [X_dev, y_dev], num_epochs=500, log_epochs=50, save_path="best_model.pdparams")
结果:
best accuracy performence has been updated: 0.00000 --> 0.75000
[Train] epoch: 0, loss: 0.693146824836731, score: 0.5
[Dev] epoch: 0, loss: 0.6844645738601685, score: 0.75
[Train] epoch: 50, loss: 0.48319950699806213, score: 0.807812511920929
[Dev] epoch: 50, loss: 0.519908607006073, score: 0.75
[Train] epoch: 100, loss: 0.4398561418056488, score: 0.8140624761581421
[Dev] epoch: 100, loss: 0.4893949627876282, score: 0.75
best accuracy performence has been updated: 0.75000 --> 0.75625
[Train] epoch: 150, loss: 0.42317506670951843, score: 0.817187488079071
[Dev] epoch: 150, loss: 0.4799765646457672, score: 0.7562500238418579
best accuracy performence has been updated: 0.75625 --> 0.76250
[Train] epoch: 200, loss: 0.41500502824783325, score: 0.823437511920929
[Dev] epoch: 200, loss: 0.47652289271354675, score: 0.762499988079071
[Train] epoch: 250, loss: 0.4104517996311188, score: 0.8203125
[Dev] epoch: 250, loss: 0.47522956132888794, score: 0.7437499761581421
[Train] epoch: 300, loss: 0.407705694437027, score: 0.8218749761581421
[Dev] epoch: 300, loss: 0.4748341143131256, score: 0.75
[Train] epoch: 350, loss: 0.4059614837169647, score: 0.823437511920929
[Dev] epoch: 350, loss: 0.4748414158821106, score: 0.7562500238418579
[Train] epoch: 400, loss: 0.40481358766555786, score: 0.8265625238418579
[Dev] epoch: 400, loss: 0.47503310441970825, score: 0.75
[Train] epoch: 450, loss: 0.40403881669044495, score: 0.828125
[Dev] epoch: 450, loss: 0.4753051698207855, score: 0.75
可视化观察训练集与验证集的准确率和损失的变化情况。
# 可视化观察训练集与验证集的指标变化情况
def plot(runner,fig_name):
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
epochs = [i for i in range(len(runner.train_scores))]
# 绘制训练损失变化曲线
plt.plot(epochs, runner.train_loss, color='#e4007f', label="Train loss")
# 绘制评价损失变化曲线
plt.plot(epochs, runner.dev_loss, color='#f19ec2', linestyle='--', label="Dev loss")
# 绘制坐标轴和图例
plt.ylabel("loss", fontsize='large')
plt.xlabel("epoch", fontsize='large')
plt.legend(loc='upper right', fontsize='x-large')
plt.subplot(1,2,2)
# 绘制训练准确率变化曲线
plt.plot(epochs, runner.train_scores, color='#e4007f', label="Train accuracy")
# 绘制评价准确率变化曲线
plt.plot(epochs, runner.dev_scores, color='#f19ec2', linestyle='--', label="Dev accuracy")
# 绘制坐标轴和图例
plt.ylabel("score", fontsize='large')
plt.xlabel("epoch", fontsize='large')
plt.legend(loc='lower right', fontsize='x-large')
plt.tight_layout()
plt.savefig(fig_name)
plt.show()
plot(runner,fig_name='linear-acc.pdf')
3.1.8 模型评价
使用测试集对训练完成后的最终模型进行评价,观察模型在测试集上的准确率和loss数据。
score, loss = runner.evaluate([X_test, y_test])
print("[Test] score/loss: {:.4f}/{:.4f}".format(score, loss))
可视化观察拟合的决策边界 Xw+b=0。
def decision_boundary(w, b, x1):
w1, w2 = w
x2 = (- w1 * x1 - b) / w2
return x2
plt.figure(figsize=(5,5))
# 绘制原始数据
plt.scatter(X[:, 0].tolist(), X[:, 1].tolist(), marker='*', c=y.tolist())
w = model.params['w']
b = model.params['b']
x1 = torch.linspace(-2, 3, 1000)
x2 = decision_boundary(w, b, x1)
# 绘制决策边界
plt.plot(x1.tolist(), x2.tolist(), color="red")
plt.show()
3.2 基于Softmax回归的多分类任务
Logistic回归可以有效地解决二分类问题。
但在分类任务中,还有一类多分类问题,即类别数C大于2 的分类问题。
Softmax回归就是Logistic回归在多分类问题上的推广。
3.2.1 数据集构建
数据来自3个不同的簇,每个簇对一个类别。我们采集1000条样本,每个样本包含2个特征。
import numpy as np
import torch
import matplotlib.pyplot as plt
def make_multiclass_classification(n_samples=100, n_features=2, n_classes=3, shuffle=True, noise=0.1):
"""
生成带噪音的多类别数据
输入:
- n_samples:数据量大小,数据类型为int
- n_features:特征数量,数据类型为int
- shuffle:是否打乱数据,数据类型为bool
- noise:以多大的程度增加噪声,数据类型为None或float,noise为None时表示不增加噪声
输出:
- X:特征数据,shape=[n_samples,2]
- y:标签数据, shape=[n_samples,1]
"""
# 计算每个类别的样本数量
n_samples_per_class = [int(n_samples / n_classes) for k in range(n_classes)]
for i in range(n_samples - sum(n_samples_per_class)):
n_samples_per_class[i % n_classes] += 1
# 将特征和标签初始化为0
X = torch.zeros([n_samples, n_features])
y = torch.zeros([n_samples])
# 随机生成3个簇中心作为类别中心
centroids = torch.randperm(2 ** n_features)[:n_classes]
centroids_bin = np.unpackbits(centroids.numpy().astype('uint8')).reshape((-1, 8))[:, -n_features:]
centroids = torch.tensor(centroids_bin, )
# 控制簇中心的分离程度
centroids = 1.5 * centroids - 1
# 随机生成特征值
X[:, :n_features] = torch.rand(size=[n_samples, n_features])
stop = 0
# 将每个类的特征值控制在簇中心附近
for k, centroid in enumerate(centroids):
start, stop = stop, stop + n_samples_per_class[k]
# 指定标签值
y[start:stop] = k % n_classes
X_k = X[start:stop, :n_features]
# 控制每个类别特征值的分散程度
A = 2 * torch.rand(size=[n_features, n_features]) - 1
X_k[...] = torch.matmul(X_k, A)
X_k += centroid
X[start:stop, :n_features] = X_k
# 如果noise不为None,则给特征加入噪声
if noise > 0.0:
# 生成noise掩膜,用来指定给那些样本加入噪声
noise_mask = torch.rand([n_samples]) < noise
for i in range(len(noise_mask)):
if noise_mask[i]:
# 给加噪声的样本随机赋标签值
y[i] = torch.randint(n_classes, size=[1])
# 如果shuffle为True,将所有数据打乱
if shuffle:
idx = torch.randperm(X.shape[0])
X = X[idx]
y = y[idx]
return X, y
# 固定随机种子,保持每次运行结果一致
torch.seed()
# 采样1000个样本
n_samples = 1000
X, y = make_multiclass_classification(n_samples=n_samples, n_features=2, n_classes=3, noise=0.2)
# 可视化生产的数据集,不同颜色代表不同类别
plt.figure(figsize=(5,5))
plt.scatter(x=X[:, 0].tolist(), y=X[:, 1].tolist(), marker='*', c=y.tolist())
plt.savefig('linear-dataset-vis2.pdf')
plt.show()
num_train = 640
num_dev = 160
num_test = 200
X_train, y_train = X[:num_train], y[:num_train]
X_dev, y_dev = X[num_train:num_train + num_dev], y[num_train:num_train + num_dev]
X_test, y_test = X[num_train + num_dev:], y[num_train + num_dev:]
# 打印X_train和y_train的维度
print("X_train shape: ", X_train.shape, "y_train shape: ", y_train.shape)
# 打印前5个数据的标签
print(y_train[:5])
3.2.2 模型构建
import torch
# x为tensor
def softmax(X):
"""
输入:
- X:shape=[N, C],N为向量数量,C为向量维度
"""
x_max = torch.max(X)
x_exp = torch.exp(X - x_max)
partition = torch.sum(x_exp)
return x_exp / partition
# 观察softmax的计算方式
X = torch.tensor([[0.1, 0.2, 0.3, 0.4],[1,2,3,4]])
predict = softmax(X)
print(predict)
思考题:Logistic函数是激活函数。Softmax函数是激活函数么?谈谈你的看法。
softmax通常来讲是激活函数,但是softmax函数要与交叉熵损失函数一起使用来避免数值溢出的问题。所以,在我们的深度学习框架中,在网络构造中通常是看不见softmax函数的,而在我们调用交叉熵损失函数时,框架会在其之前自动为我们添加softmax函数。
3.2.3 损失函数
import torch
class model_SR():
def __init__(self, input_dim, output_dim):
super(model_SR, self).__init__()
self.params = {}
# 将线性层的权重参数全部初始化为0
self.params['W'] = torch.zeros(size=[input_dim, output_dim])
# self.params['W'] = torch.normal(mean=0, std=0.01, size=[input_dim, output_dim])
# 将线性层的偏置参数初始化为0
self.params['b'] = torch.zeros(size=[output_dim])
self.outputs = None
def __call__(self, inputs):
return self.forward(inputs)
def forward(self, inputs):
"""
输入:
- inputs: shape=[N,D], N是样本数量,D是特征维度
输出:
- outputs:预测值,shape=[N,C],C是类别数
"""
# 线性计算
score = torch.matmul(inputs, self.params['W']) + self.params['b']
# Softmax 函数
self.outputs = softmax(score)
return self.outputs
# 随机生成1条长度为4的数据
inputs = torch.randn(size=[1,4])
# 实例化模型,这里令输入长度为4,输出类别数为3
model = model_SR(input_dim=4, output_dim=3)
outputs = model(inputs)
class MultiCrossEntropyLoss():
def __init__(self):
self.predicts = None
self.labels = None
self.num = None
def __call__(self, predicts, labels):
return self.forward(predicts, labels)
def forward(self, predicts, labels):
"""
输入:
- predicts:预测值,shape=[N, 1],N为样本数量
- labels:真实标签,shape=[N, 1]
输出:
- 损失值:shape=[1]
"""
self.predicts = predicts
self.labels = labels
self.num = self.predicts.shape[0]
loss = 0
for i in range(0, self.num):
index = self.labels[i]
loss -= torch.log(self.predicts[i][index])
return loss / self.num
# 测试一下
# 假设真实标签为第1类
labels = torch.tensor([0])
# 计算风险函数
mce_loss = MultiCrossEntropyLoss()
print(mce_loss(outputs, labels))
3.2.4 模型优化
使用3.1.4.2中实现的梯度下降法进行参数更新
class model_SR():
def __init__(self, input_dim, output_dim):
super(model_SR, self).__init__()
self.params = {}
# 将线性层的权重参数全部初始化为0
self.params['W'] = torch.zeros(size=[input_dim, output_dim])
# self.params['W'] = torch.normal(mean=0, std=0.01, size=[input_dim, output_dim])
# 将线性层的偏置参数初始化为0
self.params['b'] = torch.zeros(size=[output_dim])
# 存放参数的梯度
self.grads = {}
self.X = None
self.outputs = None
self.output_dim = output_dim
def __call__(self, inputs):
return self.forward(inputs)
def forward(self, inputs):
self.X = inputs
# 线性计算
score = torch.matmul(self.X, self.params['W']) + self.params['b']
# Softmax 函数
self.outputs = softmax(score)
return self.outputs
def backward(self, labels):
"""
输入:
- labels:真实标签,shape=[N, 1],其中N为样本数量
"""
# 计算偏导数
N =labels.shape[0]
labels = torch.nn.functional.one_hot(labels, self.output_dim)
self.grads['W'] = -1 / N * torch.matmul(self.X.t(), (labels-self.outputs))
self.grads['b'] = -1 / N * torch.matmul(torch.ones(shape=[N]), (labels-self.outputs))
3.2.5 模型训练
实例化RunnerV2类,并传入训练配置。使用训练集和验证集进行模型训练,共训练500个epoch。每隔50个epoch打印训练集上的指标。
# 固定随机种子,保持每次运行结果一致
torch.manual_seed(102)
# 特征维度
input_dim = 2
# 学习率
lr = 0.1
# 实例化模型
model = model_LR(input_dim=input_dim)
# 指定优化器
optimizer = SimpleBatchGD(init_lr=lr, model=model)
# 指定损失函数
loss_fn = BinaryCrossEntropyLoss()
# 指定评价方式
metric = accuracy
# 实例化Runner类,并传入训练配置
runner = Runner(model, optimizer, metric, loss_fn)
runner.train([X_train, y_train], [X_dev, y_dev], num_epochs=500, log_epochs=50, save_path="best_model.pdparams")
结果:
best accuracy performence has been updated: 0.00000 --> 0.75000
[Train] epoch: 0, loss: 0.693146824836731, score: 0.5
[Dev] epoch: 0, loss: 0.6844645738601685, score: 0.75
[Train] epoch: 50, loss: 0.48319950699806213, score: 0.807812511920929
[Dev] epoch: 50, loss: 0.519908607006073, score: 0.75
[Train] epoch: 100, loss: 0.4398561418056488, score: 0.8140624761581421
[Dev] epoch: 100, loss: 0.4893949627876282, score: 0.75
best accuracy performence has been updated: 0.75000 --> 0.75625
[Train] epoch: 150, loss: 0.42317506670951843, score: 0.817187488079071
[Dev] epoch: 150, loss: 0.4799765646457672, score: 0.7562500238418579
best accuracy performence has been updated: 0.75625 --> 0.76250
[Train] epoch: 200, loss: 0.41500502824783325, score: 0.823437511920929
[Dev] epoch: 200, loss: 0.47652289271354675, score: 0.762499988079071
[Train] epoch: 250, loss: 0.4104517996311188, score: 0.8203125
[Dev] epoch: 250, loss: 0.47522956132888794, score: 0.7437499761581421
[Train] epoch: 300, loss: 0.407705694437027, score: 0.8218749761581421
[Dev] epoch: 300, loss: 0.4748341143131256, score: 0.75
[Train] epoch: 350, loss: 0.4059614837169647, score: 0.823437511920929
[Dev] epoch: 350, loss: 0.4748414158821106, score: 0.7562500238418579
[Train] epoch: 400, loss: 0.40481358766555786, score: 0.8265625238418579
[Dev] epoch: 400, loss: 0.47503310441970825, score: 0.75
[Train] epoch: 450, loss: 0.40403881669044495, score: 0.828125
[Dev] epoch: 450, loss: 0.4753051698207855, score: 0.75
# 可视化观察训练集与验证集的指标变化情况
def plot(runner,fig_name):
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
epochs = [i for i in range(len(runner.train_scores))]
# 绘制训练损失变化曲线
plt.plot(epochs, runner.train_loss, color='#e4007f', label="Train loss")
# 绘制评价损失变化曲线
plt.plot(epochs, runner.dev_loss, color='#f19ec2', linestyle='--', label="Dev loss")
# 绘制坐标轴和图例
plt.ylabel("loss", fontsize='large')
plt.xlabel("epoch", fontsize='large')
plt.legend(loc='upper right', fontsize='x-large')
plt.subplot(1,2,2)
# 绘制训练准确率变化曲线
plt.plot(epochs, runner.train_scores, color='#e4007f', label="Train accuracy")
# 绘制评价准确率变化曲线
plt.plot(epochs, runner.dev_scores, color='#f19ec2', linestyle='--', label="Dev accuracy")
# 绘制坐标轴和图例
plt.ylabel("score", fontsize='large')
plt.xlabel("epoch", fontsize='large')
plt.legend(loc='lower right', fontsize='x-large')
plt.tight_layout()
plt.savefig(fig_name)
plt.show()
# 可视化观察训练集与验证集的准确率变化情况
plot(runner,fig_name='linear-acc2.pdf')
3.2.6 模型评价
使用测试集对训练完成后的最终模型进行评价,观察模型在测试集上的准确率。
score, loss = runner.evaluate([X_test, y_test])
print("[Test] score/loss: {:.4f}/{:.4f}".format(score, loss))
结果:
[Test] score/loss: 0.8400/0.7014
3.3 实践:基于Softmax回归完成鸢尾花分类任务
在本节,我们用入门深度学习的基础实验之一“鸢尾花分类任务”来进行实践,使用经典学术数据集Iris作为训练数据,实现基于Softmax回归的鸢尾花分类任务。
- 缺失值分析
对数据集中的缺失值或异常值等情况进行分析和处理,保证数据可以被模型正常读取。
- 异常值处理
通过箱线图直观的显示数据分布,并观测数据中的异常值。
from sklearn.datasets import load_iris
import pandas
import numpy as np
import matplotlib.pyplot as plt
iris_features = np.array(load_iris().data, dtype=np.float32)
iris_labels = np.array(load_iris().target, dtype=np.int32)
print(pandas.isna(iris_features).sum())
print(pandas.isna(iris_labels).sum())
# 箱线图查看异常值分布
def boxplot(features):
feature_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
# 连续画几个图片
plt.figure(figsize=(5, 5), dpi=200)
# 子图调整
plt.subplots_adjust(wspace=0.6)
# 每个特征画一个箱线图
for i in range(4):
plt.subplot(2, 2, i+1)
# 画箱线图
plt.boxplot(features[:, i],
showmeans=True,
whiskerprops={"color":"#E20079", "linewidth":0.4, 'linestyle':"--"},
flierprops={"markersize":0.4},
meanprops={"markersize":1})
# 图名
plt.title(feature_names[i], fontdict={"size":5}, pad=2)
# y方向刻度
plt.yticks(fontsize=4, rotation=90)
plt.tick_params(pad=0.5)
# x方向刻度
plt.xticks([])
plt.savefig('ml-vis.pdf')
plt.show()
boxplot(iris_features)
数据读取
将80%80%的数据用于模型训练,10%10%的数据用于模型验证,10%10%的数据用于模型测试。
def load_data(shuffle=True): # 加载鸾尾花数据
"""
- shuffle:是否打乱数据,数据类型为bool
- X:特征数据,shape=[150,4]
- y:标签数据, shape=[150]
"""
# 加载原始数据
X = np.array(load_iris().data, dtype=np.float32)
y = np.array(load_iris().target, dtype=np.int32)
X = torch.tensor(X)
y = torch.tensor(y)
# 数据归一化
X_min = torch.min(X, 0)
X_max = torch.max(X, 0)
X = (X-X_min.values) / (X_max.values - X_min.values)
# 如果shuffle为True,随机打乱数据
if shuffle:
idx = torch.randperm(X.shape[0])
X = X[idx]
y = y[idx]
return X, y
torch.manual_seed(102)
num_train = 120
num_dev = 15
num_test = 15
X, y = load_data(shuffle=True)
print("X shape: ", X.shape, "y shape: ", y.shape)
X_train, y_train = X[:num_train], y[:num_train]
X_dev, y_dev = X[num_train:num_train + num_dev], y[num_train:num_train + num_dev]
X_test, y_test = X[num_train + num_dev:], y[num_train + num_dev:]
3.3.2 模型构建
使用Softmax回归模型进行鸢尾花分类实验,将模型的输入维度定义为4,输出维度定义为3。
# 维度
input_dim = 4
# 类别数
output_dim = 3
# 实例化模型
model = op.model_SR(input_dim=input_dim, output_dim=output_dim)
3.3.3 模型训练
实例化RunnerV2类,使用训练集和验证集进行模型训练,共训练80个epoch,其中每隔10个epoch打印训练集上的指标,并且保存准确率最高的模型作为最佳模型。
# 学习率
lr = 0.2
# 梯度下降法
optimizer = opitimizer.SimpleBatchGD(init_lr=lr, model=model)
# 交叉熵损失
loss_fn = op.MultiCrossEntropyLoss()
# 准确率
metric = metric.accuracy
# 实例化RunnerV2
runner = RunnerV2(model, optimizer, metric, loss_fn)
# 启动训
runner.train([X_train, y_train], [X_dev, y_dev], num_epochs=200, log_epochs=10, save_path="best_model.pdparams")
结果:
best accuracy performence has been updated: 0.00000 --> 0.40000
[Train] epoch: 0, loss: 1.09861159324646, score: 0.31666672229766846
[Dev] epoch: 0, loss: 1.0828731060028076, score: 0.40000003576278687
best accuracy performence has been updated: 0.40000 --> 0.46667
best accuracy performence has been updated: 0.46667 --> 0.66667
best accuracy performence has been updated: 0.66667 --> 0.73333
[Train] epoch: 10, loss: 0.9869819283485413, score: 0.6416667699813843
[Dev] epoch: 10, loss: 0.974640965461731, score: 0.73333340883255
[Train] epoch: 20, loss: 0.9098353385925293, score: 0.6500000953674316
[Dev] epoch: 20, loss: 0.8997330069541931, score: 0.73333340883255
[Train] epoch: 30, loss: 0.847343385219574, score: 0.6833333969116211
[Dev] epoch: 30, loss: 0.8396621346473694, score: 0.73333340883255
[Train] epoch: 40, loss: 0.7956345677375793, score: 0.7250000238418579
[Dev] epoch: 40, loss: 0.7903936505317688, score: 0.73333340883255
[Train] epoch: 50, loss: 0.7523643970489502, score: 0.7416666746139526
[Dev] epoch: 50, loss: 0.7495585083961487, score: 0.73333340883255
[Train] epoch: 60, loss: 0.7158005237579346, score: 0.783333420753479
[Dev] epoch: 60, loss: 0.7153650522232056, score: 0.73333340883255
best accuracy performence has been updated: 0.73333 --> 0.80000
[Train] epoch: 70, loss: 0.6845439672470093, score: 0.8083333969116211
[Dev] epoch: 70, loss: 0.6863659620285034, score: 0.8000000715255737
best accuracy performence has been updated: 0.80000 --> 0.86667
[Train] epoch: 80, loss: 0.657481849193573, score: 0.8166667819023132
[Dev] epoch: 80, loss: 0.6614803075790405, score: 0.8666667342185974
[Train] epoch: 90, loss: 0.6339080333709717, score: 0.8416667580604553
[Dev] epoch: 90, loss: 0.64008629322052, score: 0.8666667342185974
[Train] epoch: 100, loss: 0.613059937953949, score: 0.8416667580604553
[Dev] epoch: 100, loss: 0.6212700009346008, score: 0.8666667342185974
3.3.4 模型评价
使用测试数据对在训练过程中保存的最佳模型进行评价,观察模型在测试集上的准确率情况。
# 加载最优模型
runner.load_model('best_model.pdparams')
# 模型评价
score, loss = runner.evaluate([X_test, y_test])
print("[Test] score/loss: {:.4f}/{:.4f}".format(score, loss))
3.3.5 模型预测
使用保存好的模型,对测试集中的数据进行模型预测,并取出1条数据观察模型效果。
# 预测测试集数据
logits = runner.predict(X_test)
# 观察其中一条样本的预测结果
pred = paddle.argmax(logits[0]).numpy()
# 获取该样本概率最大的类别
label = y_test[0].numpy()
# 输出真实类别与预测类别
print("The true category is {} and the predicted category is {}".format(label[0], pred[0]))
3.5 实验拓展
尝试调整学习率和训练轮数等超参数,观察是否能够得到更高的精度;
1.将学习率调整维0.001,训练次数增加至250
[Test] score/loss:0.6975/5.4614
2.第二种学习率0.15,训练次数300
[Test] score/loss:0.6975/2.7812
3.第三种学习率0.25,训练次数250
[Test] score/loss:0.5600/0.8179
总结
本章主要学习了logistic函数和softmax函数及其模型,了解logistic回归是主要用于处理二分类问题的模型及其构建,学会了softmax回归的应用。