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()

 运行截图:

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值