【问题标题】:How would I plot my linear regression model with a line of best fit?如何用最佳拟合线绘制我的线性回归模型?
【发布时间】:2021-03-15 10:00:59
【问题描述】:

我刚刚训练了一个线性回归模型,根据“number_rooms”和“price”获得了房价的截距和系数。但是我有点不确定如何使用具有最佳拟合线的散点图来绘制我的回归模型。

对于如何执行此操作的任何帮助将不胜感激 - 谢谢!

这是我的代码:

rgr = linear_model.LinearRegression()
rgr.fit(X=sample['number_rooms'].values.reshape(-1,1), y=sample['price'].values)

print(rgr.intercept_, rgr.coef_[0])

predictions = rgr.predict(X=sample['number_rooms'].values.reshape(-1,1))
metrics.mean_squared_error(y_pred=predictions, y_true=sample['price'], squared=False)

【问题讨论】:

    标签: python machine-learning scikit-learn regression linear-regression


    【解决方案1】:

    让我们看看它的数学原理

    在给定x 的情况下,线性回归拟合y 的直线,从而最大限度地减少误差。这条线表示为:y = w*x +b

    w = rgr.coef_[0]
    bias = rgr.intercept_
    
    number_rooms = sample['number_rooms'].values
    
    plt.plot([min(number_rooms), max(number_rooms)], 
             [w*min(number_rooms)+bias, w*max(number_rooms)+bias])
    

    【讨论】:

      【解决方案2】:

      这很简单,试试这个-

      import matplotlib.pyplot as plt
      
      # to plot predictions
      plt.scatter(sample['number_rooms'].values, predictions.array.reshape(-1, 1), c='g', label='predicted prices')
      
      # to plot the best fit line
      min_rooms = 0 # or 1
      max_rooms = 10 #say
      
      rooms_range = range(min_rooms, max_rooms+1)
      plt.plot(rooms_range, rgr.predict(X=rooms_range).array.reshape(-1, 1), c='r', label='best fit')
      plt.legend()
      

      【讨论】:

      • 嗨赛 - 感谢您的回答。我已经尝试过您提供给我的解决方案,但是在最后一行代码中,我收到一条错误消息:“Reshape your data either using array.reshape(-1, 1)”。
      • 嗨,可能是因为回归器输出结果的方式。检查我的更新
      【解决方案3】:

      您可以尝试以下其他方法:

      鉴于现在您知道斜率和截距,找到一个合理的范围 - 一个最能描述房间数量的范围,然后

      y = m*number_of_beds + 截距

      然后在散点图上绘制 y 和 x

      【讨论】:

      • 我也喜欢sai的回答
      • 谢谢,我也试试!
      猜你喜欢
      • 2018-03-17
      • 2022-11-04
      • 2019-09-11
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 2011-07-18
      相关资源
      最近更新 更多