,可以通过以下步骤实现:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 定义数据集
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 6, 8])
# 定义最小二乘估计函数
def least_squares(x, y):
n = len(x)
sum_x = np.sum(x)
sum_y = np.sum(y)
sum_xy = np.sum(x * y)
sum_x2 = np.sum(x ** 2)
# 计算最小二乘估计的系数
a = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
b = (sum_y - a * sum_x) / n
return a, b
# 计算最小二乘估计的系数
a, b = least_squares(x, y)
# 定义绘制等高线图的函数
def plot_contour(a, b):
# 创建网格点
a_range = np.linspace(-10, 10, 100)
b_range = np.linspace(-10, 10, 100)
a_grid, b_grid = np.meshgrid(a_range, b_range)
# 计算误差平方和
error = np.sum((y - (a_grid * x + b_grid)) ** 2, axis=0)
# 绘制等高线图
plt.figure()
plt.contour(a_grid, b_grid, error, levels=20)
plt.xlabel('a')
plt.ylabel('b')
plt.title('Contour Plot of Least Squares Estimation')
plt.colorbar(label='Error')
plt.show()
# 调用绘制等高线图的函数
plot_contour(a, b)
这样就可以在matplotlib中绘制最小二乘估计函数的等高线图了。在图中,等高线的高度表示误差平方和,通过观察等高线的形状,可以了解最小二乘估计函数的拟合效果。
领取专属 10元无门槛券
手把手带您无忧上云