大家好,我正在尝试绘制轮廓图,但是以非常奇怪的方式写在 x 轴上的 x 值与实际 x 值相差不大。我没有成功解决这个问题,想知道为什么会这样。我尝试以多种不同的方式更改 x 刻度,但没有成功,希望有人可以帮助我摆脱这种情况。谢谢!
`import numpy as np
import numdifftools as nd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def Function(x):
return np.cos(x[0])+np.sin(x[1])+(1/5)*x[0]**2+(1/4)*x[1]**2
def hw10GDstep(f,x0):
xold=x0[0]
yold=x0[1]
grad=nd.Gradient(Function)([xold,yold])
Xnew=xold-0.2*grad[0]
Ynew=yold-0.2*grad[1]
X,Y=np.meshgrid(Xnew,Ynew)
fval=f(X,Y)
fval=list(fval)
return ([Xnew,Ynew],fval[0][0])
def GradienDecent(f,x0):
numberofiter=0
xtol=10**-4
norm=100
xy=x0
listofalliter=[]
while(norm>xtol and numberofiter<1000):
numberofiter=numberofiter+1
step=hw10GDstep(f,xy)
xy=step[0]
fval=step[1]
templist=[xy,fval,numberofiter]
listofalliter.append(templist)
grad=nd.Gradient(Function)([xy[0],xy[1]])
norm=np.linalg.norm(grad)
return (listofalliter)
f=lambda x,y:np.cos(x)+np.sin(y)+(1/5)*x**2+(1/4)*y**2
xlist=np.linspace(-10,10,1000)
ylist=np.linspace(-10,10,1000)
X,Y=np.meshgrid(xlist,ylist)
Z=f(X,Y)
plt.contourf(X,Y,Z,cmap ="bone")
x0_1=[7,7]
x0_2=[-7,-7]
x0_3=[0,-7]
x1=GradienDecent(f,x0_1)
x0_1listofx=[]
x0_1listofy=[]
for i in range(0,len(x1)):
x0_1listofx.append(x1[i][0][0])
x0_1listofy.append(x1[i][0][1])
x1iter=x1[len(x1)-1][2]
x1xmin=x1[len(x1)-1][0][0]
x1ymin=x1[len(x1)-1][0][1]
x1zmin=x1[len(x1)-1][1]
xyz1=[x1xmin,x1ymin,x1zmin]
x2=GradienDecent(f,x0_2)
x0_2listofx=[]
x0_2listofy=[]
for i in range(0,len(x2)):
x0_2listofx.append(x2[i][0][0])
x0_2listofy.append(x2[i][0][1])
x2iter=x2[len(x2)-1][2]
x2xmin=x2[len(x2)-1][0][0]
x2ymin=x2[len(x2)-1][0][1]
x2zmin=x2[len(x2)-1][1]
xyz2=[x2xmin,x2ymin,x2zmin]
x3=GradienDecent(f,x0_3)
x0_3listofx=[]
x0_3listofy=[]
for i in range(0,len(x3)):
x0_3listofx.append(x3[i][0][0])
x0_3listofy.append(x3[i][0][1])
x3iter=x3[len(x3)-1][2]
x3xmin=x3[len(x3)-1][0][0]
x3ymin=x3[len(x3)-1][0][1]
x3zmin=x3[len(x3)-1][1]
xyz3=[x3xmin,x3ymin,x3zmin]
print("For Start Point Of [7,7] Made: "+str(x1iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz1))
print("For Start Point Of [-7,-7] Made: "+str(x2iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz2))
print("For Start Point Of [0,-7] Made: "+str(x3iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz3))
print("The End.")
plt.plot_date(x0_1listofx,x0_1listofy,color='green',markersize=2,label="For Start Point Of [7,7]")
plt.plot_date(x0_2listofx,x0_2listofy,color='blue',markersize=2,label="For Start Point Of [-7,-7]")
plt.plot_date(x0_3listofx,x0_3listofy,color='red',markersize=2,label="For Start Point Of [0,-7]")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Gradient Descent For F(x,y):")
plt.colorbar()
plt.legend()
plt.show()