如何在线性回归方程中找到结果的平均值

How to find the average of results in a linear regression equation

我有方程式,我被要求求出 2010 年到 2015 年 x 的平均值。我开始了一个循环以首先获取 2010-2015 年的值,但我仍然不知道如何获得平均值这些值。以下是我目前所拥有的:

a = -22562.8
b = 11.24
i = 2010
while i <=2015:
    sum_estimated_riders = (a + (i * b)) * 100000
    print(sum_estimated_riders)
    i = i + 1 

你每次都覆盖sum_estimated_riders。相反,在循环之前将其初始化为 0 并在循环内添加到它。然后除以迭代次数。

a = -22562.8
b = 11.24
i = 2010
sum_estimated_riders = 0
num_years = 0
while i <=2015:
    sum_estimated_riders += (a + (i * b)) * 100000
    num_years += 1
    i = i + 1 

mean_estimated_riders = sum_estimated_riders / num_years
print(mean_estimated_riders)

或者,您可以为每年创建一个 estimated_riders 列表。然后,使用sum()计算总和并除以列表的长度。

estimated_riders = []
while i <= 2015:
    estimated_riders.append((a + (i * b)) * 100000)

mean_estimated_riders = sum(estimated_riders) / len(estimated_riders)

或者,作为列表理解:

estimated_riders = [(a + (i * b)) * 100000 for i in range(2010, 2016)] # 2016 because range() excludes the end
mean_estimated_riders = sum(estimated_riders) / len(estimated_riders)

您可以为此使用 numpy.mean() 制作一个列表,将每个值附加到它,然后取平均值。

import numpy as np


estimated_riders = []
a = -22562.8
b = 11.24
i = 2010
while i <=2015:
    sum_estimated_riders = (a + (i * b)) * 100000
    estimated_rides.append(sum_estimated_riders)
    i = i + 1 

avg = np.mean(estimated_riders)
print(avg)