如何在不使用多重拟合的情况下将最佳拟合线拟合到曲线,或者是否有其他方法

2024-09-28 21:54:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里发现了一个问题(Multivariate (polynomial) best fit curve in python?),我相信它可以回答我的问题(我没有任何曲线拟合经验,但我知道我的原始数据几乎总是这种形状),但我无法完全安装multipolyfit。我使用了“pip install myltipolyfit”,这很有效,但是当我运行这个脚本时,我得到一个回溯,说

回溯

"from core import multipolyfit, mk_model, mk_sympy_function
ModuleNotFoundError: No module named 'core'"

我想知道其他人是如何安装multipolyfit的

代码

import os
import csv
import pandas as pd
print('\n'*2)
import re
import matplotlib
import multipolyfit as mpf
from matplotlib.figure import Figure
from matplotlib import style
import numpy as np
import math
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
from scipy.stats import linregress

x = [190,195,200,205,210,215,220,225,230,235,240,245,250,255,260,265,270,275,280,285,290]
av_50 = [5.045, 5.05, 5.115, 5.23, 5.355, 5.42, 5.59, 5.77, 5.855, 5.8, 5.745, 5.725, 5.795, 5.835, 5.81, 5.73, 5.675, 5.65, 5.63, 5.555, 5.405]

def min_max_values(num_list):
    results_list = sorted(num_list)
    return results_list[0], results_list[-1]

min_x, max_x = min_max_values(x)

# Plotting
plt.axis([min_x - 5, max_x + 5, 0, 8])

x = np.array(x)
y = np.array(av_50)
plt.plot(x, y, 'kx')

stacked_x = numpy.array([x,x+1,x-1])
coeffs = mpf(stacked_x, y, deg) 
x2 = numpy.arange(min(x)-1, max(x)+1, .01) #use more points for a smoother plot
y2 = numpy.polyval(coeffs, x2) #Evaluates the polynomial for each x2 value
plt.plot(x2, y2, label="deg=3")

plt.show()

有效的替代方法

from numpy import arange
from pandas import read_csv
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt



# define the true objective function
def objective(x, a, b, c):
    return a * x + b * x**2 + c
 
sclk = [190,195,200,205,210,215,220,225,230,235,240,245,250,255,260,265,270,275,280,285,290]
av_50 = [5.045, 5.05, 5.115, 5.23, 5.355, 5.42, 5.59, 5.77, 5.855, 5.8, 5.745, 5.725, 5.795, 5.835, 5.81, 5.73, 5.675, 5.65, 5.63, 5.555, 5.405]


# curve fit
popt, _ = curve_fit(objective, sclk, av_50)

# summarize the parameter values
a, b, c = popt
print('y = %.5f * x + %.5f * x^2 + %.5f' % (a, b, c))

# plot input vs output
plt.scatter(sclk, av_50)

# define a sequence of inputs between the smallest and largest known inputs
sclk_line = arange(min(sclk), max(sclk), 1)

# calculate the output for the range
av_50_line = objective(sclk_line, a, b, c)

# create a line plot for the mapping function
plt.plot(sclk_line, av_50_line, '--', color='red')
plt.show()

Tags: thefromimportnumpyplotmatplotlibasline
1条回答
网友
1楼 · 发布于 2024-09-28 21:54:33

简单看一下PyPI上的multipolyfit包的代码,它很可能适用于python2

直接从GitHub上的存储库页面安装Python时,您可能会更幸运(在使用Python 3时;我不建议您使用Python 2):

pip install https://github.com/mrocklin/multipolyfit.git  force-reinstall

force-reinstall以覆盖当前安装)。 从那边的代码来看,至少那里的导入似乎与Python3兼容

然而,这个包裹已经有七到八年的历史了。它可能与当前的Python版本还有其他不兼容之处,鉴于过去几年缺乏活动,作者不太可能解决这些问题

因此,如果您的工作代码没有MultiplyFit,那么这可能是首选

相关问题 更多 >