import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
# 定义函数,单个自变量
def fun_exp(
X, k
):
a, x, b = X
Y = a * np.exp(k*x) + b
return Y
# 读取数据
df_test = pd.DataFrame(
[
[300, 0, 30, 300],
[300, 10, 30, 100]
])
# 提取自变量和因变量
X = df_test.iloc[:, :-1].values.T
Y = df_test.iloc[:, -1].values
X
# 拟合模型并输出参数
popt, pcov = curve_fit(fun_exp, X, Y)
print(popt)
# 定义函数,单个自变量+单个数值型控制变量
def fun_exp(
X, k1, k2
):
a, x, b, z1 = X
k = k1*z1 + k2
Y = a * np.exp(k*x) + b
return Y
# 读取数据
df_test = pd.DataFrame(
[
[300, 0, 30, 1, 300],
[300, 10, 30, 1, 100],
[300, 0, 30, 2, 300],
[300, 10, 30, 2, 200]
])
# 提取自变量和因变量
X = df_test.iloc[:, :-1].values.T
Y = df_test.iloc[:, -1].values
X
# 拟合模型并输出参数
popt, pcov = curve_fit(fun_exp, X, Y) # 如果实验数据未体现变量相关性 OptimizeWarning: Covariance could not be estimated
print(popt)
# 定义函数,单个自变量+单个序列(独热编码)控制变量
# curve_fit函数要求X中的元素都是可以转换为浮点数的数值
def fun_exp(
X, k1, k2, k3
):
a, x, b, z1, z2 = X
k = np.dot([k1, k2], [z1, z2]) + k3
Y = a * np.exp(k*x) + b
return Y
# 读取数据
df_test = pd.DataFrame(
[
[300, 0, 30, [1,0], 300],
[300, 10, 30, [1,0], 100],
[300, 0, 30, [0,1], 300],
[300, 10, 30, [0,1], 200]
])
# 提取自变量和因变量
# 将独热编码list拆分为两列
X = pd.concat(
[
df_test.iloc[:, :-2],
df_test.iloc[:, -2].apply(pd.Series)
],
axis=1
).values.T
Y = df_test.iloc[:, -1].values
# 拟合模型并输出参数
popt, pcov = curve_fit(fun_exp, X, Y) # curve_fit 函数要求输入的 X 必须是包含数值型元素的 NumPy 数组
print(popt)
print(fun_exp(X.T[1], *popt)) # 基本准确
标签:函数,300,30,df,popt,test,exp,单个,控制变量
From: https://blog.51cto.com/u_16055028/7860092