gpt4 book ai didi

python - 使用 Numpy 的最小二乘法进行线性回归后的奇怪图

转载 作者:行者123 更新时间:2023-11-30 09:01:19 25 4
gpt4 key购买 nike

我正在使用多个变量进行线性回归。为了获得 thetas(系数),我使用了 Numpy 的最小二乘 numpy.linalg.lstsq 工具。在我的数据中,我有 n = 143 个特征和 m = 13000 个训练示例。我想根据面积绘制房价并显示此功能的拟合线。

数据准备代码(Python):

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

path = 'DB2.csv'
data = pd.read_csv(path, header=None, delimiter=";")
data.insert(0, 'Ones', 1)

cols = data.shape[1]
X = data.iloc[:,0:cols-1]
y = data.iloc[:,cols-1:cols]

使用 numpy.linalg.lstsq 获取 theta 系数:

thetas = np.linalg.lstsq(X, y)[0]

预测部分:

allAreasData = X.iloc[:,120] #Used as argument to scatter all training data
areasTestValues = X.iloc[0:100,120] #Used as argument for plot function
testingExamples = X.iloc[0:100,:] #Used to make predictions

predictions = testingExamples.dot(thetas)

注意:上面代码中的 120 是我的数据集中 Area 列的索引。

可视化部分:

fig, ax = plt.subplots(figsize=(18,10))  
ax.scatter(allAreasData, y, label='Traning Data', color='r')
ax.plot(areasTestValues, predictions, 'b', label='Prediction')
ax.legend(loc=2)
ax.set_xlabel('Area')
ax.set_ylabel('Price')
ax.set_title('Predicted Price vs. House Area')

输出图: enter image description here

我期望得到一些适合数据的单一回归线,但它却得到了如此奇怪的折线(虚线)。我做错了什么?分散效果很好。但情节不是。对于绘图函数,我发送 2 个参数:

1) Testing area data (100 area data examples)
2) Predictions of price based on 100 training examples that include area data


更新:对 x 进行排序后,我得到了这个曲线图: enter image description here

我本来希望用最小二乘误差得到直线拟合所有数据,但结果却得到了一条曲线。线性回归和 numpy.linalg.lstsq 工具不是应该返回直线拟合线而不是曲线吗?

最佳答案

您的结果在 143 维空间中呈线性。 ;) 由于您的 X 包含的特征不仅仅是区域,因此预测也将(线性)取决于这些特征。

如果您使用 X = data.iloc[:,120] 重新进行训练(仅考虑区域特征),则在绘制结果时应该会收到一条直线。

关于python - 使用 Numpy 的最小二乘法进行线性回归后的奇怪图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34178669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com