使用python 3如何获取协方差/方差

时间:2019-09-20 08:45:44

标签: python-3.x linear-regression

我有一个简单的线性回归模型,我需要计算方差和协方差。如何使用线性回归计算方差和协方差?

  

在机器学习的上下文中,方差是由于模型对训练集中的小波动敏感的原因而发生的一种错误。

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)

1 个答案:

答案 0 :(得分:0)

对于获得方差和协方差的输出矢量,请尝试以下操作:

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

y_covariace = np.mean(y_predict - y_true_values)

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

相关问题