使用 lmfit 模型 - 函数将数据框作为参数
Use lmfit Model - function has dataframe as argument
我想使用 lmfit 来拟合我的数据。
我正在使用的函数只有一个参数 features
。 features
的内容会不一样(包括列和值),所以我无法初始化参数。
我尝试将数据框创建为 here,但我无法使用 guess
方法,因为这是针对 LorentzianModel
而我只想使用 Model
.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import lmfit
from sklearn.linear_model import LinearRegression
df = {'a': [0, 0.2, 0.3], 'b':[14, 10, 9], 'target':[100, 200, 300]}
df = pd.DataFrame(df)
X = df[['a', 'b']]
y = df[['target']]
model = LinearRegression().fit(X, y)
features = pd.DataFrame({"a": np.array([0, 0.11, 0.36]),
"b": np.array([10, 14, 8])})
def eval_custom(features):
res = model.predict(features)
return res
x_val = features[["a"]].values
def calling_func(features, x_val):
pred_custom = eval_custom(features)
df = pd.DataFrame({'x': np.squeeze(x_val), 'y': np.squeeze(pred_custom)})
themodel = lmfit.Model(eval_custom)
params = themodel.guess(df['y'], x=df['x'])
result = themodel.fit(df['y'], params, x = df['x'])
result.plot_fit()
calling_func(features, x_val)
模型函数需要将自变量和各个模型参数作为参数。您将所有这些包装到一个 pandas 数据帧中,然后发送它。不要那样做。
如果您需要根据模型的当前值创建数据框,请在您的模型函数中执行此操作。
此外:通用模型函数没有有效的 guess
函数。使用 model.make_params()
并且绝对,绝对(没有例外,从来没有)为每个参数提供实际的初始值。
我想使用 lmfit 来拟合我的数据。
我正在使用的函数只有一个参数 features
。 features
的内容会不一样(包括列和值),所以我无法初始化参数。
我尝试将数据框创建为 here,但我无法使用 guess
方法,因为这是针对 LorentzianModel
而我只想使用 Model
.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import lmfit
from sklearn.linear_model import LinearRegression
df = {'a': [0, 0.2, 0.3], 'b':[14, 10, 9], 'target':[100, 200, 300]}
df = pd.DataFrame(df)
X = df[['a', 'b']]
y = df[['target']]
model = LinearRegression().fit(X, y)
features = pd.DataFrame({"a": np.array([0, 0.11, 0.36]),
"b": np.array([10, 14, 8])})
def eval_custom(features):
res = model.predict(features)
return res
x_val = features[["a"]].values
def calling_func(features, x_val):
pred_custom = eval_custom(features)
df = pd.DataFrame({'x': np.squeeze(x_val), 'y': np.squeeze(pred_custom)})
themodel = lmfit.Model(eval_custom)
params = themodel.guess(df['y'], x=df['x'])
result = themodel.fit(df['y'], params, x = df['x'])
result.plot_fit()
calling_func(features, x_val)
模型函数需要将自变量和各个模型参数作为参数。您将所有这些包装到一个 pandas 数据帧中,然后发送它。不要那样做。
如果您需要根据模型的当前值创建数据框,请在您的模型函数中执行此操作。
此外:通用模型函数没有有效的 guess
函数。使用 model.make_params()
并且绝对,绝对(没有例外,从来没有)为每个参数提供实际的初始值。