第三章 一元线性回归

2 代码

导入库

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.sandbox.regression.predstd import wls_prediction_std

导入数据

x = [80, 30, 50, 90, 70, 60, 120, 80, 100, 50, 40, 70, 90, 20, 110, 100, 30, 50] # 批量大小
y = [399, 121, 221, 376, 361, 224, 546, 352, 353, 157, 160, 242, 389, 113, 435, 420, 212, 268] # 劳动工时数

画图

plt.scatter(x, y) # 散点图

在这里插入图片描述

构建回归模型

x_ = sm.add_constant(x) # 添加一列1
mo = sm.OLS(y, x_) # 最小二乘法
result = mo.fit() # 拟合数据

print(result.summary())

在这里插入图片描述

print(result.conf_int(alpha=0.05, cols=None))

在这里插入图片描述

预测

y_fitted = result.fittedvalues # 计算点预测值
_, confidence_interval_lower, confidence_interval_upper = wls_prediction_std(result) #计算区间预测

画图

plt.scatter(x, y)
plt.plot(x, y_fitted, c='r')
plt.plot(x, confidence_interval_lower, 'g--')
plt.plot(x, confidence_interval_upper, 'g--') # 

在这里插入图片描述

发布了50 篇原创文章 · 获赞 51 · 访问量 2462

猜你喜欢

转载自blog.csdn.net/hezuijiudexiaobai/article/details/104664445
今日推荐