最小二乘求解线性回归参数


import numpy as np
#假设X,Y服从 Y = b * X + a 线性关系
X = np.array([1.779817,3.553517, 7.051988, 14.296636])  #光学变焦倍数
Y = np.array([12.2, 24.3, 48.1, 97.6])					#焦距


# 最小二乘估计
x_ = np.mean(X)
y_ = np.mean(Y)
S_xy = np.sum((X - x_) * (Y - y_))
S_xx = np.sum((X - x_)**2)

pre_b = S_xy / S_xx
pre_a = y_ - x_ * pre_b

print(pre_b, pre_a)

# y = b * x + a
import matplotlib.pyplot as plt

pre_y = pre_b * X + pre_a
plt.plot(X, Y, 's')
plt.plot(X,pre_y, 'k-')
plt.show()

你可能感兴趣的:(python,ML,线性回归,python,numpy)