最小二乘法
最小二乘法的拟合也是存在一定偏差的,需要通过R平方系数来判定,R平方在0-1之间,1为完全拟合。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
# 新的给定点
new_points = np.array([
[297, 243],
[349, 590],
[369, 914],
[382, 1270],
[280, 1707]
])
# 提取新的x和y
new_x = new_points[:, 0]
new_y = new_points[:, 1]
# 构建设计矩阵
A_new = np.vstack([new_x, np.ones(len(new_x))]).T
# 使用最小二乘法求解系数
a_new, b_new = np.linalg.lstsq(A_new, new_y, rcond=None)[0]
# 计算拟合的 y 值
y_fit = a_new * new_x + b_new
# 计算 R 平方
r_squared = r2_score(new_y, y_fit)
print(f'R^2 = {r_squared:.2f}')
# 打印拟合结果
print(f'拟合结果: y = {a_new:.2f}x + {b_new:.2f}')
# 创建画布
plt.figure(figsize=(10, 18)) # 根据画布比例调整图像尺寸比例
plt.scatter(new_x, new_y, color='blue', label='points', s=100)
plt.plot(new_x, a_new * new_x + b_new, 'r', label='line')
# 设置画布尺寸
plt.xlim(0, 1080)
plt.ylim(0, 1960)
# 标注轴标签和标题
plt.xlabel('x')
plt.ylabel('y')
plt.title(f'y = {a_new:.2f}x + {b_new:.2f} R^2 = {r_squared:.2f}')
# 添加网格和图例
plt.grid(True)
plt.legend()
plt.gca().invert_yaxis() # Invert y-axis to match typical screen coordinate system
# 显示图像
plt.show()
RANSAC算法
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import RANSACRegressor
from sklearn.linear_model import LinearRegression
# 给定点
new_points = np.array([
[297, 243],
[349, 590],
[369, 914],
[382, 1270],
[280, 1707]
])
# 分割x和y坐标
X = new_points[:, 0].reshape(-1, 1)
y = new_points[:, 1]
# 定义一个RANSAC回归模型
ransac = RANSACRegressor(LinearRegression(), max_trials=100, min_samples=2, residual_threshold=10, random_state=0)
ransac.fit(X, y)
# 预测线
line_X = np.arange(X.min(), X.max())[:, np.newaxis]
line_y_ransac = ransac.predict(line_X)
# 绘图
plt.figure(figsize=(10, 6))
plt.scatter(X, y, color='yellowgreen', marker='.', label='Data points')
plt.plot(line_X, line_y_ransac, color='cornflowerblue', linewidth=2, label='RANSAC fit line')
plt.legend()
plt.xlabel('X')
plt.ylabel('y')
plt.title('RANSAC regression')
plt.show()