python-3.x - 使用python 3如何获得协方差/方差
问题描述
我有一个简单的线性回归模型,我需要计算方差和协方差。如何使用线性回归计算方差和协方差?
在机器学习的背景下,方差是由于模型对训练集中的小波动的敏感性而发生的一种错误。
from sklearn.linear_model import LinearRegression
import numpy as np
X = np.array([2,3,4,5])
y = np.array([4,3,2,9] )
#train-test split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)
# Train the model using the training sets
model = LinearRegression()
model.fit(x_train, y_train)
y_predict = model.predict(X_predict)
解决方案
试试这个你得到的方差和协方差的输出向量:
y_variance = np.mean((y_predict - np.mean(y_predict))**2)
y_covariace = np.mean(y_predict - y_true_values)
注意:这里的协方差是相对于真实值的预测变化的平均值。
推荐阅读
- python - Django 查询集:检查外键值并从查询集中减去它们
- ubuntu - Ubuntu18.04 - Anaconda 导航器更新问题
- c - memset 如何提供比 bzero 或 explicit_bzero 更高的安全性?
- dart - Flutter POST 请求正文未发送
- php - 连接到 Fedex api 时出现身份验证错误
- kubernetes - Kubernetes:定期删除 pod
- javascript - 如何正确使用 Nuxt JS 的 Vuex 模块模式?
- python - 为什么`conda update --all`不会全部更新?
- json - Postgres jsob 选择特定的数组字段
- android - Android WebView shouldOverrideUrlLoading 问题