动手学深度学习-Pytorch第三章
线性回归
概述
对于特征集合X,预测值yˆ ∈ Rn 可以通过矩阵-向量乘法表⽰为:yˆ = Xw + b
最终要找到一组w和b,在新的数据上实现对y值的预测
由于存在误差,所以需要加入个噪声项来考虑观测误差带
来的影响
为了使得到的w和b更准确,需要有(1)度量模型质量的方法;(2)更新模型参数的方法
定义time类用于时间基准测试
class Timer:
def __init__(self):
self.times=[]
self.start()
def start(self):
self.tik=time.time()
def stop(self):
self.times.append(time.time()-self.tik)
return self.times[-1]
def avg(self):
return sum(self.times)/len(self.times)
def sum(self):
return sum(self.times)
def cumsum(self):
return np.array(self.times).cumsum().tolist()
正态分布可视化
def normal(x,mu,sigma):
p=1/math.sqrt(2*math.pi*sigma**2)
return p*np.exp(-0.5/sigma**2*(x-mu)**2)
x=np.arange(-7,7,0.01)
params=[(0,1),(0,2),(3,1)]
y1=normal(x,0,1)
y2=normal(x,0,2)
y3=normal(x,3,1)
plt.plot(x,y1)
plt.plot(x,y2)
plt.plot(x,y3)
plt.legend(labels=['$\mu = 0, \sigma^2=1$', '$\mu = 0, \sigma^2=2$', '$\mu = 3, \sigma^2=1$'])
plt.show()
小结
1.机器学习的关键因素:训练数据、损失函数、优化算法、模型本身
2.矢量化能加快运行速度
3.最小化目标函数与执行最大似然估计等同
练习题参考-https://blog.csdn.net/qq_43853021/article/details/122445047
从零实现线性回归
import torch
import matplotlib.pyplot as plt
import random
import math
#生成数据集
def synthetic_data(w,b,num_examples):
X=torch.normal(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))
true_w=torch.tensor([2,-3.4])
true_b=4.2
features,labels=synthetic_data(true_w,true_b,1000)
print(features[0],'\n',labels[0])
plt.figure()
plt.scatter(features[:,1].detach().numpy(),labels.detach().numpy(),1)
plt.show()
#读取数据集
def data_iter(batch_size,features,labels):
num_examples=len(features)
indices=list(range(num_examples))
random.shuffle(indices)
for i in range(0,num_examples,batch_size):
batch_indices=torch.tensor(
indices[i:min(i+batch_size,num_examples)])
yield features[batch_indices],labels[batch_indices]
batch_size=10
for X,y in data_iter(batch_size,features,labels):
print(X,'\n',y)
break
#初始化参数
w=torch.normal(0,0.01,size=(2,1),requires_grad=True)
b=torch.zeros(1,requires_grad=True)
#定义模型
def linreg(X,w,b):
return torch.matmul(X,w)+b
#定义损失函数
def square_loss(y_hat,y):
return (y_hat-y.reshape(y_hat.shape))**2
#定义优化算法
def sgd(params,lr,batch_size):
with torch.no_grad():
for param in params:
param-=lr*param.grad/batch_size
param.grad.zero_()
#训练
lr=0.01
num_epochs=3
net=linreg
loss=square_loss
for epoch in range(num_epochs):
for X,y in data_iter(batch_size,features,labels):
l=square_loss(linreg(X,w,b),y)
l.sum().backward()
sgd([w,b],lr,batch_size)
with torch.no_grad():
train_l=loss(net(features,w,b),labels)
print(f'epoch{epoch+1},loss{float(train_l.mean()):f}')
使用API实现线性回归
import torch
from torch.utils import data
from torch import nn
#生成数据集
def synthetic_data(w,b,num_examples):
X=torch.normal(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))
true_w=torch.tensor([2,-3.4])
true_b=4.2
features,labels=synthetic_data(true_w,true_b,1000)
#读取数据集
def load_array(data_arrays,batch_size,is_train=True):
'''构建python迭代器'''
dataset=data.TensorDataset(*data_arrays)
return data.DataLoader(dataset,batch_size,shuffle=is_train)
batch_size=10
data_iter=load_array((features,labels),batch_size)
print(next(iter(data_iter)))
#定义模型
'''利用sequential将模型连接和参数传递
Linear为全连接层,两个特征生成一个标量'''
net=nn.Sequential(nn.Linear(2,1))
#初始化参数
net[0].weight.data.normal_(0,0.01)
net[0].bias.data.fill_(0)
#定义损失函数
loss=nn.MSELoss()
#定义优化算法
trainer=torch.optim.SGD(net.parameters(),lr=0.01)
#训练
'''设置迭代次数,在每次迭代中要遍历数据集抽取小批量数据的标签和特征,
计算损失函数,反向传播计算梯度,更新参数
'''
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)
Softmax回归
生成的o为具体各个类别的概率,由于具有一定的随机性,为保证概率值非负且和为1,利用softmax转换为非负且和为1的向量值
损失函数(交叉熵损失函数)
one-hot编码使得在损失函数计算中只保留了一项
图像分类
数据集准备与读取
def load_data_fashion_mnist(batch_size,resize=None):
trans=[transforms.ToTensor()]
if resize:
trans.insert(0,transforms.Resize(resize))
trans=transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(
root="../data", train=True, transform=trans, download=True)
mnist_test = torchvision.datasets.FashionMNIST(
root="../data", train=False, transform=trans, download=True)
return (data.DataLoader(mnist_train,batch_size,shuffle=True),
data.DataLoader(mnist_test,batch_size,shuffle=False))
train_iter,test_iter=load_data_fashion_mnist(32,resize=64)
for X,y in train_iter:
print(X.shape,X.dtype,y.shape,y.dtype)
break
模型搭建与训练
import torch
import torchvision
from torch.utils import data
from torchvision import transforms
from torch import nn
from torch.utils.tensorboard import SummaryWriter
def load_data_fashion_mnist(batch_size,resize=None):
trans=[transforms.ToTensor()]
if resize:
trans.insert(0,transforms.Resize(resize))
trans=transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(
root="../data", train=True, transform=trans, download=True)
mnist_test = torchvision.datasets.FashionMNIST(
root="../data", train=False, transform=trans, download=True)
return (data.DataLoader(mnist_train,batch_size,shuffle=True),
data.DataLoader(mnist_test,batch_size,shuffle=False))
batch_size=256
train_iter,test_iter=load_data_fashion_mnist(batch_size)
def accuracy(y_hat,y):
if len(y_hat.shape) >1and y_hat.shape[1]>1:
y_hat=y_hat.argmax(axis=1)
cmp=y_hat.type(y.dtype)==y
return float(cmp.type(y.dtype).sum())
class Accumulator:
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 train_epoch_ch3(net,train_iter,loss,updater):
if isinstance(net,torch.nn.Module):
net.train()
metric=Accumulator(3)
for X,y in train_iter:
y_hat=net(X)
l=loss(y_hat,y)
if isinstance(updater,torch.optim.Optimizer):
updater.zero_grad()
l.mean().backward()
updater.step()
else:
#定制的优化器,暂无使用
l.sum().backward()
updater(X.shape[0])
metric.add(l.sum(),accuracy(y_hat,y),y.numel())
return metric[0]/metric[2],metric[1]/metric[2]
Writer=SummaryWriter("logs")
#训练函数
def train_ch3(net,train_iter,test_iter,loss,num_epochs,updater):
for epoch in range(num_epochs):
train_metrics=train_epoch_ch3(net,train_iter,loss,updater)
test_acc=evaluate_accuracy(net,test_iter)
train_loss, train_acc = train_metrics
Writer.add_scalar("test_acc", test_acc, epoch)
Writer.add_scalar("train_acc", train_acc, epoch)
Writer.add_scalar("train_loss", train_loss, epoch)
train_loss,train_acc=train_metrics
Writer.close()
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
#初始化参数
net=nn.Sequential(nn.Flatten(),nn.Linear(784,10))
def init_weight(m):
if type(m)==nn.Linear:
nn.init.normal_(m.weight,std=0.01)
net.apply(init_weight)#初始化模型参数
loss=nn.CrossEntropyLoss(reduction='none')
#定义优化器
trainer=torch.optim.SGD(net.parameters(),lr=0.1)
#训练
num_epochs=10
train_ch3(net,train_iter,test_iter,loss,num_epochs,trainer)