# python数学方法实现一元线性拟合

代码如下:
(含部分注释)

import numpy as np
import matplotlib.pyplot as plt

#define data
x = np.array([0.5,1.0,1.5,2.0])
y = np.array([1.75,2.45,3.81,4.00])
plt.scatter(x,y)

#define needs in calculate
s1 = 0
s2 = 0
s3 = 0
s4 = 0
#len(x) 与 s 的个数要对应上,len(x) == 4 ,就应该有 4 个 s
n = 4

#最小二乘法公式()
for i in range(n):
    s1 = s1 + x[i]*y[i]
    s2 = s2 + x[i]
    s3 = s3 + y[i]
    s4 = s4 + x[i]*x[i]
#calculate coeff(斜率) and intercept(截距)
b = (s2*s3-n*s1) /  (s2*s2-s4*n)
a = (s3 - b*s2) / n
print("coeff:{} intercept:{}".format(b,a))

x = np.linspace(0,4,4)
y = b*x + a
plt.plot(x,y)
plt.show()

运行结果如下:
# python数学方法实现一元线性拟合_第1张图片

你可能感兴趣的:(机器学习入门)