首页 文章

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

提问于
浏览
1

我正在使用多个变量进行线性回归 . 为了获得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

我希望得到一些适合数据的单一回归线,但它没有得到如此奇怪的折线(折线) . 我做错了什么? Scatter工作正常 . 但情节不是 . 对于绘图函数,我发送2个参数:

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

Update: 排序后 x 我用曲线得到了这个情节:
enter image description here

我期望直线拟合我的所有数据与最小平方误差,但得到一条曲线 . 是不是线性回归和numpy.linalg.lstsq工具应该返回直线而不是曲线?

1 回答

  • 1

    您的结果在143维空间中是线性的 . ;)由于您的X包含的功能多于区域,因此预测也将(线性地)依赖于这些功能 .

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

相关问题