lw优化算法
‘壹’ 关于遗传算法优化BP神经网络的问题
程序:
1、未经遗传算法优化的BP神经网络建模
clear;
clc;
%%%%%%%%%%%%%输入参数%%%%%%%%%%%%%%
N=2000; %数据总个数
M=1500; %训练数据
%%%%%%%%%%%%%训练数据%%%%%%%%%%%%%%
for i=1:N
input(i,1)=-5+rand*10;
input(i,2)=-5+rand*10;
end
output=input(:,1).^2+input(:,2).^2;
save data input output
load data.mat
%从1到N随机排序
k=rand(1,N);
[m,n]=sort(k);
%找出训练数据和预测数据
input_train=input(n(1:M),:)';
output_train=output(n(1:M),:)';
input_test=input(n((M+1):N),:)';
output_test=output(n((M+1):N),:)';
%数据归一化
[inputn,inputs]=mapminmax(input_train);
[outputn,outputs]=mapminmax(output_train);
%构建BP神经网络
net=newff(inputn,outputn,5);
net.trainParam.epochs=100;
net.trainParam.lr=0.1;
net.trainParam.goal=0.0000004;
%BP神经网络训练
net=train(net,inputn,outputn);
%测试样本归一化
inputn_test=mapminmax('apply',input_test,inputs);
%BP神经网络预测
an=sim(net,inputn_test);
%%网络得到数据反归一化
BPoutput=mapminmax('reverse',an,outputs);
figure(1)
%plot(BPoutput,':og');
scatter(1:(N-M),BPoutput,'rx');
hold on;
%plot(output_test,'-*');
scatter(1:(N-M),output_test,'o');
legend('预测输出','期望输出','fontsize',12);
title('BP网络预测输出','fontsize',12);
xlabel('样本','fontsize',12);
xlabel('优化前输出的误差','fontsize',12);
figure(2)
error=BPoutput-output_test;
plot(1:(N-M),error);
xlabel('样本','fontsize',12);
ylabel('优化前输出的误差','fontsize',12);
%save net net inputs outputs
2、遗传算法优化的BP神经网络建模
(1)主程序
%清空环境变量
clc
clear
%读取数据
load data.mat
%节点个数
inputnum=2;
hiddennum=5;
outputnum=1;
%训练数据和预测数据
input_train=input(1:1500,:)';
input_test=input(1501:2000,:)';
output_train=output(1:1500)';
output_test=output(1501:2000)';
%选连样本输入输出数据归一化
[inputn,inputps]=mapminmax(input_train);
[outputn,outputps]=mapminmax(output_train);
%构建网络
net=newff(inputn,outputn,hiddennum);
%% 遗传算法参数初始化
maxgen=10; %进化代数,即迭代次数
sizepop=30; %种群规模
pcross=[0.3]; %交叉概率选择,0和1之间
pmutation=[0.1]; %变异概率选择,0和1之间
%节点总数
numsum=inputnum*hiddennum+hiddennum+hiddennum*outputnum+outputnum;
lenchrom=ones(1,numsum);
bound=[-3*ones(numsum,1) 3*ones(numsum,1)]; %数据范围
%------------------------------------------------------种群初始化------------------------------%------------------
--------
indivials=struct('fitness',zeros(1,sizepop), 'chrom',[]); %将种群信息定义为一个结构体
%avgfitness=[]; %每一代种群的平均适应度
bestfitness=[]; %每一代种群的最佳适应度
bestchrom=[]; %适应度最好的染色体
%初始化种群
for i=1:sizepop
%随机产生一个种群
indivials.chrom(i,:)=Code(lenchrom,bound); %编码
x=indivials.chrom(i,:);
%计算适应度
indivials.fitness(i)=fun(x,inputnum,hiddennum,outputnum,net,inputn,outputn); %染色体的适应度
end
%找最好的染色体
[bestfitness bestindex]=min(indivials.fitness);
bestchrom=indivials.chrom(bestindex,:); %最好的染色体
%avgfitness=sum(indivials.fitness)/sizepop; %染色体的平均适应度
% 记录每一代进化中最好的适应度和平均适应度
%trace=[avgfitness bestfitness];
%% 迭代求解最佳初始阀值和权值
% 进化开始
for i=1:maxgen
i
% 选择
indivials=Select(indivials,sizepop);
% avgfitness=sum(indivials.fitness)/sizepop;
%交叉
indivials.chrom=Cross(pcross,lenchrom,indivials.chrom,sizepop,bound);
% 变异
indivials.chrom=Mutation(pmutation,lenchrom,indivials.chrom,sizepop,i,maxgen,bound);
% 计算适应度
for j=1:sizepop
x=indivials.chrom(j,:); %解码
indivials.fitness(j)=fun(x,inputnum,hiddennum,outputnum,net,inputn,outputn);
end
%找到最小和最大适应度的染色体及它们在种群中的位置
[newbestfitness,newbestindex]=min(indivials.fitness);
[worestfitness,worestindex]=max(indivials.fitness);
% 代替上一次进化中最好的染色体
if bestfitness>newbestfitness
bestfitness=newbestfitness;
bestchrom=indivials.chrom(newbestindex,:);
end
indivials.chrom(worestindex,:)=bestchrom;
indivials.fitness(worestindex)=bestfitness;
%avgfitness=sum(indivials.fitness)/sizepop;
% trace=[trace;avgfitness bestfitness]; %记录每一代进化中最好的适应度和平均适应度
end
%% 遗传算法结果分析
%figure(3)
%[r c]=size(trace);
%plot([1:r]',trace(:,2),'b--');
%title(['适应度曲线 ' '终止代数=' num2str(maxgen)]);
%xlabel('进化代数');ylabel('适应度');
%legend('平均适应度','最佳适应度');
disp('适应度 变量');
x=bestchrom;
%% 把最优初始阀值权值赋予网络预测
% %用遗传算法优化的BP网络进行值预测
w1=x(1:inputnum*hiddennum);
B1=x(inputnum*hiddennum+1:inputnum*hiddennum+hiddennum);
w2=x(inputnum*hiddennum+hiddennum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum);
B2=x
(inputnum*hiddennum+hiddennum+hiddennum*outputnum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum+outputnum);
net.iw{1,1}=reshape(w1,hiddennum,inputnum);
net.lw{2,1}=reshape(w2,outputnum,hiddennum);
net.b{1}=reshape(B1,hiddennum,1);
net.b{2}=B2;
%% BP网络训练
%网络进化参数
net.trainParam.epochs=100;
net.trainParam.lr=0.1;
%net.trainParam.goal=0.00001;
%网络训练
[net,per2]=train(net,inputn,outputn);
%% BP网络预测
%数据归一化
inputn_test=mapminmax('apply',input_test,inputps);
an=sim(net,inputn_test);
test_simu=mapminmax('reverse',an,outputps);
error=test_simu-output_test;
%figure(4);
hold on;plot(1:500,error,'r');
legend('优化前的误差','优化后的误差','fontsize',12)
(2)编码子程序code.m
function ret=Code(lenchrom,bound)
%本函数将变量编码成染色体,用于随机初始化一个种群
% lenchrom input : 染色体长度
% bound input : 变量的取值范围
% ret output: 染色体的编码值
flag=0;
while flag==0
pick=rand(1,length(lenchrom));
ret=bound(:,1)'+(bound(:,2)-bound(:,1))'.*pick; %线性插值,编码结果以实数向量存入ret中
flag=test(lenchrom,bound,ret); %检验染色体的可行性
end
(3)适应度函数fun.m
function error = fun(x,inputnum,hiddennum,outputnum,net,inputn,outputn)
%该函数用来计算适应度值
%x input 个体
%inputnum input 输入层节点数
%outputnum input 隐含层节点数
%net input 网络
%inputn input 训练输入数据
%outputn input 训练输出数据
%error output 个体适应度值
%提取
w1=x(1:inputnum*hiddennum);
B1=x(inputnum*hiddennum+1:inputnum*hiddennum+hiddennum);
w2=x(inputnum*hiddennum+hiddennum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum);
B2=x(inputnum*hiddennum+hiddennum+hiddennum*outputnum+1:inputnum*hiddennum+hiddennum+hiddennum*outputnum+outputnum);
net=newff(inputn,outputn,hiddennum);
%网络进化参数
net.trainParam.epochs=20;
net.trainParam.lr=0.1;
net.trainParam.goal=0.00001;
net.trainParam.show=100;
net.trainParam.showWindow=0;
%网络权值赋值
net.iw{1,1}=reshape(w1,hiddennum,inputnum);
net.lw{2,1}=reshape(w2,outputnum,hiddennum);
net.b{1}=reshape(B1,hiddennum,1);
net.b{2}=B2;
%网络训练
net=train(net,inputn,outputn);
an=sim(net,inputn);
error=sum(abs(an-outputn));
(4)选择操作Select.m
function ret=select(indivials,sizepop)
% 该函数用于进行选择操作
% indivials input 种群信息
% sizepop input 种群规模
% ret output 选择后的新种群
%求适应度值倒数
[a bestch]=min(indivials.fitness);
%b=indivials.chrom(bestch);
%c=indivials.fitness(bestch);
fitness1=10./indivials.fitness; %indivials.fitness为个体适应度值
%个体选择概率
sumfitness=sum(fitness1);
sumf=fitness1./sumfitness;
%采用轮盘赌法选择新个体
index=[];
for i=1:sizepop %sizepop为种群数
pick=rand;
while pick==0
pick=rand;
end
for i=1:sizepop
pick=pick-sumf(i);
if pick<0
index=[index i];
break;
end
end
end
%index=[index bestch];
%新种群
indivials.chrom=indivials.chrom(index,:); %indivials.chrom为种群中个体
indivials.fitness=indivials.fitness(index);
%indivials.chrom=[indivials.chrom;b];
%indivials.fitness=[indivials.fitness;c];
ret=indivials;
(5)交叉操作cross.m
function ret=Cross(pcross,lenchrom,chrom,sizepop,bound)
%本函数完成交叉操作
% pcorss input : 交叉概率
% lenchrom input : 染色体的长度
% chrom input : 染色体群
% sizepop input : 种群规模
% ret output : 交叉后的染色体
for i=1:sizepop %每一轮for循环中,可能会进行一次交叉操作,染色体是随机选择的,交叉位置也是随机选择的,%但该轮for循环中是否进行交叉操作则由交叉概率决定(continue控制)
% 随机选择两个染色体进行交叉
pick=rand(1,2);
while prod(pick)==0
pick=rand(1,2);
end
index=ceil(pick.*sizepop);
% 交叉概率决定是否进行交叉
pick=rand;
while pick==0
pick=rand;
end
if pick>pcross
continue;
end
flag=0;
while flag==0
% 随机选择交叉位
pick=rand;
while pick==0
pick=rand;
end
pos=ceil(pick.*sum(lenchrom)); %随机选择进行交叉的位置,即选择第几个变量进行交叉,注意:两个染色体交叉的位置相同
pick=rand; %交叉开始
v1=chrom(index(1),pos);
v2=chrom(index(2),pos);
chrom(index(1),pos)=pick*v2+(1-pick)*v1;
chrom(index(2),pos)=pick*v1+(1-pick)*v2; %交叉结束
flag1=test(lenchrom,bound,chrom(index(1),:)); %检验染色体1的可行性
flag2=test(lenchrom,bound,chrom(index(2),:)); %检验染色体2的可行性
if flag1*flag2==0
flag=0;
else flag=1;
end %如果两个染色体不是都可行,则重新交叉
end
end
ret=chrom;
(6)变异操作Mutation.m
function ret=Mutation(pmutation,lenchrom,chrom,sizepop,num,maxgen,bound)
% 本函数完成变异操作
% pcorss input : 变异概率
% lenchrom input : 染色体长度
% chrom input : 染色体群
% sizepop input : 种群规模
% opts input : 变异方法的选择
% pop input : 当前种群的进化代数和最大的进化代数信息
% bound input : 每个个体的上届和下届
% maxgen input :最大迭代次数
% num input : 当前迭代次数
% ret output : 变异后的染色体
for i=1:sizepop %每一轮for循环中,可能会进行一次变异操作,染色体是随机选择的,变异位置也是随机选择的,
%但该轮for循环中是否进行变异操作则由变异概率决定(continue控制)
% 随机选择一个染色体进行变异
pick=rand;
while pick==0
pick=rand;
end
index=ceil(pick*sizepop);
% 变异概率决定该轮循环是否进行变异
pick=rand;
if pick>pmutation
continue;
end
flag=0;
while flag==0
% 变异位置
pick=rand;
while pick==0
pick=rand;
end
pos=ceil(pick*sum(lenchrom)); %随机选择了染色体变异的位置,即选择了第pos个变量进行变异
pick=rand; %变异开始
fg=(rand*(1-num/maxgen))^2;
if pick>0.5
chrom(i,pos)=chrom(i,pos)+(bound(pos,2)-chrom(i,pos))*fg;
else
chrom(i,pos)=chrom(i,pos)-(chrom(i,pos)-bound(pos,1))*fg;
end %变异结束
flag=test(lenchrom,bound,chrom(i,:)); %检验染色体的可行性
end
end
ret=chrom;
‘贰’ 关于神经网络LM训练算法的一些问题
1.初始权值不一样,如果一样,每次训练结果是相同的 2.是 3.在train之前修改权值,IW,LW,b,使之相同 4.取多次实验的均值 一点浅见,仅供参考
‘叁’ python怎么做最优化
最优化
为什么要做最优化呢?因为在生活中,人们总是希望幸福值或其它达到一个极值,比如做生意时希望成本最小,收入最大,所以在很多商业情境中,都会遇到求极值的情况。
函数求根
这里“函数的根”也称“方程的根”,或“函数的零点”。
先把我们需要的包加载进来。import numpy as npimport scipy as spimport scipy.optimize as optimport matplotlib.pyplot as plt%matplotlib inline
函数求根和最优化的关系?什么时候函数是最小值或最大值?
两个问题一起回答:最优化就是求函数的最小值或最大值,同时也是极值,在求一个函数最小值或最大值时,它所在的位置肯定是导数为 0 的位置,所以要求一个函数的极值,必然要先求导,使其为 0,所以函数求根就是为了得到最大值最小值。
scipy.optimize 有什么方法可以求根?
可以用 scipy.optimize 中的 bisect 或 brentq 求根。f = lambda x: np.cos(x) - x # 定义一个匿名函数x = np.linspace(-5, 5, 1000) # 先生成 1000 个 xy = f(x) # 对应生成 1000 个 f(x)plt.plot(x, y); # 看一下这个函数长什么样子plt.axhline(0, color='k'); # 画一根横线,位置在 y=0
opt.bisect(f, -5, 5) # 求取函数的根0.7390851332155535plt.plot(x, y)plt.axhline(0, color='k')plt.scatter([_], [0], c='r', s=100); # 这里的 [_] 表示上一个 Cell 中的结果,这里是 x 轴上的位置,0 是 y 上的位置
求根有两种方法,除了上面介绍的 bisect,还有 brentq,后者比前者快很多。%timeit opt.bisect(f, -5, 5)%timeit opt.brentq(f, -5, 5)10000 loops, best of 3: 157 s per loopThe slowest run took 11.65 times longer than the fastest. This could mean that an intermediate result is being cached.10000 loops, best of 3: 35.9 s per loop
函数求最小化
求最小值就是一个最优化问题。求最大值时只需对函数做一个转换,比如加一个负号,或者取倒数,就可转成求最小值问题。所以两者是同一问题。
初始值对最优化的影响是什么?
举例来说,先定义个函数。f = lambda x: 1-np.sin(x)/xx = np.linspace(-20., 20., 1000)y = f(x)
当初始值为 3 值,使用 minimize 函数找到最小值。minimize 函数是在新版的 scipy 里,取代了以前的很多最优化函数,是个通用的接口,背后是很多方法在支撑。x0 = 3xmin = opt.minimize(f, x0).x # x0 是起始点,起始点最好离真正的最小值点不要太远plt.plot(x, y)plt.scatter(x0, f(x0), marker='o', s=300); # 起始点画出来,用圆圈表示plt.scatter(xmin, f(xmin), marker='v', s=300); # 最小值点画出来,用三角表示plt.xlim(-20, 20);
初始值为 3 时,成功找到最小值。
现在来看看初始值为 10 时,找到的最小值点。x0 = 10xmin = opt.minimize(f, x0).xplt.plot(x, y)plt.scatter(x0, f(x0), marker='o', s=300)plt.scatter(xmin, f(xmin), marker='v', s=300)plt.xlim(-20, 20);
由上图可见,当初始值为 10 时,函数找到的是局部最小值点,可见 minimize 的默认算法对起始点的依赖性。
那么怎么才能不管初始值在哪个位置,都能找到全局最小值点呢?
如何找到全局最优点?
可以使用 basinhopping 函数找到全局最优点,相关背后算法,可以看帮助文件,有提供论文的索引和出处。
我们设初始值为 10 看是否能找到全局最小值点。x0 = 10from scipy.optimize import basinhoppingxmin = basinhopping(f,x0,stepsize = 5).xplt.plot(x, y);plt.scatter(x0, f(x0), marker='o', s=300);plt.scatter(xmin, f(xmin), marker='v', s=300);plt.xlim(-20, 20);
当起始点在比较远的位置,依然成功找到了全局最小值点。
如何求多元函数最小值?
以二元函数为例,使用 minimize 求对应的最小值。def g(X): x,y = X return (x-1)**4 + 5 * (y-1)**2 - 2*x*yX_opt = opt.minimize(g, (8, 3)).x # (8,3) 是起始点print X_opt[ 1.88292611 1.37658521]fig, ax = plt.subplots(figsize=(6, 4)) # 定义画布和图形x_ = y_ = np.linspace(-1, 4, 100)X, Y = np.meshgrid(x_, y_)c = ax.contour(X, Y, g((X, Y)), 50) # 等高线图ax.plot(X_opt[0], X_opt[1], 'r*', markersize=15) # 最小点的位置是个元组ax.set_xlabel(r"$x_1$", fontsize=18)ax.set_ylabel(r"$x_2$", fontsize=18)plt.colorbar(c, ax=ax) # colorbar 表示颜色越深,高度越高fig.tight_layout()
画3D 图。from mpl_toolkits.mplot3d import Axes3Dfrom matplotlib import cmfig = plt.figure()ax = fig.gca(projection='3d')x_ = y_ = np.linspace(-1, 4, 100)X, Y = np.meshgrid(x_, y_)surf = ax.plot_surface(X, Y, g((X,Y)), rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)cset = ax.contour(X, Y, g((X,Y)), zdir='z',offset=-5, cmap=cm.coolwarm)fig.colorbar(surf, shrink=0.5, aspect=5);
曲线拟合
曲线拟合和最优化有什么关系?
曲线拟合的问题是,给定一组数据,它可能是沿着一条线散布的,这时要找到一条最优的曲线来拟合这些数据,也就是要找到最好的线来代表这些点,这里的最优是指这些点和线之间的距离是最小的,这就是为什么要用最优化问题来解决曲线拟合问题。
举例说明,给一些点,找到一条线,来拟合这些点。
先给定一些点:N = 50 # 点的个数m_true = 2 # 斜率b_true = -1 # 截距dy = 2.0 # 误差np.random.seed(0)xdata = 10 * np.random.random(N) # 50 个 x,服从均匀分布ydata = np.random.normal(b_true + m_true * xdata, dy) # dy 是标准差plt.errorbar(xdata, ydata, dy, fmt='.k', ecolor='lightgray');
上面的点整体上呈现一个线性关系,要找到一条斜线来代表这些点,这就是经典的一元线性回归。目标就是找到最好的线,使点和线的距离最短。要优化的函数是点和线之间的距离,使其最小。点是确定的,而线是可变的,线是由参数值,斜率和截距决定的,这里就是要通过优化距离找到最优的斜率和截距。
点和线的距离定义如下:def chi2(theta, x, y): return np.sum(((y - theta[0] - theta[1] * x)) ** 2)
上式就是误差平方和。
误差平方和是什么?有什么作用?
误差平方和公式为:
误差平方和大,表示真实的点和预测的线之间距离太远,说明拟合得不好,最好的线,应该是使误差平方和最小,即最优的拟合线,这里是条直线。
误差平方和就是要最小化的目标函数。
找到最优的函数,即斜率和截距。theta_guess = [0, 1] # 初始值theta_best = opt.minimize(chi2, theta_guess, args=(xdata, ydata)).xprint(theta_best)[-1.01442005 1.93854656]
上面两个输出即是预测的直线斜率和截距,我们是根据点来反推直线的斜率和截距,那么真实的斜率和截距是多少呢?-1 和 2,很接近了,差的一点是因为有噪音的引入。xfit = np.linspace(0, 10)yfit = theta_best[0] + theta_best[1] * xfitplt.errorbar(xdata, ydata, dy, fmt='.k', ecolor='lightgray');plt.plot(xfit, yfit, '-k');
最小二乘(Least Square)是什么?
上面用的是 minimize 方法,这个问题的目标函数是误差平方和,这就又有一个特定的解法,即最小二乘。
最小二乘的思想就是要使得观测点和估计点的距离的平方和达到最小,这里的“二乘”指的是用平方来度量观测点与估计点的远近(在古汉语中“平方”称为“二乘”),“最小”指的是参数的估计值要保证各个观测点与估计点的距离的平方和达到最小。
关于最小二乘估计的计算,涉及更多的数学知识,这里不想详述,其一般的过程是用目标函数对各参数求偏导数,并令其等于 0,得到一个线性方程组。具体推导过程可参考斯坦福机器学习讲义 第 7 页。def deviations(theta, x, y): return (y - theta[0] - theta[1] * x)theta_best, ier = opt.leastsq(deviations, theta_guess, args=(xdata, ydata))print(theta_best)[-1.01442016 1.93854659]
最小二乘 leastsq 的结果跟 minimize 结果一样。注意 leastsq 的第一个参数不再是误差平方和 chi2,而是误差本身 deviations,即没有平方,也没有和。yfit = theta_best[0] + theta_best[1] * xfitplt.errorbar(xdata, ydata, dy, fmt='.k', ecolor='lightgray');plt.plot(xfit, yfit, '-k');
非线性最小二乘
上面是给一些点,拟合一条直线,拟合一条曲线也是一样的。def f(x, beta0, beta1, beta2): # 首先定义一个非线性函数,有 3 个参数 return beta0 + beta1 * np.exp(-beta2 * x**2)beta = (0.25, 0.75, 0.5) # 先猜 3 个 betaxdata = np.linspace(0, 5, 50)y = f(xdata, *beta)ydata = y + 0.05 * np.random.randn(len(xdata)) # 给 y 加噪音def g(beta): return ydata - f(xdata, *beta) # 真实 y 和 预测值的差,求最优曲线时要用到beta_start = (1, 1, 1)beta_opt, beta_cov = opt.leastsq(g, beta_start)print beta_opt # 求到的 3 个最优的 beta 值[ 0.25525709 0.74270226 0.54966466]
拿估计的 beta_opt 值跟真实的 beta = (0.25, 0.75, 0.5) 值比较,差不多。fig, ax = plt.subplots()ax.scatter(xdata, ydata) # 画点ax.plot(xdata, y, 'r', lw=2) # 真实值的线ax.plot(xdata, f(xdata, *beta_opt), 'b', lw=2) # 拟合的线ax.set_xlim(0, 5)ax.set_xlabel(r"$x$", fontsize=18)ax.set_ylabel(r"$f(x, \beta)$", fontsize=18)fig.tight_layout()
除了使用最小二乘,还可以使用曲线拟合的方法,得到的结果是一样的。beta_opt, beta_cov = opt.curve_fit(f, xdata, ydata)print beta_opt[ 0.25525709 0.74270226 0.54966466]
有约束的最小化
有约束的最小化是指,要求函数最小化之外,还要满足约束条件,举例说明。
边界约束def f(X): x, y = X return (x-1)**2 + (y-1)**2 # 这是一个碗状的函数x_opt = opt.minimize(f, (0, 0), method='BFGS').x # 无约束最优化
假设有约束条件,x 和 y 要在一定的范围内,如 x 在 2 到 3 之间,y 在 0 和 2 之间。bnd_x1, bnd_x2 = (2, 3), (0, 2) # 对自变量的约束x_cons_opt = opt.minimize(f, np.array([0, 0]), method='L-BFGS-B', bounds=[bnd_x1, bnd_x2]).x # bounds 矩形约束fig, ax = plt.subplots(figsize=(6, 4))x_ = y_ = np.linspace(-1, 3, 100)X, Y = np.meshgrid(x_, y_)c = ax.contour(X, Y, f((X,Y)), 50)ax.plot(x_opt[0], x_opt[1], 'b*', markersize=15) # 没有约束下的最小值,蓝色五角星ax.plot(x_cons_opt[0], x_cons_opt[1], 'r*', markersize=15) # 有约束下的最小值,红色星星bound_rect = plt.Rectangle((bnd_x1[0], bnd_x2[0]), bnd_x1[1] - bnd_x1[0], bnd_x2[1] - bnd_x2[0], facecolor="grey")ax.add_patch(bound_rect)ax.set_xlabel(r"$x_1$", fontsize=18)ax.set_ylabel(r"$x_2$", fontsize=18)plt.colorbar(c, ax=ax)fig.tight_layout()
不等式约束
介绍下相关理论,先来看下存在等式约束的极值问题求法,比如下面的优化问题。
目标函数是 f(w),下面是等式约束,通常解法是引入拉格朗日算子,这里使用 ββ 来表示算子,得到拉格朗日公式为
l 是等式约束的个数。
然后分别对 w 和ββ 求偏导,使得偏导数等于 0,然后解出 w 和βiβi,至于为什么引入拉格朗日算子可以求出极值,原因是 f(w) 的 dw 变化方向受其他不等式的约束,dw的变化方向与f(w)的梯度垂直时才能获得极值,而且在极值处,f(w) 的梯度与其他等式梯度的线性组合平行,因此他们之间存在线性关系。(参考《最优化与KKT条件》)
对于不等式约束的极值问题
常常利用拉格朗日对偶性将原始问题转换为对偶问题,通过解对偶问题而得到原始问题的解。该方法应用在许多统计学习方法中。有兴趣的可以参阅相关资料,这里不再赘述。def f(X): return (X[0] - 1)**2 + (X[1] - 1)**2def g(X): return X[1] - 1.75 - (X[0] - 0.75)**4x_opt = opt.minimize(f, (0, 0), method='BFGS').xconstraints = [dict(type='ineq', fun=g)] # 约束采用字典定义,约束方式为不等式约束,边界用 g 表示x_cons_opt = opt.minimize(f, (0, 0), method='SLSQP', constraints=constraints).xfig, ax = plt.subplots(figsize=(6, 4))x_ = y_ = np.linspace(-1, 3, 100)X, Y = np.meshgrid(x_, y_)c = ax.contour(X, Y, f((X, Y)), 50)ax.plot(x_opt[0], x_opt[1], 'b*', markersize=15) # 蓝色星星,没有约束下的最小值ax.plot(x_, 1.75 + (x_-0.75)**4, '', markersize=15)ax.fill_between(x_, 1.75 + (x_-0.75)**4, 3, color="grey")ax.plot(x_cons_opt[0], x_cons_opt[1], 'r*', markersize=15) # 在区域约束下的最小值ax.set_ylim(-1, 3)ax.set_xlabel(r"$x_0$", fontsize=18)ax.set_ylabel(r"$x_1$", fontsize=18)plt.colorbar(c, ax=ax)fig.tight_layout()
scipy.optimize.minimize 中包括了多种最优化算法,每种算法使用范围不同,详细参考官方文档。
‘肆’ python数据分析与应用第三章代码3-5的数据哪来的
savetxt
import numpy as np
i2 = np.eye(2)
np.savetxt("eye.txt", i2)
3.4 读入CSV文件
# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800
c,v=np.loadtxt('data.csv', delimiter=',', usecols=(6,7), unpack=True) #index从0开始
3.6.1 算术平均值
np.mean(c) = np.average(c)
3.6.2 加权平均值
t = np.arange(len(c))
np.average(c, weights=t)
3.8 极值
np.min(c)
np.max(c)
np.ptp(c) 最大值与最小值的差值
3.10 统计分析
np.median(c) 中位数
np.msort(c) 升序排序
np.var(c) 方差
3.12 分析股票收益率
np.diff(c) 可以返回一个由相邻数组元素的差
值构成的数组
returns = np.diff( arr ) / arr[ : -1] #diff返回的数组比收盘价数组少一个元素
np.std(c) 标准差
对数收益率
logreturns = np.diff( np.log(c) ) #应检查输入数组以确保其不含有零和负数
where 可以根据指定的条件返回所有满足条件的数
组元素的索引值。
posretindices = np.where(returns > 0)
np.sqrt(1./252.) 平方根,浮点数
3.14 分析日期数据
# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800
dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6), converters={1:datestr2num}, unpack=True)
print "Dates =", dates
def datestr2num(s):
return datetime.datetime.strptime(s, "%d-%m-%Y").date().weekday()
# 星期一 0
# 星期二 1
# 星期三 2
# 星期四 3
# 星期五 4
# 星期六 5
# 星期日 6
#output
Dates = [ 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 1. 2. 4. 0. 1. 2. 3. 4. 0.
1. 2. 3. 4.]
averages = np.zeros(5)
for i in range(5):
indices = np.where(dates == i)
prices = np.take(close, indices) #按数组的元素运算,产生一个数组作为输出。
>>>a = [4, 3, 5, 7, 6, 8]
>>>indices = [0, 1, 4]
>>>np.take(a, indices)
array([4, 3, 6])
np.argmax(c) #返回的是数组中最大元素的索引值
np.argmin(c)
3.16 汇总数据
# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800
#得到第一个星期一和最后一个星期五
first_monday = np.ravel(np.where(dates == 0))[0]
last_friday = np.ravel(np.where(dates == 4))[-1]
#创建一个数组,用于存储三周内每一天的索引值
weeks_indices = np.arange(first_monday, last_friday + 1)
#按照每个子数组5个元素,用split函数切分数组
weeks_indices = np.split(weeks_indices, 5)
#output
[array([1, 2, 3, 4, 5]), array([ 6, 7, 8, 9, 10]), array([11,12, 13, 14, 15])]
weeksummary = np.apply_along_axis(summarize, 1, weeks_indices,open, high, low, close)
def summarize(a, o, h, l, c): #open, high, low, close
monday_open = o[a[0]]
week_high = np.max( np.take(h, a) )
week_low = np.min( np.take(l, a) )
friday_close = c[a[-1]]
return("APPL", monday_open, week_high, week_low, friday_close)
np.savetxt("weeksummary.csv", weeksummary, delimiter=",", fmt="%s") #指定了文件名、需要保存的数组名、分隔符(在这个例子中为英文标点逗号)以及存储浮点数的格式。
.png
格式字符串以一个百分号开始。接下来是一个可选的标志字符:-表示结果左对齐,0表示左端补0,+表示输出符号(正号+或负号-)。第三部分为可选的输出宽度参数,表示输出的最小位数。第四部分是精度格式符,以”.”开头,后面跟一个表示精度的整数。最后是一个类型指定字符,在例子中指定为字符串类型。
numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)
>>>def my_func(a):
... """Average first and last element of a 1-D array"""
... return (a[0] + a[-1]) * 0.5
>>>b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>>np.apply_along_axis(my_func, 0, b) #沿着X轴运动,取列切片
array([ 4., 5., 6.])
>>>np.apply_along_axis(my_func, 1, b) #沿着y轴运动,取行切片
array([ 2., 5., 8.])
>>>b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>>np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
[3, 4, 9],
[2, 5, 6]])
3.20 计算简单移动平均线
(1) 使用ones函数创建一个长度为N的元素均初始化为1的数组,然后对整个数组除以N,即可得到权重。如下所示:
N = int(sys.argv[1])
weights = np.ones(N) / N
print "Weights", weights
在N = 5时,输出结果如下:
Weights [ 0.2 0.2 0.2 0.2 0.2] #权重相等
(2) 使用这些权重值,调用convolve函数:
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)
sma = np.convolve(weights, c)[N-1:-N+1] #卷积是分析数学中一种重要的运算,定义为一个函数与经过翻转和平移的另一个函数的乘积的积分。
t = np.arange(N - 1, len(c)) #作图
plot(t, c[N-1:], lw=1.0)
plot(t, sma, lw=2.0)
show()
3.22 计算指数移动平均线
指数移动平均线(exponential moving average)。指数移动平均线使用的权重是指数衰减的。对历史上的数据点赋予的权重以指数速度减小,但永远不会到达0。
x = np.arange(5)
print "Exp", np.exp(x)
#output
Exp [ 1. 2.71828183 7.3890561 20.08553692 54.59815003]
Linspace 返回一个元素值在指定的范围内均匀分布的数组。
print "Linspace", np.linspace(-1, 0, 5) #起始值、终止值、可选的元素个数
#output
Linspace [-1. -0.75 -0.5 -0.25 0. ]
(1)权重计算
N = int(sys.argv[1])
weights = np.exp(np.linspace(-1. , 0. , N))
(2)权重归一化处理
weights /= weights.sum()
print "Weights", weights
#output
Weights [ 0.11405072 0.14644403 0.18803785 0.24144538 0.31002201]
(3)计算及作图
c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)
ema = np.convolve(weights, c)[N-1:-N+1]
t = np.arange(N - 1, len(c))
plot(t, c[N-1:], lw=1.0)
plot(t, ema, lw=2.0)
show()
3.26 用线性模型预测价格
(x, resials, rank, s) = np.linalg.lstsq(A, b) #系数向量x、一个残差数组、A的秩以及A的奇异值
print x, resials, rank, s
#计算下一个预测值
print np.dot(b, x)
3.28 绘制趋势线
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2], [3, 4, 5]])
>>> np.ones_like(x) #用1填充数组
array([[1, 1, 1], [1, 1, 1]])
类似函数
zeros_like
empty_like
zeros
ones
empty
3.30 数组的修剪和压缩
a = np.arange(5)
print "a =", a
print "Clipped", a.clip(1, 2) #将所有比给定最大值还大的元素全部设为给定的最大值,而所有比给定最小值还小的元素全部设为给定的最小值
#output
a = [0 1 2 3 4]
Clipped [1 1 2 2 2]
a = np.arange(4)
print a
print "Compressed", a.compress(a > 2) #返回一个根据给定条件筛选后的数组
#output
[0 1 2 3]
Compressed [3]
b = np.arange(1, 9)
print "b =", b
print "Factorial", b.prod() #输出数组元素阶乘结果
#output
b = [1 2 3 4 5 6 7 8]
Factorial 40320
print "Factorials", b.cumprod()
#output