python - 如何计算python中简单线性回归拟合的截距和斜率?

标签 python python-3.x

我有以下代码 类数据: def init(self, x, y): """(数据、列表、列表)-> NoneType

    Create a new data object with two attributes: x and y.
    """
    self.x = x
    self.y = y

def num_obs(self):
    """ (Data) -> int

    Return the number of observations in the data set.

    >>> data = Data([1, 2], [3, 4])
    >>> data.num_obs()
    2
    """

    return len(self.x)

def __str__(self):
    """ (Data) -> str
    Return a string representation of this Data in this format:
    x               y
    18.000          120.000
    20.000          110.000
    22.000          120.000
    25.000          135.000
    26.000          140.000
    29.000          115.000
    30.000          150.000
    33.000          165.000
    33.000          160.000
    35.000          180.000
    """

    return 'x               y\n' + '\n'.join('{0:.3f}         {1:.3f}'.format(a, b) for a, b in zip(self.x, self.y))

def compute_sample_means(self):
    """ (Data) -> number, number

    Return sample mean of x and sample mean of y.
    """
    a = sum(self.x)/len(self.x)
    b = sum(self.y)/len(self.y)
    return a,b

def compute_least_squares_fit(self):
    """ (Data) -> number, number

 Return the intercept and slope of the simple linear regression fit
    of the data.
    """
    pass


def compute_SST(self):
    """ (Data) -> number

    Return the sum of squares total (SST).
    """

    avg_y = np.mean(self.y)
    squared_errors = (self.y - avg_y) ** 2
    return np.sum(squared_errors)

我坚持返回compute_least_squares_fit部分。如何计算数据的简单线性回归拟合的截距和斜率。有我可以使用的内置功能吗?

最佳答案

SciPy模块有scipy.optimize.least_squares我一直将其用于简单的线性回归模型。

根据文档,它解决了变量有界的非线性最小二乘问题。它返回找到的解决方案,我想这会导致您正在寻找的结果。

请告诉我这是否有帮助!

关于python - 如何计算python中简单线性回归拟合的截距和斜率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59206282/

相关文章:

python - 如何在 Django ORM 中连接两个表而没有第一个表中的任何列引用第二个

python - python3 和 pip 的问题

python - Python 中的有界逻辑回归

python - 2个for循环可以同时运行,一个接一个循环吗?

javascript - 在 python 和 node.js 中复制 java.lang.String.hashCode() 输出的函数

Python打印函数不按顺序打印

python - 在 Python 中粘贴多行时出现 SyntaxError

python - 集成测试多个 Celery Worker 和一个数据库支持的 Django API

Python3 快速检查元素是否在元素集合中的方法

python-3.x - YOLO v3 的 OpenCV 实现在 GCP 实例上重现异常