如何使用 numpy.polyfit 执行线性回归并打印错误统计信息?
How to perform linear regression with numpy.polyfit and print error statistics?
我正在弄清楚如何使用 np.polyfit
函数,而 documentation 让我感到困惑。特别是,我正在尝试执行线性回归并打印相关统计数据,例如误差平方和 (SSE)。有人可以提供清晰简洁的解释,可能还有一个最小的工作示例吗?
np.polyfit
returns 是一个元组,包含参数化 best-fitting 度数 deg
多项式的系数。要拟合一条线,请使用 deg = 1
。您可以通过将 full = True
作为参数传递给 polyfit
来 return 残差(误差平方和)。请注意,使用此参数,polyfit
还将 return 一些有关拟合的其他信息,我们可以将其丢弃。
总而言之,我们可能有类似的东西
import matplotlib.pyplot as plt
import numpy as np
# Generate some toy data.
x = np.random.rand(25)
y = 2 * x + 0.5 + np.random.normal(scale=0.05, size=x.size)
# Fit the trend line.
(m, b), (SSE,), *_ = np.polyfit(x, y, deg=1, full=True)
# Plot the original data.
plt.scatter(x, y, color='k')
# Plot the trend line.
line_x = np.linspace(0, 1, 200)
plt.plot(line_x, m * line_x + b, color='r')
plt.title(f'slope = {round(m, 3)}, int = {round(b, 3)}, SSE = {round(SSE, 3)}')
plt.show()
polyfit
调用中的 *_
表示法只是告诉 Python 丢弃,但是函数 return 编辑了许多其他值。如果您有兴趣,文档可以告诉您这些额外的值。我们必须将 SSE 解析为元组 (SSE,)
,因为 polyfit
return 将其作为单例数组。此代码生成类似 this plot.
的内容
您可能还想了解 np.polyval
,它将采用多项式系数的元组并在输入点计算相应的函数。
我正在弄清楚如何使用 np.polyfit
函数,而 documentation 让我感到困惑。特别是,我正在尝试执行线性回归并打印相关统计数据,例如误差平方和 (SSE)。有人可以提供清晰简洁的解释,可能还有一个最小的工作示例吗?
np.polyfit
returns 是一个元组,包含参数化 best-fitting 度数 deg
多项式的系数。要拟合一条线,请使用 deg = 1
。您可以通过将 full = True
作为参数传递给 polyfit
来 return 残差(误差平方和)。请注意,使用此参数,polyfit
还将 return 一些有关拟合的其他信息,我们可以将其丢弃。
总而言之,我们可能有类似的东西
import matplotlib.pyplot as plt
import numpy as np
# Generate some toy data.
x = np.random.rand(25)
y = 2 * x + 0.5 + np.random.normal(scale=0.05, size=x.size)
# Fit the trend line.
(m, b), (SSE,), *_ = np.polyfit(x, y, deg=1, full=True)
# Plot the original data.
plt.scatter(x, y, color='k')
# Plot the trend line.
line_x = np.linspace(0, 1, 200)
plt.plot(line_x, m * line_x + b, color='r')
plt.title(f'slope = {round(m, 3)}, int = {round(b, 3)}, SSE = {round(SSE, 3)}')
plt.show()
polyfit
调用中的 *_
表示法只是告诉 Python 丢弃,但是函数 return 编辑了许多其他值。如果您有兴趣,文档可以告诉您这些额外的值。我们必须将 SSE 解析为元组 (SSE,)
,因为 polyfit
return 将其作为单例数组。此代码生成类似 this plot.
您可能还想了解 np.polyval
,它将采用多项式系数的元组并在输入点计算相应的函数。