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

Python: Predict the y value using Statsmodels - Linear Regression

我正在使用 Python 的 statsmodels 库来使用线性回归预测未来的余额。 csv 文件显示如下:

| 余额
3 | 30
8 | 57
9 | 64
13 | 72
3 | 36
6 | 43
11 | 59
21 | 90
1 | 20
16 | 83
它包含 'Year' 作为独立 'x' 变量,而 'Balance' 是依赖 '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