栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python实践-最小二乘拟合

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python实践-最小二乘拟合

实现对数据x=[ 2,0.2 ,0.02 ,0.002 ,0.0002 ,0.00002])
y=[3 , 4 , 6 , 7 , 9, 12 ]最小二乘拟合并预测。

代码如下:

import  numpy  as np
import matplotlib.pyplot as plt

# 核心代码,求斜率w,截距b:拟合直线方程为y=wx+b :这里x代表logx
def fit(data_x, data_y):
    m = len(data_y)
    x_bar = np.mean(data_x)
    sum_yx = 0
    sum_x2 = 0
    sum_delta = 0
    for i in range(m):
        x = data_x[i]
        y = data_y[i]
        sum_yx += y * (x - x_bar)
        sum_x2 += x ** 2
    # 根据公式计算w
    w = sum_yx / (sum_x2 - m * (x_bar ** 2))

    for i in range(m):
        x = data_x[i]
        y = data_y[i]
        sum_delta += (y - w * x)
    b = sum_delta / m
    return w, b

# 模拟数据
x_orgin = np.array([ 2,0.2 ,0.02 ,0.002 ,0.0002 ,0.00002])
y = np.array([3 , 4 , 6 , 7 , 9, 12 ])

#变型后的数据:x到logx
x=np.log10(x_orgin)

# 拟合方程并绘制
w, b = fit(x, y)
pred_y = w * x + b

#画图
#plt.axis([-11, 2 ,0 ,40])
plt.xlabel("log(x)")
plt.ylabel("y")
plt.scatter(x, y,label='orgin')
plt.plot(x, pred_y, c='r', label='line')
plt.title("y = {} + {}*x".format(b, w))
print("y = {} + {}*logx".format(b, w))
#plt.show()

for i in range(len(x)):
    plt.text(x[i],y[i],(x_orgin[i],y[i]),color='r')
plt.grid(True)
#预测

y1 = np.array([5,8, 10])
x1=10**((y1-b)/w)
plt.scatter(np.log10(x1), y1,label='priect')
np.set_printoptions(suppress=True)

for i in range(len(x1)):
    plt.text(np.log10(x1[i])-1,y1[i],(x1[i],y1[i]),color='r')
plt.legend()
plt.show()

 运行截图:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/307715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号