You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于指定数据的Simple Linear Regression代码排查与Colab绘图修复

单一特征简单线性回归代码问题排查与修正

你的代码逻辑本身是正确的,数学计算完全符合简单线性回归的系数推导公式,数据也和参考数据集匹配。在Google Colab中运行报错,大概率是因为matplotlib的显示配置问题,而非代码逻辑错误。

问题原因

Google Colab中默认需要显式启用matplotlib的inline渲染模式,否则图像可能无法正常显示甚至触发报错。

修正后的代码

%matplotlib inline  # 添加这行,启用Colab的matplotlib inline显示
import numpy as np
import matplotlib.pyplot as plt
  
def estimate_coef(x, y):
    # 样本数量
    n = np.size(x)
  
    # x和y的均值
    m_x = np.mean(x)
    m_y = np.mean(y)
  
    # 计算交叉离均差和x的离均差平方和
    SS_xy = np.sum(y*x) - n*m_y*m_x
    SS_xx = np.sum(x*x) - n*m_x*m_x
  
    # 计算回归系数
    b_1 = SS_xy / SS_xx
    b_0 = m_y - b_1*m_x
  
    return (b_0, b_1)
  
def plot_regression_line(x, y, b):
    # 绘制原始数据散点图
    plt.scatter(x, y, color = "m", marker = "o", s = 30)
  
    # 计算预测值
    y_pred = b[0] + b[1]*x
  
    # 绘制回归线
    plt.plot(x, y_pred, color = "g")
  
    # 设置坐标轴标签
    plt.xlabel('x')
    plt.ylabel('y')
  
    # 显示图像
    plt.show()
  
def main():
    # 数据集
    x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
  
    # 估算回归系数
    b = estimate_coef(x, y)
    print(f"Estimated coefficients:\nb_0 = {b[0]:.4f}\nb_1 = {b[1]:.4f}")
  
    # 绘制回归线
    plot_regression_line(x, y, b)
  
if __name__ == "__main__":
    main()

额外说明

  • 添加%matplotlib inline是Colab中显示matplotlib图像的关键步骤,它会将图像嵌入到笔记本单元格中。
  • 对打印格式做了微调,用f-string让系数显示更简洁规范,保留四位小数便于阅读。
  • 修正后运行代码,会输出正确的回归系数,并生成你预期的回归曲线图。

内容的提问来源于stack exchange,提问作者Aaryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:41:12