homework-0306-最小二乘法

#问题1.实现一元线性回归
#使用如下提供的数据求解
x=[300,400,400,550,720,850,900,950]
y=[300,350,490,500,600,610,700,660]
import numpy as np
x_array = np.array(x)
y_array = np.array(y)
x_mean = np.mean(x_array)
y_mean = y_array.mean()
print(x_mean, y_mean)

a=((x_array-x_mean).dot(y_array-y_mean))/((x_array-x_mean)@(x_array-x_mean))
b=y_mean-a*x_mean
print(a,b)
633.75 526.25
0.530960991635149 189.75347155122432
#问题2.使用问题1实现的一元线性回归绘制一条直线,同时绘制上述的x,y散点图
import matplotlib.pyplot as plt
plt.plot(x,y, "ro") #plt.plot(x_array,y_array, "ro") 
m = np.linspace(0, 1000, 100)
plt.plot(m, a*m+b)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("linear regression")
plt.show()

你可能感兴趣的:(Python)