首页 > 解决方案 > 线性回归以拟合 Python 中的幂律

问题描述

我有两个数据集index_listfrequency_list我在 loglog 图中绘制plt.loglog(index_list, freq_list)。现在我试图a*x^(-b)用线性回归拟合幂律。我希望曲线紧跟初始曲线,但以下代码似乎输出了类似的曲线,但在 y 轴上镜像。我怀疑我用的curve_fit不好。

为什么这条曲线镜像在 x 轴上,我怎样才能让它正确地适合我的初始曲线?

使用这些数据

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

f = open ("input.txt", "r")
index_list = []
freq_list = []
index = 0
for line in f:
    split_line = line.split()
    freq_list.append(int(split_line[1]))
    index_list.append(index)
    index += 1

plt.loglog(index_list, freq_list)
def power_law(x, a, b):
    return a * np.power(x, -b)

popt, pcov = curve_fit(power_law, index_list, freq_list)
plt.plot(index_list,  power_law(freq_list, *popt))
plt.show()

标签: matplotliblinear-regressionpower-law

解决方案


下面的代码进行了以下更改:

  • 为了使 scipy 函数正常工作,最好两者index_list都是freq_listnumpy 数组,而不是 Python 列表。此外,为了power避免过快溢出,这些数组应该是float类型(不是int)。
  • 至于0负幂会导致被零除的问题,从 开始是有意义index_list1
  • 由于权力的原因,对于浮点数也会产生溢出。因此,为 . 添加边界是有意义的curve_fit。尤其b应限制不超过 50 左右(最高值约为power(100000, b) giving an overflow when b e.g. is100 )。此外,设置初始值有助于指导拟合过程(p0=...)。
  • index_list用asxpower_law(freq_list, ...)as绘制图y会产生一条非常奇怪的曲线。x绘图和函数必须使用相同的内容。

请注意,调用plt.loglog()会将绘图的两个轴都更改为对数。同一轴上的所有后续绘图将继续使用对数刻度。

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd
import numpy as np

def power_law(x, a, b):
    return a * np.power(x, -b)

df = pd.read_csv("https://norvig.com/google-books-common-words.txt", delim_whitespace=True, header=None)

index_list = df.index.to_numpy(dtype=float) + 1
freq_list = df[1].to_numpy(dtype=float)

plt.loglog(index_list, freq_list, label='given data')

popt, pcov = curve_fit(power_law, index_list, freq_list, p0=[1, 1], bounds=[[1e-3, 1e-3], [1e20, 50]])

plt.plot(index_list, power_law(index_list, *popt), label='power law')
plt.legend()
plt.show()

示例图


推荐阅读