如何在python中拟合任何非线性函数?

2024-05-19 07:56:56 发布

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

我已经检查了post1post2post3post4,但没有帮助。
我有一个关于特定植物的data,包括两个变量,称为“年龄”和“高度”。它们之间的相关性是非线性的。 enter image description here 为了适应一个模型,我假设一个解决方案如下:
如果非线性函数为
enter image description here

然后我们可以引入一个新变量kwhere
enter image description here

所以我们把第一个非线性函数变成了一个多元线性回归函数。基于此,我有以下代码:

data['K'] = data["Age"].pow(2)

x = data[["Age", "K"]]
y = data["Height"]

model = LinearRegression().fit(x, y)
print(model.score(x, y)) # = 0.9908571840250205

  1. 我做得对吗
  2. 如何处理三次函数和指数函数

谢谢


Tags: 函数模型agedatamodel高度post2post4
2条回答

希望你在这里使用SKLearn没有宗教热情,因为我建议的答案是完全忽略它

如果你有兴趣做回归分析,在那里你可以完全自主地使用拟合函数,我建议你直接使用最小二乘优化算法来驱动这类工作,你可以使用scipy


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

x, y = np.array([0,1,2,3,4,5]), np.array([0,1,4,9,16,25])

# initial_guess[i] maps to p[x] in function_to_fit, must be reasonable
initial_guess = [1, 1, 1] 

def function_to_fit(x, p):
    return pow(p[0]*x, 2) + p[1]*x + p[2]

def residuals(p,y,x):
    return y - function_to_fit(x,p)

cnsts = leastsq(
    residuals, 
    initial_guess, 
    args=(y, x)
)[0]

fig, ax = plt.subplots()
ax.plot(x, y, 'o')

xi = np.arange(0,10,0.1)
ax.plot(xi, [function_to_fit(x, cnsts) for x in xi])

plt.show()

graph of example code

现在这是一种数值方法来解决这个问题,所以我建议你花点时间来确保你理解这种方法的局限性——但是对于像这样的问题,我发现它们完全可以实现非线性数据集的功能化,而不必试着在一个线性流形中挥手

关于三次多项式

data['x2'] = data["Age"].pow(2)
data['x3'] = data["Age"].pow(3)

x = data[["Age", "x2","x3"]]
y = data["Height"]

model = LinearRegression().fit(x, y)
print(model.score(x, y))

您可以通过拟合log(y)来处理指数数据。 或者找到一些可以自动拟合多项式的库t.ex:https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html

相关问题 更多 >

    热门问题