残差散点图的线性回归回路

2024-04-25 16:56:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个线性回归模拟,每个模型根据“label”变量的不同值。我可以打印每个模型的指标,但我无法为每个模型运行不同的散点图。所有图形都复制在一个散点图中。我想为每个模型运行一个度量和一个不同的散点图

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from scipy.stats import binom
from scipy.stats import norm
import numpy as np

from scipy.stats import norm
# generate random numbers from N(0,1)
x = norm.rvs(size=10000,loc=0,scale=1)
y = norm.rvs(size=10000,loc=0,scale=1)
z = binom.rvs(n=10,p=0.8,size=10000)
df = pd.DataFrame(data={'v1':x.flatten(),'target':y.flatten(),'label':z.flatten()})

classes=df.label.unique().tolist()
results = []


for name in classes:
    df_subset=df.loc[df['label']==name]
    
    reg = LinearRegression()
    reg.fit(df_subset['v1'].values.reshape(-1, 1), df_subset["target"].values.reshape(-1, 1))
    predictions = reg.predict(df_subset['v1'].values.reshape(-1, 1))
    
    res=np.mean((predictions - df_subset["target"].values.reshape(-1, 1)) ** 2)
    results.append(res)
    
    msg = "Metric model %s: %f " % (name, res)
    print(msg)
    
    df_subset['pred']=predictions
    sns.scatterplot(data=df_subset, x='pred', y="target")

2条回答

我建议安装matplotlib库,然后

import matplotlib.pyplot as plt
y = 0
.
.
.
#inside your for loop
plot = sns.scatterplot(data=df_subset, x='pred', y="target")
plt.savefig('plot_' + str(y))
plt.clf()

只需在sns绘图之前创建一个新图形。 plt.figure()<- sns绘图之后,请执行plt.show(),以便可以在每个绘图之前显示打印语句(模型度量)

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from scipy.stats import binom
from scipy.stats import norm
import numpy as np
import seaborn as sns

from scipy.stats import norm
# generate random numbers from N(0,1)
x = norm.rvs(size=10000,loc=0,scale=1)
y = norm.rvs(size=10000,loc=0,scale=1)
z = binom.rvs(n=10,p=0.8,size=10000)
df = pd.DataFrame(data={'v1':x.flatten(),'target':y.flatten(),'label':z.flatten()})

classes=df.label.unique().tolist()
results = []


for name in classes:
    df_subset=df.loc[df['label']==name]
    
    reg = LinearRegression()
    reg.fit(df_subset['v1'].values.reshape(-1, 1), df_subset["target"].values.reshape(-1, 1))
    predictions = reg.predict(df_subset['v1'].values.reshape(-1, 1))
    
    res=np.mean((predictions - df_subset["target"].values.reshape(-1, 1)) ** 2)
    results.append(res)
    
    msg = "Metric model %s: %f " % (name, res)
    print(msg)
    plt.figure() #<     -here
    df_subset['pred']=predictions
    sns.scatterplot(data=df_subset, x='pred', y="target")
    plt.show() #<       here

相关问题 更多 >