对数回归线是不是直线与负对数值?

2024-06-25 23:55:45 发布

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

我有一个相关图,在这里我试着用对数标度显示值。我试图在相关图上显示最佳拟合线。你知道吗

下面是我的代码。你知道吗

import numpy             as np
import matplotlib        as mpl
import matplotlib.pyplot as plt

from scipy import stats

def loglogplot(seed):
    mpl.rcParams.update({'font.size': 10})
    figh, figw = 1.80118*2, 1.80118*2    
    fig, axes  = plt.subplots(1, 1, figsize=(figh, figw))

    axes.set_xscale('log')
    axes.set_yscale('log')

    np.random.seed(seed)
    x = 10 ** np.random.uniform(-3, 3, size=1000*4)
    y = x * 10 ** np.random.uniform(-1, 1, size=1000*4)
    axes.scatter(x, y, color='black', s=10, alpha=0.1)

    logx = np.log10(x)
    logy = np.log10(y)

    slope, intercept, r_value, p_value, std_err = stats.linregress(logx, logy)
    xps = np.arange(10**-4, 10**4, 1)
    axes.plot(xps, slope * xps + intercept, color='red', lw=2)    

    axes.set_xlim((10**-4, 10**4))
    axes.set_ylim((10**-4, 10**4))

    plt.show()

当使用loglogplot(seed=5)运行时,我得到以下图像。你知道吗

LogLog function invocation with seed=5

当使用loglogplot(seed=10)运行时,我得到以下图像。你知道吗

LogLog function invocation with seed=5

我很清楚为什么在x=1之前,回归线不是画成直线的。我做错什么了?你知道吗

编辑:将xps = np.arange(10**-4, 10**4, 1)改为xps = np.logspace(-4, 4, 1000),结果在质量上没有改善。你知道吗

种子=5给出:

LogSpace points between -4 and 4 for seed=5

种子=10给出:

LogSpace points between -4 and 4 for seed=10


Tags: importsizematplotlibasstatsnppltrandom
1条回答
网友
1楼 · 发布于 2024-06-25 23:55:45

这里的问题的关键是对数标度不转换数据,而是转换数据显示在图纸空间中的位置。这意味着,您不能将经过日志转换的最佳拟合参数用于未经日志转换的数据,并且不能正确地绘制这些参数。你知道吗

您要么需要对数据进行日志转换,并直接使用它们,要么需要考虑实际建模的关系,并根据需要撤消它。你知道吗

通过拟合数据日志,可以拟合以下等式:

log(y) = m * log(x) + p

用数学,这就变成了:

y = exp(p) * (x ^ m)

所以你的代码变成:

import numpy
from matplotlib import rcParams, pyplot
from scipy import stats

def loglogplot(seed):
    rcParams.update({'font.size': 10})
    figh, figw = 1.80118*2, 1.80118*2    
    fig, axes  = pyplot.subplots(1, 1, figsize=(figh, figw))

    axes.set_xscale('log')
    axes.set_yscale('log')

    numpy.random.seed(seed)
    x = 10 ** numpy.random.uniform(-3, 3, size=1000*4)
    y = x * 10 ** numpy.random.uniform(-1, 1, size=1000*4)
    axes.scatter(x, y, color='black', s=10, alpha=0.1)

    logx = numpy.log(x)  # <  doesn't matter that we use natural log
    logy = numpy.log(y)  #     so long as we're consistent

    slope, intercept, r_value, p_value, std_err = stats.linregress(logx, logy)
    xhat = numpy.logspace(-4, 4, 1000)
    yhat = numpy.exp(intercept) * xhat ** slope  # exp -> consistency
    axes.plot(xhat, yhat, color='red', lw=2)    

    axes.set_xlim((10**-4, 10**4))
    axes.set_ylim((10**-4, 10**4))

    return fig

enter image description here

相关问题 更多 >