首页 > 解决方案 > 使用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)

标签: python-3.xlinear-regression

解决方案


试试这个你得到的方差和协方差的输出向量:

y_variance = np.mean((y_predict - np.mean(y_predict))**2)

y_covariace = np.mean(y_predict - y_true_values)

注意:这里的协方差是相对于真实值的预测变化的平均值。


推荐阅读