遍历每一行并构建回归模型和绘图(n-1 行逐步通过)

问题描述 投票:0回答:1

下面有一个简单的线性回归模型,它适合 10 行数据。

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

# Generate 'random' data
np.random.seed(0)
X = 2.5 * np.random.randn(10) + 1.5   
res = 0.5 * np.random.randn(10)       
y = 2 + 0.3 * X + res                  
Name = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

# Create pandas dataframe to store our X and y values
df = pd.DataFrame(
    {'Name': Name,
     'X': X,
     'y': y})

# Show the dataframe
df

import statsmodels.formula.api as smf
# Initialise and fit linear regression model using `statsmodels`
model = smf.ols('X ~ y', data=df)
model = model.fit()

# Predict values
age_pred = model.predict()

# Plot regression line against actual data
plt.figure(figsize=(6, 4))
plt.plot(sc_X['Salary'], sc_X['Age'], 'o')           # scatter plot showing actual data
plt.plot(sc_X['Salary'], age_pred, 'r', linewidth=2)   # regression line
plt.show()

数据框包含如下数据:

姓名 X y
A 5.910131 3.845061
2.500393 3.477255
C 3.946845 3.564572
D 7.102233 4.191507
E 6.168895 4.072600
F -0.943195 1.883879
G 3.875221 3.909606
H 1.121607 2.233903
1.241953 2.529120
J 2.526496 2.330901

我想通过遍历上表来生成回归模型,每次为每个“名称”排除一行数据。该模型应构建为 n-1 行。

所以比如第一个模型和散点图,应该是所有名字(除了A行的行对应值);然后对于第二个模型和散点图,它将是除 B 行以外的所有数据,依此类推。

如何将其应用到上表中?对于代码自动构建的每个 (n-1) 回归模型,我还如何生成回归图?

在结果图上,我可以包含一个注释,上面写着“除了 A”之类的东西(表示 A 已从用于构建模型的数据中排除)。接下来是“B 除外”,然后是“C 除外”。

python pandas regression statsmodels
1个回答
0
投票

我们开始吧,我只是循环数据框并过滤“除一行以外的所有内容”。


import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

# Generate 'random' data
np.random.seed(0)
X = 2.5 * np.random.randn(10) + 1.5
res = 0.5 * np.random.randn(10)
y = 2 + 0.3 * X + res
Name = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

# Create pandas dataframe to store our X and y values
df = pd.DataFrame(
    {'Name': Name,
     'X': X,
     'y': y})

# Show the dataframe
df

import statsmodels.formula.api as smf
# Initialise and fit linear regression model using `statsmodels`



for row_index, row in df.iterrows():
    # dataframe with all rows except for one
    df_reduced = df[~(df.index == row_index)]
    model = smf.ols('X ~ y', data=df_reduced)
    model = model.fit()
    intercept, slope = model.params

    y1 = intercept + slope * df_reduced.y.min()
    y2 = intercept + slope * df_reduced.y.max()
    plt.plot([df_reduced.y.min(), df_reduced.y.max()], [y1, y2], label=row.Name)
    plt.scatter(df_reduced.y, df_reduced.X)
    plt.legend()
    plt.savefig(f"{row.Name}.pdf")
    plt.show()

输出看起来像这样:

© www.soinside.com 2019 - 2024. All rights reserved.