matplotlib - 线性回归以拟合 Python 中的幂律
问题描述
我有两个数据集index_list
,frequency_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()
解决方案
下面的代码进行了以下更改:
- 为了使 scipy 函数正常工作,最好两者
index_list
都是freq_list
numpy 数组,而不是 Python 列表。此外,为了power
避免过快溢出,这些数组应该是float
类型(不是int
)。 - 至于
0
负幂会导致被零除的问题,从 开始是有意义index_list
的1
。 - 由于权力的原因,对于浮点数也会产生溢出。因此,为 . 添加边界是有意义的
curve_fit
。尤其b
应限制不超过 50 左右(最高值约为power(100000, b) giving an overflow when
be.g. is
100)
。此外,设置初始值有助于指导拟合过程(p0=...
)。 index_list
用asx
和power_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()
推荐阅读
- python - 获取具有另一个数据框条件的数据框列的最小值
- css - Gatsby 如何在 scss 中正确导入 svg 作为背景?
- javascript - 如何使用来自 node.js 的参数调用 .exe 文件
- groovy - 我正在尝试在 SoapUI groovy 中将 2019-11-22 11:29:34.56 转换为以秒 +1 分钟为单位的纪元时间戳
- javascript - 页面覆盖仅在首次加载时
- javascript - GDPR Cookie 合规性 Javascript 回调
- google-chrome - 在 Chrome chrome.storage.sync.set 中为数据集放置一个对象
- javascript - 将变量字符串视为文件名
- python - 频率排序问题 python - sorted() 没有给出我所期望的
- javascript - Jquery 表单提交:无限循环