直线拟合问题(Python实现)

程序如下:

import matplotlib.pyplot as plt
import numpy as np

x_list = [466, 741, 950, 1422, 1634]
y_list = [7.04, 4.28, 3.40, 2.54, 2.13]
# x_list = [0, 1, 3, 5]
# y_list = [1, 2, 4, 8]

l_mat11 = len(x_list)
l_mat12 = l_mat21 = sum(x for x in x_list)
l_mat22 = sum(x * x for x in x_list)

r_mat1 = sum(y for y in y_list)
r_mat2 = sum(x * y for x, y in zip(x_list, y_list))

l_mat = np.asmatrix([[l_mat11, l_mat12], [l_mat21, l_mat22]])
r_mat = np.asmatrix([[r_mat1], [r_mat2]])

ans_mat = np.dot(l_mat.I, r_mat)

a0 = float(ans_mat[0])
a1 = float(ans_mat[1])

plot_x_list = [x for x in x_list]
plot_y_list = [a0 + a1 * x for x in plot_x_list]
plt.plot(plot_x_list, plot_y_list, c='b')

for x, y in zip(x_list, y_list):
    plt.scatter(x, y, c='r')

plt.show()

 编程结果

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现多条直线拟合可以使用Python中的Scikit-learn库。具体步骤如下: 1. 导入所需库和数据 ```python from sklearn.linear_model import LinearRegression import numpy as np # 定义数据 X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) y = np.dot(X, np.array([1, 2])) + 3 ``` 2. 定义模型 ```python # 定义模型 model = LinearRegression() ``` 3. 拟合数据 ```python # 拟合数据 model.fit(X, y) ``` 4. 预测结果 ```python # 预测结果 model.predict(np.array([[3, 5]])) ``` 对于多条直线拟合,可以将数据集分成多个子集,每个子集拟合一条直线,然后将这些直线拼接起来形成一条完整的直线。具体实现可以按照以下步骤: 1. 将数据按照x轴坐标进行排序 ```python data = sorted(data, key=lambda x:x[0]) ``` 2. 将数据分成多个子集 ```python subsets = [] subset = [] for i in range(len(data)-1): subset.append(data[i]) if data[i+1][0] > data[i][0] + threshold: subsets.append(subset) subset = [] subsets.append(subset) ``` 其中,threshold是一个阈值,用于判断两个点是否属于同一子集。 3. 对每个子集进行拟合 ```python models = [] for subset in subsets: X = np.array([x[0] for x in subset]).reshape(-1, 1) y = np.array([x[1] for x in subset]).reshape(-1, 1) model = LinearRegression() model.fit(X, y) models.append(model) ``` 4. 将所有直线拼接起来形成一条完整的直线 ```python def predict(x): for model in models: if x < model.intercept_: return model.predict([[x]])[0][0] return models[-1].predict([[x]])[0][0] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值