def get_linear_regression(xdata, ydata):
""" Calculate the coefficients of the linear equation corresponding
to the linear regression of a series of points. """
try:
import numpy
return tuple(numpy.polyfit(xdata, ydata, 1))
except ImportError:
# numpy not available
# try something approximate and simple
datasize = len(xdata)
sum_x = float(sum(xdata))
sum_y = float(sum(ydata))
sum_xx = float(sum(map(lambda x: x * x, xdata)))
sum_products = float(sum([xdata[i] * ydata[i]
for i in range(datasize)]))
a = (sum_products - sum_x * sum_y / datasize) / (
sum_xx - (sum_x * sum_x) / datasize)
b = (sum_y - a * sum_x) / datasize
return a, b
评论列表
文章目录