【问题标题】:Linear Regression: How to find the distance between the points and the prediction line?线性回归:如何找到点与预测线之间的距离?
【发布时间】:2023-04-03 01:50:01
【问题描述】:

我正在寻找点和预测线之间的距离。理想情况下,我希望结果显示在包含距离的新列中,称为“距离”。

我的进口:

import os.path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
%matplotlib inline 

我的数据样本:

idx  Exam Results  Hours Studied
0       93          8.232795
1       94          7.879095
2       92          6.972698
3       88          6.854017
4       91          6.043066
5       87          5.510013
6       89          5.509297

到目前为止我的代码:

x = df['Hours Studied'].values[:,np.newaxis]
y = df['Exam Results'].values

model = LinearRegression()
model.fit(x, y)

plt.scatter(x, y,color='r')
plt.plot(x, model.predict(x),color='k')
plt.show()

任何帮助将不胜感激。谢谢

【问题讨论】:

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


【解决方案1】:

您只需将ymodel.predict(x) 之间的差异分配给一个新列(如果您只想要差异的大小,则取绝对值):

#df["Distance"] = abs(y - model.predict(x))  # if you only want magnitude
df["Distance"] = y - model.predict(x)
print(df)
#   Exam Results  Hours Studied  Distance
#0            93       8.232795 -0.478739
#1            94       7.879095  1.198511
#2            92       6.972698  0.934043
#3            88       6.854017 -2.838712
#4            91       6.043066  1.714063
#5            87       5.510013 -1.265269
#6            89       5.509297  0.736102

这是因为您的模型为每个自变量 (x) 预测了一个 y(因变量)。 x的坐标是一样的,所以y的差就是你想要的值。

【讨论】:

  • 当我尝试运行那行代码时,我似乎遇到了这个错误。 ValueError:值的长度与索引的长度不匹配知道为什么会这样吗? x的形状是(132, 1),y的形状是(132,)。
  • 你的数据框的长度是多少?该错误表明问题来自df["Distance"] = 部分而不是y - model.predict(x) 部分。你也可以df["Distance"] = df['Exam Results'].values - model.predict(df['Hours Studied'].values[:,np.newaxis])
  • 我的数据帧的长度是 1789,但是最后一段代码似乎可以解决问题,非常感谢。知道我为什么遇到这个问题吗?
  • 该错误是因为您试图将 132 个值分配给具有 1789 行的数据框。我怀疑您仅在数据子集上构建了模型,然后尝试为每一行计算 Distance
  • 我知道这是一篇旧帖子。但是任何人都可以帮助如何对每个组进行此操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2022-07-29
  • 2019-01-01
  • 2017-02-11
  • 1970-01-01
  • 2020-01-26
相关资源
最近更新 更多