幂律拟合(Powerfit)与经验数据不匹配:y轴起始值异常
幂律拟合曲线起始位置错误问题排查
问题描述
处理Newman的数据集时,已将幂律拟合的xmin设为230,但红色幂律拟合曲线始终从y=1处起始,实际应从坐标(230, 0.3)开始。相关代码如下:
def powerPlot(fit): plt.figure() fig1 = fit.plot_ccdf(original_data=True, color='blue', linestyle='', marker='o', markersize=10, markerfacecolor='none', label='CCDF') fit.power_law.plot_ccdf(ax=fig1, survival=True, color='red', linestyle='--', alpha=1) fit.truncated_power_law.plot_ccdf(ax=fig1, color='purple', linestyle='--', alpha=1) import pipe import plotsettings as ps import printValues as pV import plotDist as pD def main(): data = pipe.getData("Black.txt") fit = powerlaw.Fit(data) fit2 = powerlaw.Fit(data, xmin = fit.xmin, xmax = fit.xmax , alpha = fit.alpha, discrete = True) #fit3 = powerlaw.Fit(data, xmin = 1) #pV.printAlpha(fit) #pV.printXmin(fit) #pV.printRAndP(fit) #pD.bigPlot(fit2) # pV.printBig(fit2) # pD.bigPlot(fit) pD.powerPlot(fit2) # pD.expPlot(fit2) #pD.normPlot(fit2) ps.setPlot("Words.txt") main()
问题原因
调用fit.power_law.plot_ccdf()绘制幂律曲线时,该方法默认会从x=1开始绘制整个幂律分布的生存函数(CCDF),而非你设定的xmin=230。这就导致曲线起始于y=1(x=1时的生存函数值),和原始数据CCDF在x=230处的0.3无法匹配。
解决方法
方法1:指定幂律曲线的绘制起始x值
修改powerPlot函数中幂律曲线的绘制代码,添加xmin参数,让曲线从拟合的xmin处开始绘制:
def powerPlot(fit): plt.figure() fig1 = fit.plot_ccdf(original_data=True, color='blue', linestyle='', marker='o', markersize=10, markerfacecolor='none', label='CCDF') # 指定xmin为拟合的xmin,让曲线从该点开始绘制 fit.power_law.plot_ccdf(ax=fig1, survival=True, color='red', linestyle='--', alpha=1, xmin=fit.xmin) fit.truncated_power_law.plot_ccdf(ax=fig1, color='purple', linestyle='--', alpha=1, xmin=fit.xmin)
方法2:手动生成x值并绘制
如果方法1不生效,可以手动生成从xmin开始的x数组,计算对应的生存函数值后直接绘制:
import numpy as np def powerPlot(fit): plt.figure() fig1 = fit.plot_ccdf(original_data=True, color='blue', linestyle='', marker='o', markersize=10, markerfacecolor='none', label='CCDF') # 手动生成x范围:从xmin到数据最大值 x = np.arange(fit.xmin, np.max(data), 1) # 计算幂律分布的生存函数(CCDF) y_power = fit.power_law.sf(x) # 绘制幂律曲线 plt.plot(x, y_power, color='red', linestyle='--', alpha=1, label='Power Law') # 截断幂律同理 y_trunc = fit.truncated_power_law.sf(x) plt.plot(x, y_trunc, color='purple', linestyle='--', alpha=1, label='Truncated Power Law') plt.legend()
额外验证点
可以在代码中添加print(fit2.xmin),确认拟合的xmin确实为230,避免参数传递错误。
内容的提问来源于stack exchange,提问作者Beans123
相关产品推荐
相关产品推荐

