Python 计算OLS回归的yhat

Python 计算OLS回归的yhat,python,python-3.x,Python,Python 3.x,我在python中实现了一种计算OLS回归的beta的方法。现在,我想用R^2为我的模型打分。对于我的任务,我不允许使用Python软件包来完成,因此必须从头开始实现一个方法 #load the data import numpy as np import pandas as pd from numpy.linalg import inv from sklearn.datasets import load_boston boston = load_boston() # Set the X an

我在python中实现了一种计算OLS回归的beta的方法。现在,我想用R^2为我的模型打分。对于我的任务,我不允许使用Python软件包来完成,因此必须从头开始实现一个方法

#load the data
import numpy as np
import pandas as pd
from numpy.linalg import inv
from sklearn.datasets import load_boston
boston = load_boston()

# Set the X and y variables. 
X = boston.data
y = boston.target

#append ones to my X matrix. 
int = np.ones(shape=y.shape)[..., None]
X = np.concatenate((int, X), 1)

#compute betas. 
betas = inv(X.transpose().dot(X)).dot(X.transpose()).dot(y)

# extract the feature names of the boston data set and prepend the 
#intercept
names = np.insert(boston.feature_names, 0, 'INT')

# collect results into a DataFrame for pretty printing
results = pd.DataFrame({'coeffs':betas}, index=names)

#print the results
print(results)

            coeffs
INT      36.491103
CRIM     -0.107171
ZN        0.046395
INDUS     0.020860
CHAS      2.688561
NOX     -17.795759
RM        3.804752
AGE       0.000751
DIS      -1.475759
RAD       0.305655
TAX      -0.012329
PTRATIO  -0.953464
B         0.009393
LSTAT    -0.525467
现在,我想实现一个R^2,在这个数据(或任何其他数据)上为我的模型打分。(见此处: )

我的问题是我不能完全确定如何计算分子SSE。在代码中,它将如下所示:

#numerator
sse = sum((Y - yhat ** 2)

其中Y是波士顿房价,yhat是这些房屋的预测价格。但是,我如何计算术语“yhat”?

yhat
是您对给定观测值的估计值。您可以通过
X.dot(betas)
使用该产品同时获得所有估算值

您的误差平方和如下(请注意对您给出的版本的更正:您需要对差异进行平方,即对误差进行平方):

您的总平方和:

tss = ((y - y.mean()) ** 2).sum()
得出的R平方(确定系数):


另外,我不会使用
int
作为变量名来避免对内置函数的冲击(只需将其称为
ones
const

你不求yhat的平方,而是求差的平方。这比预期的要容易,我的数学游戏肯定要升级。非常感谢。
tss = ((y - y.mean()) ** 2).sum()
r2 = 1 - sse / tss