Python 中正态方程的实现问题

  • 本文关键字:实现 问题 方程 Python python
  • 更新时间 :
  • 英文 :


我正在使用Python中的数据集,关于以下位置的房屋:

http://www.rossmanchance.com/iscam2/data/housing.txt

并尝试按如下方式实现线性回归:

import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
from sklearn.model_selection import train_test_split 
data= np.genfromtxt("housing.txt",dtype='O',delimiter="t",skip_header=True)
X=data[:,0].astype(np.float)
y=data[:,1].astype(np.float)
X_train, X_test, y_train, y_test = train_test_split(X, y)
lr=linear_model.LinearRegression()
X_trainrs=X_train.reshape(-1,1)
y_trainrs=y_train.reshape(-1,1)
lr.fit(X_trainrs,y_trainrs)
print "intercept ",lr.intercept_
yfit=lr.predict(X_test.reshape(-1,1))
plt.scatter(X_test,y_test)
plt.plot(X_test,yfit)

该程序运行良好,我得到了此数据集的线性回归图。我遇到的问题是当我想实现正态方程时。我做了这样的事情:

ft=(X_trainrs.T.dot(X_trainrs))
inv=np.linalg.inv(ft)
yfit2=X_test.reshape(-1,1).dot(inv)
plt.plot(X_test,yfit2)

我遇到的问题是绘制的值是一条平线,我做错了什么?

谢谢

据我所知,在代码的第二部分中,您试图通过求解线性方程组来获取系数,然后将其用于测试数据以生成预测。

您要做的是求解系数

X * 系数 = y

where X = [x1, 1]  y = [y1]  coeff = [slope     ]
[x2, 1]      [y2]          [intercept ]
[x3, 1]      [y3]
[ :  :]      [ :]
[xn, 1]      [yn]

该方程的解析解由下式给出:

coeff = inv(X.T * X( *

X.T * y = 伪逆(X( * y

要使用此解决方案生成预测,您需要这样做

y_test = X_test * 系数

X_test有额外的列,里面有一列。

您的代码存在 2 个问题:

  1. 您需要将包含 1 的列添加到X_trainrs。
  2. 用于生成预测的公式不正确。

这可能是您想要的:

xx = np.hstack([X_trainrs, np.ones((X_trainrs.shape[0], 1))]) # append ones
coeff = np.linalg.pinv(xx).dot(y_trainrs) # computes inv(X.T * X) * X.T * y
xx_test = np.hstack([X_test.reshape(-1, 1), np.ones((X_test.shape[0], 1))])
yfit2 = xx_test.dot(coeff)
plt.plot(X_test, yfit2)

您可以通过使用np.linalg.lstsq来避免编写手动获取coeff的逻辑,它可以为您完成所有这些操作。

coeff, _, _, _ = np.linalg.lstsq(xx, y_trainrs)

最新更新