建立一个预测模型,根据输入的特征,输出预测值。
import matplotlib.pyplot as plt
import numpy as np
data = np.array(
[
[80,200],
[95,230],
[104,245],
[112,247],
[125,259],
[135,262]
]
)
X = data[:,0]
Y = data[:,1]
plt.scatter(X,Y,c = "red")
plt.show()
import itertools
# 类型强制转换
com_list = list(itertools.combinations(data,2))
print(com_list)
print(len(com_list))
print(com_list[0])
[(array([ 80, 200]), array([ 95, 230])), (array([ 80, 200]), array([104, 245])), (array([ 80, 200]), array([112, 247])), (array([ 80, 200]), array([125, 259])), (array([ 80, 200]), array([135, 262])), (array([ 95, 230]), array([104, 245])), (array([ 95, 230]), array([112, 247])), (array([ 95, 230]), array([125, 259])), (array([ 95, 230]), array([135, 262])), (array([104, 245]), array([112, 247])), (array([104, 245]), array([125, 259])), (array([104, 245]), array([135, 262])), (array([112, 247]), array([125, 259])), (array([112, 247]), array([135, 262])), (array([125, 259]), array([135, 262]))]
15
(array([ 80, 200]), array([ 95, 230]))
ms = []
bs = []
for comlist in com_list:
x1,y1 = comlist[0]
x2,y2 = comlist[1]
m = (y2-y1)/(x2-x1);
b = y1 - m * x1;
ms.append(m)
bs.append(b)
print(ms)
print(bs)
#均值
m,b = np.mean(ms),np.mean(bs)
print(m,b)
x = 140
predict_fx = m*x+b
print(f'当x = 140时,f(x) = {predict_fx}')
[2.0, 1.875, 1.46875, 1.3111111111111111, 1.1272727272727272, 1.6666666666666667, 1.0, 0.9666666666666667, 0.8, 0.25, 0.6666666666666666, 0.5483870967741935, 0.9230769230769231, 0.6521739130434783, 0.3]
[40.0, 50.0, 82.5, 95.11111111111111, 109.81818181818183, 71.66666666666666, 135.0, 138.16666666666669, 154.0, 219.0, 175.66666666666669, 187.96774193548387, 143.6153846153846, 173.95652173913044, 221.5]
1.0370514514185623 133.19792941461947
当x = 140时,f(x) = 278.38513261321816
模型的参数 m 和 b 使用 ms 和 bs 的均值靠谱吗?
依据什么来判断?————均方误差
均方误差越小越好
losses = []
for x,y in data:
predict = m*x +b
loss = (y - predict)**2
losses.append(loss)
print(losses)
print(np.mean(losses)) #MSE为70.89464479297973
[261.2117156525208, 2.950896274059114, 15.592386778342608, 5.511657602429076, 14.664004457781697, 125.43720799274513]
70.89464479297973