import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
1.导入训练集数据
x = np.array([0.86, 0.96, 1.12, 1.35, 1.55, 1.63, 1.71, 1.78])
y = np.array([12, 15, 20, 35, 48, 51, 59, 66])
def fit(x,y):
if len(x) != len(y):
return
numerator = 0.0
denominator = 0.0
x_mean = np.mean(x)
y_mean = np.mean(y)
for i in range(len(x)):
numerator += (x[i]-x_mean)*(y[i]-y_mean)
denominator += np.square((x[i]-x_mean))
b0 = numerator / denominator
b1 = y_mean-b0*x_mean
return b0,b1
def predit(x,b0,b1):
return b0*x+b1
b0,b1 = fit(x,y)
- y = b0 * x + b1
- def fit() 函数来求b值

2.预测
x_test = np.array([0.75, 1.08, 1.26, 1.51, 1.6, 1.67, 1.85])
y_test = np.array([10, 17, 27, 41, 50, 64, 75])
y_predit = predit(x_test,b0,b1)
3.绘制图像
plt.plot(x, y, 'k.')
plt.plot(x_test, y_predit, 'g-')
yr = predit(x, b0, b1)
print(yr)
for idx, x in enumerate(x):
plt.plot([x, x], [y[idx], yr[idx]], 'r-')
plt.show()
