python - 没有 Sklearn 的 X 和 Beta 的普通最小二乘线性回归预测
问题描述
如何从以下获得具有 Beta 和 X 值的预测:
数据
import numpy as np
x = np.array([20, 25, 28, 29, 30])
y = np.array([20000, 25000, 26000, 30000, 32000])
转换
# Reshape X
X = x.reshape((-1, 1))
# Append ones to X:
X = np.append(np.ones((len(X), 1)), X, axis=1)
# Matrix X
X = np.matrix(X)
# Transpose X
XT = np.matrix.transpose(X)
# Matrix y
y = y.reshape((-1, 1))
y = np.matrix(y)
# Multiplication
XT_X = np.matmul(XT, X)
XT_y = np.matmul(XT, y)
# Betas
Betas = np.matmul(np.linalg.inv(XT_X), XT_y)
现在我需要获得我的预测来绘制并查看它的拟合程度:
import seaborn as sns
X = x
sns.regplot(X, prediction, fit_reg=False)
sns.regplot(X, y, fit_reg=False)
如何计算该预测,根据 X 值获得我的新 y?
谢谢!
解决方案
它是X @ Betas
:
predictions = np.array(X @ Betas).ravel()
x_values = np.array(X[:, 1]).ravel() # disregard the 1s column which is for bias
y_values = np.array(y).ravel()
sns.regplot(x_values, predictions, fit_reg=False, label="preds")
sns.regplot(x_values, y_values, fit_reg=False, label="truth")
plt.legend()
我不知道你为什么选择np.matrix
;我认为你可以坚持下去np.array
。
推荐阅读
- reactjs - Apollo Client + NextJs 认证问题
- python - 在 Pandas 的日期列上将分钟/秒归零
- r - 将嵌套的 JSON 转换为数据框
- java - java.time.Year#range 不返回一年中的具体星期(Java 1.8)
- javascript - align-self:flex start 没有将子元素发送到顶部
- android - Firebase 获取最后插入项目的密钥
- windows-store-apps - 找不到包含“UAP 10.0.17763.0”的“UAP.props”的 APPX321 SDK 文件夹
- c++ - 在对短字符串编码的有理数执行算术时,浮点的简单替代方案
- javascript - 按多个值过滤对象数组
- python-3.x - Pygame 协助