7.2简单线性回归(Simple Linear Regretion)下

1.简单线性回归模型举例:

   汽车卖家做电视广告数量与卖出的汽车数量:

1.1 如何练出适合简单回归模型的最佳回归线?

使sun of squares最小

   1.1.1 计算

1.2 预测:

假设有一周广告数量为6,预测的汽车销售量为多少?

x_given = 6

y_hat = 5 * 6 + 10 = 40

1.3 Python实现:

import numpy as np

def fitSLR(x, y):
    n = len(x)
    dinominator = 0
    numerator = 0
    for i in range(0, n):
        numerator += (x[i] - np.mean(x)) * (y[i] - np.mean(y))
        dinominator += (x[i] - np.mean(x)) ** 2
    print("numerator:",numerator)
    print("dinominator:",dinominator)
    b1 = numerator / float(dinominator)
    b0 = np.mean(y) - b1 * np.mean(x)

    return b0, b1


def predict(x, b0, b1):
    return b0 + x * b1


x = [1, 3, 2, 1, 3]
y = [14, 24, 18, 17, 27]

b0, b1 = fitSLR(x, y)
print("intercept:", b0, "slope:", b1)
x_test = 6
y_test = predict(6, b0, b1)
print("y_test:",y_test)

结果:

numerator: 20.0
dinominator: 4.0
intercept: 10.0 slope: 5.0
y_test: 40.0

猜你喜欢

转载自blog.csdn.net/weixin_41790863/article/details/81122803