作业打卡
研究Rosenbrock函数,其定义为
f
=
(
x
1
?
a
)
2
+
(
x
2
?
x
1
2
)
2
f = (x_1-a)^{2} +(x_2-x_1^2)^2
f=(x1??a)2+(x2??x12?)2
问题一: a,b的选择会对函数的凹凸性会产生很大的变化,但是函数的大体形状不变。
问题二:求解最优解采用的最速下降法,初始点为(1,1).
import numpy as np
import matplotlib.pyplot as plt
def f(x1,x2,a,b):
return (a-x1)**2 + b*(x2-x1**2)**2
def GetGradient(prex,a,b):
x1 = prex[0]
x2 = prex[1]
return np.array([2*(x1-a)+4*b*x1*(x1**2-x2), 2*b*(x2-x1**2)])
def Getminpoint(x1,x2,a,b):
mu = 0.01
prex = np.array([x1,x2])
prey = f(prex[0],prex[1],a,b)
nowx = prex - mu*GetGradient(prex,a,b)
nowy = f(nowx[0],nowx[1],a,b)
epoch = 0
while (nowy-prey)< 0.001 :
prex = nowx
prey = nowy
nowx = prex - mu*GetGradient(prex,a,b)
nowy = f(nowx[0],nowx[1],a,b)
epoch += 1
if epoch > 20:
break
return (nowx,nowy)
for a in [0,4,8,12]:
for b in [-8,0,8,16]:
fig = plt.figure()
ax = plt.axes(projection='3d')
minxy,minz = Getminpoint(1,1,a,b)
ax.scatter(minxy[0],minxy[1],minz,c="red",zorder= 0,marker='o',s=100)
x = np.linspace(minxy[0]-12,minxy[0]+12,30)
y = np.linspace(minxy[1]-12,minxy[1]+12,30)
X, Y = np.meshgrid(x, y)
Z = f(X,Y,a,b)
ax.plot_surface(X, Y, Z, cmap='viridis',zorder= 1)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.view_init(60, 35)
plt.savefig(r"C:\Users\huangjianguo\Desktop\SelfStudy\ensemble-learning-main\CH1-机器学习的数学基础\CH1-机器学习的数学基础\阶段一作业\a=%f,b=%f.jpg"%(a,b))
print("%f,%f"%(a,b))
a=0,b=8
a=0,b=-8
|