实现对数据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()
运行截图: