梯度下降求解二元函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


def f_2d(x, y):
return x ** 2 + 3 * x + y ** 2 + 8 * y + 1


def df_2d(x, y):
return 2 * x + 3, 2 * y + 8


x, y = 4, 4
learning_rate = 0.01

for itr in range(200):
v_x, v_y = df_2d(x, y)
x, y = x - learning_rate * v_x, y - learning_rate * v_y
print(x, y, f_2d(x, y))

x = np.linspace(-10, 10)
y = np.linspace(-10, 10)
X, Y = np.meshgrid(x, y)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, f_2d(X, Y))
plt.show()