一、概述
搭建基于线性回归模型的神经网络,结合代码阐述搭建步骤,最后给出全部代码以及运行结果
二、搭建步骤
1、生成数据集
#生成数据集
num_input=3
num_examples=1000
features=torch.Tensor(np.random.normal(0,1,(num_input,num_examples)))
true_w=torch.Tensor([[3.4,-5,2.5]])
true_b=torch.Tensor([[4.2]])
labels=torch.mm(true_w,features)+true_b
2、在定义随机梯度下降法之前预先定义一个函数,实现随机挑选小批量训练数据集的过程
#筛选小批量数据集
def Data_Iter(Features,Labels,Batch_Size):
length=Features.shape[1]
index=list(range(length))
random.shuffle(index)
for i in range(0,length,Batch_Size):
j=torch.LongTensor(index[i:min(i+Batch_Size,length)])
yield Features[0,j],Features[1,j],Features[2,j],labels[0,j]
3、定义线性回归模型
#定义线性回归神经网络
def Linear_Regression(Weight,Bias,X):
return torch.mm(Weight,X)+Bias
4、定义损失函数
#定义损失函数
def Loss_Function(Y_hat,Y,Batch_Size):
return ((Y_hat-Y)**2).sum()/Batch_Size
5、定义随机梯度下降法
#定义随机梯度下降算法
def SGD(Params,lr):
for Param in Params:
Param.data-=lr*Param.grad
6、初始化训练参数
num_epoches=3
w=torch.tensor([[1,1,1]],dtype=torch.float32,requires_grad=True)
b=torch.tensor(np.array([1]),dtype=torch.float32,requires_grad=True)
lr=0.03
batch_size=10
7、开始训练
#开始训练
for epoch in range(num_epoches):
for x1,x2,x3,y in Data_Iter(features, labels, batch_size):
x=torch.stack([x1,x2,x3],dim=0)
y_hat=Linear_Regression(w,b,x)
#计算损失函数
L=Loss_Function(y_hat,y,batch_size)
#计算梯度
L.backward()
#更新权值及偏置
SGD([w,b],lr)
#梯度清零
w.grad.data.zero_()
b.grad.data.zero_()
train_l=Loss_Function(Linear_Regression(w,b,features),labels,num_examples)
print('epoch %d, loss %f' % (epoch+1,train_l))
#验证训练结果
print(w,'\n',b)
三、全部代码
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random
#生成数据集
num_input=3
num_examples=1000
features=torch.Tensor(np.random.normal(0,1,(num_input,num_examples)))
true_w=torch.Tensor([[3.4,-5,2.5]])
true_b=torch.Tensor([[4.2]])
labels=torch.mm(true_w,features)+true_b
#筛选小批量数据集
def Data_Iter(Features,Labels,Batch_Size):
length=Features.shape[1]
index=list(range(length))
random.shuffle(index)
for i in range(0,length,Batch_Size):
j=torch.LongTensor(index[i:min(i+Batch_Size,length)])
yield Features[0,j],Features[1,j],Features[2,j],labels[0,j]
#定义线性回归神经网络
def Linear_Regression(Weight,Bias,X):
return torch.mm(Weight,X)+Bias
#定义损失函数
def Loss_Function(Y_hat,Y,Batch_Size):
return ((Y_hat-Y)**2).sum()/Batch_Size
#定义随机梯度下降算法
def SGD(Params,lr):
for Param in Params:
Param.data-=lr*Param.grad
#初始化训练参数
num_epoches=3
w=torch.tensor([[1,1,1]],dtype=torch.float32,requires_grad=True)
b=torch.tensor(np.array([1]),dtype=torch.float32,requires_grad=True)
lr=0.03
batch_size=10
#开始训练
for epoch in range(num_epoches):
for x1,x2,x3,y in Data_Iter(features, labels, batch_size):
x=torch.stack([x1,x2,x3],dim=0)
y_hat=Linear_Regression(w,b,x)
#计算损失函数
L=Loss_Function(y_hat,y,batch_size)
#计算梯度
L.backward()
#更新权值及偏置
SGD([w,b],lr)
#梯度清零
w.grad.data.zero_()
b.grad.data.zero_()
train_l=Loss_Function(Linear_Regression(w,b,features),labels,num_examples)
print('epoch %d, loss %f' % (epoch+1,train_l))
print(w,'\n',b)