Python:使用 Statsmodels - 线性回归预测 y 值

标签 python pandas regression statsmodels

我正在使用 Python 的 statsmodels 库使用线性回归来预测 future 的平衡。 csv 文件如下所示:

年份 | 余额
3 | 30
8 | 57
9 | 64
13 | 72
3 | 36
6 | 43
11 | 59
21 | 90
1 | 20
16 | 83
它包含“年”作为独立的“x”变量,而“余额”是因变量“y”

这是此数据的线性回归代码:

import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols
import numpy as np
from matplotlib import pyplot as plt

import os
os.chdir('C:\Users\Admin\Desktop\csv')

cw = pd.read_csv('data-table.csv')
y=cw.Balance
X=cw.Year

X = sm.add_constant(X)  # Adds a constant term to the predictor

est = sm.OLS(y, X)
est = est.fit()
print est.summary()

est.params

X_prime = np.linspace(X.Year.min(), X.Year.max(), 100)[:, np.newaxis]
X_prime = sm.add_constant(X_prime)  # add constant as we did before

y_hat = est.predict(X_prime)


plt.scatter(X.Year, y, alpha=0.3)  # Plot the raw data
plt.xlabel("Year")
plt.ylabel("Total Balance")
plt.plot(X_prime[:, 1], y_hat, 'r', alpha=0.9)  # Add the regression line, colored in red
plt.show()

问题是当“Year”的值=10 时,如何使用 Statsmodels 预测“Balance”值?

最佳答案

您可以使用结果对象 est 中的 predict 方法,但为了成功使用它,您必须使用 as 公式

est = sm.ols("y ~ x", data =data).fit()
est.predict(exog=new_values) 

其中 new_values 是字典。

看看这个 link .

关于Python:使用 Statsmodels - 线性回归预测 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36976795/

相关文章:

python - 以字典为内容的嵌套列表

python - 替换文件中最后一个字符的简单方法?

python - : python string assignments accidentally change '\b' into '\x08' and '\a' into '\x07' , 为什么 Python 这样做?

python - 如何使用 Python/Pandas 转换为正态分布?

python - 使用 Python/Sklearn 创建并拟合乘法线性回归

python - PyYAML与组合,属性错误

python - ValueError : Length mismatch: Expected axis has 2 elements, new values have 3 elements

python - 尝试从混合类型 pd 系列中的邮政编码中删除 +4

python - 在 pandas 中,如何使用 "where"参数来查询日期时间索引列?

python - 回归问题还是分类问题?