Skip to main content
 首页 » 编程设计

python之如何使用 yscale ('log' 拟合曲线)之Python

2025年05月04日11tuyile006

我一直在尝试将一些数据拟合到特定集合 x 和 y 的最佳拟合线。 我尝试了很多次,但都没有成功,而且我似乎无法找到一种方法来使用 yscale('log') 和 xscale('log') 来拟合数据。我得到了这个奇怪的结果,但我似乎无法找到为什么它会给出这个奇怪的 [result]

[结果]:https://www.dropbox.com/s/g6m4f8wh7r7jffg/Imagem%20sem%20t%C3%ADtulo.png?dl=0 .

我的代码:

#!/usr/bin/env python  
# import the necessary modules 
import numpy as np 
import matplotlib.pyplot as plt 
 
# Generate x and y values which the curve will be fitted to 
# (In practical cases, these should be read in) 
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048] 
y = [497775, 150760, 50929, 19697, 8520, 3948, 1812, 710, 214, 57, 18, 4] 
 
p = np.polyfit(x,y,1)  
plt.plot(x, np.polyval(p,x), 'r-') 
plt.plot(x, y) 
plt.yscale('log') 
plt.xscale('log') 
plt.show() 

我有一种预感,这是因为我使用的是多元值,但我找不到如何计算它的对数。你能帮我吗?我是新手,需要帮助!

请您参考如下方法:

在双对数图上显示为线性的东西不是线性函数,而是指数函数。

您获得了最佳拟合线:

y = a * x + b 

但您想要的是最适合以下形式的指数函数:

y = a * x**k 

有很多方法可以做到这一点。使用 polyfit 是一种很好的方法,但您需要在“对数空间”中调整该行。换句话说,将 x 的对数与 y 的对数拟合。

例如,根据您的代码:

import numpy as np 
import matplotlib.pyplot as plt 
 
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048] 
y = [497775, 150760, 50929, 19697, 8520, 3948, 1812, 710, 214, 57, 18, 4] 
 
logx, logy = np.log(x), np.log(y) 
 
p = np.polyfit(logx, logy, 1) 
y_fit = np.exp(np.polyval(p, logx)) 
 
plt.plot(x, y_fit, 'r-') 
plt.plot(x, y) 
plt.yscale('log') 
plt.xscale('log') 
plt.show()