具体数学原理我就不写了,这里只大讲一下数学公式
g
r
a
d
∣
f
(
x
,
y
)
=
∂
f
∂
x
i
⃗
+
∂
f
∂
y
j
⃗
grad\mid{f(x,y)}=\frac{\partial f}{\partial x}\vec{i} +\frac{\partial f}{\partial y}\vec{j}
grad∣f(x,y)=∂x∂fi+∂y∂fj (二维)
g
r
a
d
∣
f
(
x
,
y
,
z
)
=
∂
f
∂
x
i
⃗
+
∂
f
∂
y
j
⃗
+
∂
f
∂
z
k
⃗
grad\mid{f(x,y,z)}=\frac{\partial f}{\partial x}\vec{i} +\frac{\partial f}{\partial y}\vec{j} +\frac{\partial f}{\partial z}\vec{k}
grad∣f(x,y,z)=∂x∂fi+∂y∂fj+∂z∂fk (三维)
最重要的是理解概念,因为以后出现更高维的就画不出来了。
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def Fun(x,y):
return x-y+2*x*x+2*x*y+y*y
def PxFun(x,y): #求偏导
return 1+4*x+2*y
def PyFun(x,y):
return -1+2*x+2*y
fig=plt.figure(dpi=400)
ax=Axes3D(fig)
X,Y=np.mgrid[-2:2:40j,-2:2:40j] #取样并做满射联合
Z=Fun(X,Y) #取样Z坐标打表
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap="rainbow")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
#梯度下降设置步长
step=0.0008
x=-2
y=-2
tag_x=[x]
tag_y=[y]
tag_z=[Fun(x,y)]
new_x=x
new_y=y
Over=False
while Over==False:
new_x-=step*PxFun(x,y)
new_y-=step*PyFun(x,y)
if Fun(x,y)-Fun(new_x,new_y)<7e-9:
Over=True
x=new_x
y=new_y
tag_x.append(x)
tag_y.append(y)
tag_z.append(Fun(x,y))
ax.plot(tag_x,tag_y,tag_z,'k')
plt.title('(x,y)~('+str(x)+","+str(y)+')')
plt.show()