如何在Python中模仿Excel的LOGEST函数

1 人关注

我对在Python中模仿Excel的LOGEST函数很感兴趣,但不知道从哪里开始。

5 个评论
看看excel对该函数的帮助,然后再看看一些数学教科书。
@SolarMike 我不明白你的评论和Python特定问题之间的关系。请你简要地解释一下?
@JamesPhillips excel被明确提及,并被标记为应遵循的标准。顺便问一下,使用相同的数据集,你的结果如何?
@SolarMike请与OP讨论。
python
excel
curve-fitting
Rhubarb
Rhubarb
发布于 2019-04-21
2 个回答
James Phillips
James Phillips
发布于 2020-06-12
已采纳
0 人赞同

下面是一个使用LOGEST的图形拟合器,如图所示 https://support.office.com/en-us/article/logest-function-f27462d8-3657-4030-866b-a272c1d18b4b

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7])
yData = numpy.array([1.1, 20.2, 30.3, 60.4, 50.0, 60.6, 70.7])
# LOGEST from https://support.office.com/en-us/article/logest-function-f27462d8-3657-4030-866b-a272c1d18b4b
def func(x, b, m):
    y = b * m**x
    return y
# these are the same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0])
# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)
modelPredictions = func(xData, *fittedParameters) 
absError = modelPredictions - yData
SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)
print()
##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)
    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')
    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)
    # now the model as a line plot
    axes.plot(xModel, yModel)
    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label
    plt.show()
    plt.close('all') # clean up after using pyplot
graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)
    
tommy.carstensen
tommy.carstensen
发布于 2020-06-12
0 人赞同

你可以用对数做线性回归,也可以用指数函数来拟合。在这里,我展示了两种解决方案,使用 scipy.stats.linregress scipy.optimal.curve_fit , respectively.

下面是一个来自 文件 on the function LOGEST in Excel from Microsoft:

Method using linregress :

from scipy.stats import linregress
import math
x = months = [11, 12, 13, 14, 15, 16]
y = units = [33100, 47300, 69000, 102000, 150000, 220000]
slope, intercept, r_value, p_value, std_err = linregress(
    list(map(math.log, y)),
print('m', math.exp(slope))
print('b', math.exp(intercept))

Output:

m 1.4632756281161756
b 495.3047701587278

Method using curve_fit:

from scipy.optimize import curve_fit
def f(x, b, m):
    return b * m ** x
popt, pcov = curve_fit(f, x, y)
print('m', popt[1])
print('b', popt[0])