带激活函数的梯度下降及线性回归算法和matlab代码-20170522.docx
文本预览下载声明
经典文档 下载后可编辑复制
带激活函数的梯度下降及线性回归和matlab代码
单变量线性回归带输入输出数据归一化处理
我们知道,对于输入数据进行归一化处理能极大地提高神经网络的学习速率,从而提高神经网络的收敛速度。对于同样的学习速率,未经过归一化数据处理的同样的数据集训练神经网络时,将会出现发散的现象,导致神经网络无法收敛。
神经网络的激活函数(比如Relu、Sigmoid函数)会导致神经网络的输出节点只能输出正值,无法输出负值。此时由于激活函数的输出值范围是正值,因此神经网络的期望输出值也是正值。万一当神经网络的训练数据集中包含负值时,可对输出数据集进行加一个最大负值的绝对值的操作,使得神经网络的期望输出值全部为正值。
如果神经网络的输出值的范围比较大,也可以对神经网络输出值进行归一化处理。
如果神经元包含激活函数,则激活函数会自动使得神经元的输出为非负值。
未进行输入数据归一化处理的代码
clear all
clc
% training sample data;
p0=3;
p1=7;
x=1:3;
y=p0+p1*x;
num_sample=size(y,2);
% gradient descending process
% initial values of parameters
theta0=1;
theta1=3;
%learning rate
alpha=0.33;
% if alpha is too large, the final error will be much large.
% if alpha is too small, the convergence will be slow
epoch=100;
for k=1:epoch
v_k=k
h_theta_x=theta0+theta1*x; % hypothesis function
Jcost(k)=((h_theta_x(1)-y(1))^2+(h_theta_x(2)-y(2))^2+(h_theta_x(3)-y(3))^2)/num_sample
theta0=theta0-alpha*((h_theta_x(1)-y(1))+(h_theta_x(2)-y(2))+(h_theta_x(3)-y(3)))/num_sample;
theta1=theta1-alpha*((h_theta_x(1)-y(1))*x(1)+(h_theta_x(2)-y(2))*x(2)+(h_theta_x(3)-y(3))*x(3))/num_sample;
end
plot(Jcost)
yn=theta0+theta1*x
上述未进行输入数据归一化处理的代码最大的学习速率为0.35,在迭代次数到达60次时,输出误差下降至0.0000。
进行输入数据归一化处理的代码
clear all
clc
% training sample data;
p0=3;
p1=7;
x=1:3;
x_mean=mean(x)
x_max=max(x)
x_min=min(x)
xn=(x-x_mean)/(x_max-x_min)
x=xn;
y=p0+p1*x
y=y+0.5;
num_sample=size(y,2);
% gradient descending process
% initial values of parameters
theta0=1;
theta1=3;
%learning rate
alpha=0.9;
% if alpha is too large, the final error will be much large.
% if alpha is too small, the convergence will be slow
epoch=100;
for k=1:epoch
v_k=k
h_theta_x=theta0+theta1*x; % hypothesis function
Jcost(k)=((h_theta_x(1)-y(1))^2+(h_theta_x(2)-y(2))^2+(h_theta_x(3)-y(3))^2)/num_sample
theta0=theta0-alpha*((h_theta_x(1)-y(1))+(h_theta_x(2)-y(2))+(h_theta_x(3)-y(3)))/num_sample;
theta1=theta1-alpha*((h_theta_x(1)-y(1))*x(1)+(h_theta_x(2)-y(2))*x(2)+(h_theta_x(3)-y(
显示全部