问题陈述:
我需要构造一个函数 f(x,y),其中有 3 个最小值。2个本地和1个全局,写在下面。
局部变量是:z = f(0.2,0.3) = 0.7 | z = f(0.6,0.8) = 0.8
全局为:z = f(0.85,0.5) = 0.6
到目前为止我尝试过的
我尝试过多项式回归来构建估计给定最小点的特征。但是,估计函数 z = f(x,y) 只是遍历所有给定的最小点,而不将它们视为最小值。我需要一种方法,通过它我可以构造一个具有上述 3 个最小值的函数。如果您能提供您的方法的代码片段,我会非常高兴。作为一种编程语言,我使用 Python。
代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
degree = 6
def func(x1, x2):
arr = []
for i in range(degree, 0, -1):
arr.append(x1 ** i)
for i in range(degree, 0, -1):
arr.append(x2 ** i)
arr.append(1)
return np.array(arr)
def der_func(x1, x2):
arr1 = []
arr2 = []
for i in range(degree - 1, -1, -1):
arr1.append((i + 1) * x1 ** i)
for i in range(degree + 1):
arr1.append(0)
for i in range(degree):
arr2.append(0)
for i in range(degree - 1, -1, -1):
arr2.append((i + 1) * x2 ** i)
arr2.append(0)
return np.array([arr1, arr2])
given_x = np.array([[0.2, 0.3],
[0.6, 0.8],
[0.85, 0.5]])
given_y = np.array([0.7, 0.8, 0.6])
data_x = []
data_y = []
for i in range(len(given_x)):
x1x2 = given_x[i]
data_x.append(func(x1x2[0], x1x2[1]))
data_y.append(given_y[i])
if i < 3: # in case there's more than 3 data point in given_x
data_x.append(der_func(x1x2[0], x1x2[1])[0])
data_y.append(0)
data_x.append(der_func(x1x2[0], x1x2[1])[1])
data_y.append(0)
data_x = np.array(data_x)
data_y = np.array(data_y)
w = np.linalg.inv(data_x.T @ data_x) @ data_x.T @ data_y
pred_y = data_x @ w
cost = np.mean((data_y - pred_y) ** 2)
print("Cost | ", cost)
#######################################
X = np.linspace(0, 1, 100)
Y = np.linspace(0, 1, 100)
X, Y = np.meshgrid(X, Y)
Z = np.zeros(np.shape(X))
for i in range(len(X)):
for j in range(len(X[0])):
Z[i, j] = np.array([func(X[i, j], Y[i, j])]) @ w
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.contour(X, Y, Z, 150)
ax.scatter(given_x[:3, 0], given_x[:3, 1], given_y[:3])
plt.show()


